xref: /openbmc/linux/drivers/scsi/lpfc/lpfc_sli.c (revision 77a87824)
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 supported on 32-bit x86 - use do_div */
2951 	do_div(cnt, phba->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 * phba->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 (phba->cfg_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 sli_mode "
4673 				"parameter (%d) to auto (0).\n",
4674 				phba->cfg_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 sli_mode parameter: %d.\n",
4685 				phba->cfg_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 && phba->cfg_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 	else if (rc && mode == 2)
4700 		rc = lpfc_sli_config_port(phba, 3);
4701 	if (rc)
4702 		goto lpfc_sli_hba_setup_error;
4703 
4704 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
4705 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
4706 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
4707 		if (!rc) {
4708 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4709 					"2709 This device supports "
4710 					"Advanced Error Reporting (AER)\n");
4711 			spin_lock_irq(&phba->hbalock);
4712 			phba->hba_flag |= HBA_AER_ENABLED;
4713 			spin_unlock_irq(&phba->hbalock);
4714 		} else {
4715 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4716 					"2708 This device does not support "
4717 					"Advanced Error Reporting (AER): %d\n",
4718 					rc);
4719 			phba->cfg_aer_support = 0;
4720 		}
4721 	}
4722 
4723 	if (phba->sli_rev == 3) {
4724 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
4725 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
4726 	} else {
4727 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
4728 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
4729 		phba->sli3_options = 0;
4730 	}
4731 
4732 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4733 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
4734 			phba->sli_rev, phba->max_vpi);
4735 	rc = lpfc_sli_ring_map(phba);
4736 
4737 	if (rc)
4738 		goto lpfc_sli_hba_setup_error;
4739 
4740 	/* Initialize VPIs. */
4741 	if (phba->sli_rev == LPFC_SLI_REV3) {
4742 		/*
4743 		 * The VPI bitmask and physical ID array are allocated
4744 		 * and initialized once only - at driver load.  A port
4745 		 * reset doesn't need to reinitialize this memory.
4746 		 */
4747 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
4748 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
4749 			phba->vpi_bmask = kzalloc(longs * sizeof(unsigned long),
4750 						  GFP_KERNEL);
4751 			if (!phba->vpi_bmask) {
4752 				rc = -ENOMEM;
4753 				goto lpfc_sli_hba_setup_error;
4754 			}
4755 
4756 			phba->vpi_ids = kzalloc(
4757 					(phba->max_vpi+1) * sizeof(uint16_t),
4758 					GFP_KERNEL);
4759 			if (!phba->vpi_ids) {
4760 				kfree(phba->vpi_bmask);
4761 				rc = -ENOMEM;
4762 				goto lpfc_sli_hba_setup_error;
4763 			}
4764 			for (i = 0; i < phba->max_vpi; i++)
4765 				phba->vpi_ids[i] = i;
4766 		}
4767 	}
4768 
4769 	/* Init HBQs */
4770 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
4771 		rc = lpfc_sli_hbq_setup(phba);
4772 		if (rc)
4773 			goto lpfc_sli_hba_setup_error;
4774 	}
4775 	spin_lock_irq(&phba->hbalock);
4776 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
4777 	spin_unlock_irq(&phba->hbalock);
4778 
4779 	rc = lpfc_config_port_post(phba);
4780 	if (rc)
4781 		goto lpfc_sli_hba_setup_error;
4782 
4783 	return rc;
4784 
4785 lpfc_sli_hba_setup_error:
4786 	phba->link_state = LPFC_HBA_ERROR;
4787 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4788 			"0445 Firmware initialization failed\n");
4789 	return rc;
4790 }
4791 
4792 /**
4793  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
4794  * @phba: Pointer to HBA context object.
4795  * @mboxq: mailbox pointer.
4796  * This function issue a dump mailbox command to read config region
4797  * 23 and parse the records in the region and populate driver
4798  * data structure.
4799  **/
4800 static int
4801 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
4802 {
4803 	LPFC_MBOXQ_t *mboxq;
4804 	struct lpfc_dmabuf *mp;
4805 	struct lpfc_mqe *mqe;
4806 	uint32_t data_length;
4807 	int rc;
4808 
4809 	/* Program the default value of vlan_id and fc_map */
4810 	phba->valid_vlan = 0;
4811 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
4812 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
4813 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
4814 
4815 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4816 	if (!mboxq)
4817 		return -ENOMEM;
4818 
4819 	mqe = &mboxq->u.mqe;
4820 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
4821 		rc = -ENOMEM;
4822 		goto out_free_mboxq;
4823 	}
4824 
4825 	mp = (struct lpfc_dmabuf *) mboxq->context1;
4826 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4827 
4828 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
4829 			"(%d):2571 Mailbox cmd x%x Status x%x "
4830 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
4831 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
4832 			"CQ: x%x x%x x%x x%x\n",
4833 			mboxq->vport ? mboxq->vport->vpi : 0,
4834 			bf_get(lpfc_mqe_command, mqe),
4835 			bf_get(lpfc_mqe_status, mqe),
4836 			mqe->un.mb_words[0], mqe->un.mb_words[1],
4837 			mqe->un.mb_words[2], mqe->un.mb_words[3],
4838 			mqe->un.mb_words[4], mqe->un.mb_words[5],
4839 			mqe->un.mb_words[6], mqe->un.mb_words[7],
4840 			mqe->un.mb_words[8], mqe->un.mb_words[9],
4841 			mqe->un.mb_words[10], mqe->un.mb_words[11],
4842 			mqe->un.mb_words[12], mqe->un.mb_words[13],
4843 			mqe->un.mb_words[14], mqe->un.mb_words[15],
4844 			mqe->un.mb_words[16], mqe->un.mb_words[50],
4845 			mboxq->mcqe.word0,
4846 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
4847 			mboxq->mcqe.trailer);
4848 
4849 	if (rc) {
4850 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
4851 		kfree(mp);
4852 		rc = -EIO;
4853 		goto out_free_mboxq;
4854 	}
4855 	data_length = mqe->un.mb_words[5];
4856 	if (data_length > DMP_RGN23_SIZE) {
4857 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
4858 		kfree(mp);
4859 		rc = -EIO;
4860 		goto out_free_mboxq;
4861 	}
4862 
4863 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
4864 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
4865 	kfree(mp);
4866 	rc = 0;
4867 
4868 out_free_mboxq:
4869 	mempool_free(mboxq, phba->mbox_mem_pool);
4870 	return rc;
4871 }
4872 
4873 /**
4874  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
4875  * @phba: pointer to lpfc hba data structure.
4876  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
4877  * @vpd: pointer to the memory to hold resulting port vpd data.
4878  * @vpd_size: On input, the number of bytes allocated to @vpd.
4879  *	      On output, the number of data bytes in @vpd.
4880  *
4881  * This routine executes a READ_REV SLI4 mailbox command.  In
4882  * addition, this routine gets the port vpd data.
4883  *
4884  * Return codes
4885  * 	0 - successful
4886  * 	-ENOMEM - could not allocated memory.
4887  **/
4888 static int
4889 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
4890 		    uint8_t *vpd, uint32_t *vpd_size)
4891 {
4892 	int rc = 0;
4893 	uint32_t dma_size;
4894 	struct lpfc_dmabuf *dmabuf;
4895 	struct lpfc_mqe *mqe;
4896 
4897 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
4898 	if (!dmabuf)
4899 		return -ENOMEM;
4900 
4901 	/*
4902 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
4903 	 * mailbox command.
4904 	 */
4905 	dma_size = *vpd_size;
4906 	dmabuf->virt = dma_zalloc_coherent(&phba->pcidev->dev, dma_size,
4907 					   &dmabuf->phys, GFP_KERNEL);
4908 	if (!dmabuf->virt) {
4909 		kfree(dmabuf);
4910 		return -ENOMEM;
4911 	}
4912 
4913 	/*
4914 	 * The SLI4 implementation of READ_REV conflicts at word1,
4915 	 * bits 31:16 and SLI4 adds vpd functionality not present
4916 	 * in SLI3.  This code corrects the conflicts.
4917 	 */
4918 	lpfc_read_rev(phba, mboxq);
4919 	mqe = &mboxq->u.mqe;
4920 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
4921 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
4922 	mqe->un.read_rev.word1 &= 0x0000FFFF;
4923 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
4924 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
4925 
4926 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4927 	if (rc) {
4928 		dma_free_coherent(&phba->pcidev->dev, dma_size,
4929 				  dmabuf->virt, dmabuf->phys);
4930 		kfree(dmabuf);
4931 		return -EIO;
4932 	}
4933 
4934 	/*
4935 	 * The available vpd length cannot be bigger than the
4936 	 * DMA buffer passed to the port.  Catch the less than
4937 	 * case and update the caller's size.
4938 	 */
4939 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
4940 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
4941 
4942 	memcpy(vpd, dmabuf->virt, *vpd_size);
4943 
4944 	dma_free_coherent(&phba->pcidev->dev, dma_size,
4945 			  dmabuf->virt, dmabuf->phys);
4946 	kfree(dmabuf);
4947 	return 0;
4948 }
4949 
4950 /**
4951  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
4952  * @phba: pointer to lpfc hba data structure.
4953  *
4954  * This routine retrieves SLI4 device physical port name this PCI function
4955  * is attached to.
4956  *
4957  * Return codes
4958  *      0 - successful
4959  *      otherwise - failed to retrieve physical port name
4960  **/
4961 static int
4962 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
4963 {
4964 	LPFC_MBOXQ_t *mboxq;
4965 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
4966 	struct lpfc_controller_attribute *cntl_attr;
4967 	struct lpfc_mbx_get_port_name *get_port_name;
4968 	void *virtaddr = NULL;
4969 	uint32_t alloclen, reqlen;
4970 	uint32_t shdr_status, shdr_add_status;
4971 	union lpfc_sli4_cfg_shdr *shdr;
4972 	char cport_name = 0;
4973 	int rc;
4974 
4975 	/* We assume nothing at this point */
4976 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
4977 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
4978 
4979 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4980 	if (!mboxq)
4981 		return -ENOMEM;
4982 	/* obtain link type and link number via READ_CONFIG */
4983 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
4984 	lpfc_sli4_read_config(phba);
4985 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
4986 		goto retrieve_ppname;
4987 
4988 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
4989 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
4990 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
4991 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
4992 			LPFC_SLI4_MBX_NEMBED);
4993 	if (alloclen < reqlen) {
4994 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4995 				"3084 Allocated DMA memory size (%d) is "
4996 				"less than the requested DMA memory size "
4997 				"(%d)\n", alloclen, reqlen);
4998 		rc = -ENOMEM;
4999 		goto out_free_mboxq;
5000 	}
5001 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5002 	virtaddr = mboxq->sge_array->addr[0];
5003 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5004 	shdr = &mbx_cntl_attr->cfg_shdr;
5005 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5006 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5007 	if (shdr_status || shdr_add_status || rc) {
5008 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5009 				"3085 Mailbox x%x (x%x/x%x) failed, "
5010 				"rc:x%x, status:x%x, add_status:x%x\n",
5011 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5012 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5013 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5014 				rc, shdr_status, shdr_add_status);
5015 		rc = -ENXIO;
5016 		goto out_free_mboxq;
5017 	}
5018 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5019 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5020 	phba->sli4_hba.lnk_info.lnk_tp =
5021 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5022 	phba->sli4_hba.lnk_info.lnk_no =
5023 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5024 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5025 			"3086 lnk_type:%d, lnk_numb:%d\n",
5026 			phba->sli4_hba.lnk_info.lnk_tp,
5027 			phba->sli4_hba.lnk_info.lnk_no);
5028 
5029 retrieve_ppname:
5030 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5031 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
5032 		sizeof(struct lpfc_mbx_get_port_name) -
5033 		sizeof(struct lpfc_sli4_cfg_mhdr),
5034 		LPFC_SLI4_MBX_EMBED);
5035 	get_port_name = &mboxq->u.mqe.un.get_port_name;
5036 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5037 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
5038 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
5039 		phba->sli4_hba.lnk_info.lnk_tp);
5040 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5041 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5042 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5043 	if (shdr_status || shdr_add_status || rc) {
5044 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5045 				"3087 Mailbox x%x (x%x/x%x) failed: "
5046 				"rc:x%x, status:x%x, add_status:x%x\n",
5047 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5048 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5049 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5050 				rc, shdr_status, shdr_add_status);
5051 		rc = -ENXIO;
5052 		goto out_free_mboxq;
5053 	}
5054 	switch (phba->sli4_hba.lnk_info.lnk_no) {
5055 	case LPFC_LINK_NUMBER_0:
5056 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
5057 				&get_port_name->u.response);
5058 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5059 		break;
5060 	case LPFC_LINK_NUMBER_1:
5061 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
5062 				&get_port_name->u.response);
5063 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5064 		break;
5065 	case LPFC_LINK_NUMBER_2:
5066 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
5067 				&get_port_name->u.response);
5068 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5069 		break;
5070 	case LPFC_LINK_NUMBER_3:
5071 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
5072 				&get_port_name->u.response);
5073 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5074 		break;
5075 	default:
5076 		break;
5077 	}
5078 
5079 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
5080 		phba->Port[0] = cport_name;
5081 		phba->Port[1] = '\0';
5082 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5083 				"3091 SLI get port name: %s\n", phba->Port);
5084 	}
5085 
5086 out_free_mboxq:
5087 	if (rc != MBX_TIMEOUT) {
5088 		if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5089 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
5090 		else
5091 			mempool_free(mboxq, phba->mbox_mem_pool);
5092 	}
5093 	return rc;
5094 }
5095 
5096 /**
5097  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
5098  * @phba: pointer to lpfc hba data structure.
5099  *
5100  * This routine is called to explicitly arm the SLI4 device's completion and
5101  * event queues
5102  **/
5103 static void
5104 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
5105 {
5106 	int fcp_eqidx;
5107 
5108 	lpfc_sli4_cq_release(phba->sli4_hba.mbx_cq, LPFC_QUEUE_REARM);
5109 	lpfc_sli4_cq_release(phba->sli4_hba.els_cq, LPFC_QUEUE_REARM);
5110 	fcp_eqidx = 0;
5111 	if (phba->sli4_hba.fcp_cq) {
5112 		do {
5113 			lpfc_sli4_cq_release(phba->sli4_hba.fcp_cq[fcp_eqidx],
5114 					     LPFC_QUEUE_REARM);
5115 		} while (++fcp_eqidx < phba->cfg_fcp_io_channel);
5116 	}
5117 
5118 	if (phba->cfg_fof)
5119 		lpfc_sli4_cq_release(phba->sli4_hba.oas_cq, LPFC_QUEUE_REARM);
5120 
5121 	if (phba->sli4_hba.hba_eq) {
5122 		for (fcp_eqidx = 0; fcp_eqidx < phba->cfg_fcp_io_channel;
5123 		     fcp_eqidx++)
5124 			lpfc_sli4_eq_release(phba->sli4_hba.hba_eq[fcp_eqidx],
5125 					     LPFC_QUEUE_REARM);
5126 	}
5127 
5128 	if (phba->cfg_fof)
5129 		lpfc_sli4_eq_release(phba->sli4_hba.fof_eq, LPFC_QUEUE_REARM);
5130 }
5131 
5132 /**
5133  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
5134  * @phba: Pointer to HBA context object.
5135  * @type: The resource extent type.
5136  * @extnt_count: buffer to hold port available extent count.
5137  * @extnt_size: buffer to hold element count per extent.
5138  *
5139  * This function calls the port and retrievs the number of available
5140  * extents and their size for a particular extent type.
5141  *
5142  * Returns: 0 if successful.  Nonzero otherwise.
5143  **/
5144 int
5145 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
5146 			       uint16_t *extnt_count, uint16_t *extnt_size)
5147 {
5148 	int rc = 0;
5149 	uint32_t length;
5150 	uint32_t mbox_tmo;
5151 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
5152 	LPFC_MBOXQ_t *mbox;
5153 
5154 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5155 	if (!mbox)
5156 		return -ENOMEM;
5157 
5158 	/* Find out how many extents are available for this resource type */
5159 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
5160 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5161 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5162 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
5163 			 length, LPFC_SLI4_MBX_EMBED);
5164 
5165 	/* Send an extents count of 0 - the GET doesn't use it. */
5166 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5167 					LPFC_SLI4_MBX_EMBED);
5168 	if (unlikely(rc)) {
5169 		rc = -EIO;
5170 		goto err_exit;
5171 	}
5172 
5173 	if (!phba->sli4_hba.intr_enable)
5174 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5175 	else {
5176 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5177 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5178 	}
5179 	if (unlikely(rc)) {
5180 		rc = -EIO;
5181 		goto err_exit;
5182 	}
5183 
5184 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
5185 	if (bf_get(lpfc_mbox_hdr_status,
5186 		   &rsrc_info->header.cfg_shdr.response)) {
5187 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5188 				"2930 Failed to get resource extents "
5189 				"Status 0x%x Add'l Status 0x%x\n",
5190 				bf_get(lpfc_mbox_hdr_status,
5191 				       &rsrc_info->header.cfg_shdr.response),
5192 				bf_get(lpfc_mbox_hdr_add_status,
5193 				       &rsrc_info->header.cfg_shdr.response));
5194 		rc = -EIO;
5195 		goto err_exit;
5196 	}
5197 
5198 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
5199 			      &rsrc_info->u.rsp);
5200 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
5201 			     &rsrc_info->u.rsp);
5202 
5203 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5204 			"3162 Retrieved extents type-%d from port: count:%d, "
5205 			"size:%d\n", type, *extnt_count, *extnt_size);
5206 
5207 err_exit:
5208 	mempool_free(mbox, phba->mbox_mem_pool);
5209 	return rc;
5210 }
5211 
5212 /**
5213  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
5214  * @phba: Pointer to HBA context object.
5215  * @type: The extent type to check.
5216  *
5217  * This function reads the current available extents from the port and checks
5218  * if the extent count or extent size has changed since the last access.
5219  * Callers use this routine post port reset to understand if there is a
5220  * extent reprovisioning requirement.
5221  *
5222  * Returns:
5223  *   -Error: error indicates problem.
5224  *   1: Extent count or size has changed.
5225  *   0: No changes.
5226  **/
5227 static int
5228 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
5229 {
5230 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
5231 	uint16_t size_diff, rsrc_ext_size;
5232 	int rc = 0;
5233 	struct lpfc_rsrc_blks *rsrc_entry;
5234 	struct list_head *rsrc_blk_list = NULL;
5235 
5236 	size_diff = 0;
5237 	curr_ext_cnt = 0;
5238 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5239 					    &rsrc_ext_cnt,
5240 					    &rsrc_ext_size);
5241 	if (unlikely(rc))
5242 		return -EIO;
5243 
5244 	switch (type) {
5245 	case LPFC_RSC_TYPE_FCOE_RPI:
5246 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5247 		break;
5248 	case LPFC_RSC_TYPE_FCOE_VPI:
5249 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
5250 		break;
5251 	case LPFC_RSC_TYPE_FCOE_XRI:
5252 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5253 		break;
5254 	case LPFC_RSC_TYPE_FCOE_VFI:
5255 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5256 		break;
5257 	default:
5258 		break;
5259 	}
5260 
5261 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
5262 		curr_ext_cnt++;
5263 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
5264 			size_diff++;
5265 	}
5266 
5267 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
5268 		rc = 1;
5269 
5270 	return rc;
5271 }
5272 
5273 /**
5274  * lpfc_sli4_cfg_post_extnts -
5275  * @phba: Pointer to HBA context object.
5276  * @extnt_cnt - number of available extents.
5277  * @type - the extent type (rpi, xri, vfi, vpi).
5278  * @emb - buffer to hold either MBX_EMBED or MBX_NEMBED operation.
5279  * @mbox - pointer to the caller's allocated mailbox structure.
5280  *
5281  * This function executes the extents allocation request.  It also
5282  * takes care of the amount of memory needed to allocate or get the
5283  * allocated extents. It is the caller's responsibility to evaluate
5284  * the response.
5285  *
5286  * Returns:
5287  *   -Error:  Error value describes the condition found.
5288  *   0: if successful
5289  **/
5290 static int
5291 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
5292 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
5293 {
5294 	int rc = 0;
5295 	uint32_t req_len;
5296 	uint32_t emb_len;
5297 	uint32_t alloc_len, mbox_tmo;
5298 
5299 	/* Calculate the total requested length of the dma memory */
5300 	req_len = extnt_cnt * sizeof(uint16_t);
5301 
5302 	/*
5303 	 * Calculate the size of an embedded mailbox.  The uint32_t
5304 	 * accounts for extents-specific word.
5305 	 */
5306 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
5307 		sizeof(uint32_t);
5308 
5309 	/*
5310 	 * Presume the allocation and response will fit into an embedded
5311 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
5312 	 */
5313 	*emb = LPFC_SLI4_MBX_EMBED;
5314 	if (req_len > emb_len) {
5315 		req_len = extnt_cnt * sizeof(uint16_t) +
5316 			sizeof(union lpfc_sli4_cfg_shdr) +
5317 			sizeof(uint32_t);
5318 		*emb = LPFC_SLI4_MBX_NEMBED;
5319 	}
5320 
5321 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5322 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
5323 				     req_len, *emb);
5324 	if (alloc_len < req_len) {
5325 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5326 			"2982 Allocated DMA memory size (x%x) is "
5327 			"less than the requested DMA memory "
5328 			"size (x%x)\n", alloc_len, req_len);
5329 		return -ENOMEM;
5330 	}
5331 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
5332 	if (unlikely(rc))
5333 		return -EIO;
5334 
5335 	if (!phba->sli4_hba.intr_enable)
5336 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5337 	else {
5338 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5339 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5340 	}
5341 
5342 	if (unlikely(rc))
5343 		rc = -EIO;
5344 	return rc;
5345 }
5346 
5347 /**
5348  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
5349  * @phba: Pointer to HBA context object.
5350  * @type:  The resource extent type to allocate.
5351  *
5352  * This function allocates the number of elements for the specified
5353  * resource type.
5354  **/
5355 static int
5356 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
5357 {
5358 	bool emb = false;
5359 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
5360 	uint16_t rsrc_id, rsrc_start, j, k;
5361 	uint16_t *ids;
5362 	int i, rc;
5363 	unsigned long longs;
5364 	unsigned long *bmask;
5365 	struct lpfc_rsrc_blks *rsrc_blks;
5366 	LPFC_MBOXQ_t *mbox;
5367 	uint32_t length;
5368 	struct lpfc_id_range *id_array = NULL;
5369 	void *virtaddr = NULL;
5370 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
5371 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
5372 	struct list_head *ext_blk_list;
5373 
5374 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5375 					    &rsrc_cnt,
5376 					    &rsrc_size);
5377 	if (unlikely(rc))
5378 		return -EIO;
5379 
5380 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
5381 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5382 			"3009 No available Resource Extents "
5383 			"for resource type 0x%x: Count: 0x%x, "
5384 			"Size 0x%x\n", type, rsrc_cnt,
5385 			rsrc_size);
5386 		return -ENOMEM;
5387 	}
5388 
5389 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
5390 			"2903 Post resource extents type-0x%x: "
5391 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
5392 
5393 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5394 	if (!mbox)
5395 		return -ENOMEM;
5396 
5397 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
5398 	if (unlikely(rc)) {
5399 		rc = -EIO;
5400 		goto err_exit;
5401 	}
5402 
5403 	/*
5404 	 * Figure out where the response is located.  Then get local pointers
5405 	 * to the response data.  The port does not guarantee to respond to
5406 	 * all extents counts request so update the local variable with the
5407 	 * allocated count from the port.
5408 	 */
5409 	if (emb == LPFC_SLI4_MBX_EMBED) {
5410 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
5411 		id_array = &rsrc_ext->u.rsp.id[0];
5412 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
5413 	} else {
5414 		virtaddr = mbox->sge_array->addr[0];
5415 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
5416 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
5417 		id_array = &n_rsrc->id;
5418 	}
5419 
5420 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
5421 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
5422 
5423 	/*
5424 	 * Based on the resource size and count, correct the base and max
5425 	 * resource values.
5426 	 */
5427 	length = sizeof(struct lpfc_rsrc_blks);
5428 	switch (type) {
5429 	case LPFC_RSC_TYPE_FCOE_RPI:
5430 		phba->sli4_hba.rpi_bmask = kzalloc(longs *
5431 						   sizeof(unsigned long),
5432 						   GFP_KERNEL);
5433 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
5434 			rc = -ENOMEM;
5435 			goto err_exit;
5436 		}
5437 		phba->sli4_hba.rpi_ids = kzalloc(rsrc_id_cnt *
5438 						 sizeof(uint16_t),
5439 						 GFP_KERNEL);
5440 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
5441 			kfree(phba->sli4_hba.rpi_bmask);
5442 			rc = -ENOMEM;
5443 			goto err_exit;
5444 		}
5445 
5446 		/*
5447 		 * The next_rpi was initialized with the maximum available
5448 		 * count but the port may allocate a smaller number.  Catch
5449 		 * that case and update the next_rpi.
5450 		 */
5451 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
5452 
5453 		/* Initialize local ptrs for common extent processing later. */
5454 		bmask = phba->sli4_hba.rpi_bmask;
5455 		ids = phba->sli4_hba.rpi_ids;
5456 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5457 		break;
5458 	case LPFC_RSC_TYPE_FCOE_VPI:
5459 		phba->vpi_bmask = kzalloc(longs *
5460 					  sizeof(unsigned long),
5461 					  GFP_KERNEL);
5462 		if (unlikely(!phba->vpi_bmask)) {
5463 			rc = -ENOMEM;
5464 			goto err_exit;
5465 		}
5466 		phba->vpi_ids = kzalloc(rsrc_id_cnt *
5467 					 sizeof(uint16_t),
5468 					 GFP_KERNEL);
5469 		if (unlikely(!phba->vpi_ids)) {
5470 			kfree(phba->vpi_bmask);
5471 			rc = -ENOMEM;
5472 			goto err_exit;
5473 		}
5474 
5475 		/* Initialize local ptrs for common extent processing later. */
5476 		bmask = phba->vpi_bmask;
5477 		ids = phba->vpi_ids;
5478 		ext_blk_list = &phba->lpfc_vpi_blk_list;
5479 		break;
5480 	case LPFC_RSC_TYPE_FCOE_XRI:
5481 		phba->sli4_hba.xri_bmask = kzalloc(longs *
5482 						   sizeof(unsigned long),
5483 						   GFP_KERNEL);
5484 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
5485 			rc = -ENOMEM;
5486 			goto err_exit;
5487 		}
5488 		phba->sli4_hba.max_cfg_param.xri_used = 0;
5489 		phba->sli4_hba.xri_ids = kzalloc(rsrc_id_cnt *
5490 						 sizeof(uint16_t),
5491 						 GFP_KERNEL);
5492 		if (unlikely(!phba->sli4_hba.xri_ids)) {
5493 			kfree(phba->sli4_hba.xri_bmask);
5494 			rc = -ENOMEM;
5495 			goto err_exit;
5496 		}
5497 
5498 		/* Initialize local ptrs for common extent processing later. */
5499 		bmask = phba->sli4_hba.xri_bmask;
5500 		ids = phba->sli4_hba.xri_ids;
5501 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5502 		break;
5503 	case LPFC_RSC_TYPE_FCOE_VFI:
5504 		phba->sli4_hba.vfi_bmask = kzalloc(longs *
5505 						   sizeof(unsigned long),
5506 						   GFP_KERNEL);
5507 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
5508 			rc = -ENOMEM;
5509 			goto err_exit;
5510 		}
5511 		phba->sli4_hba.vfi_ids = kzalloc(rsrc_id_cnt *
5512 						 sizeof(uint16_t),
5513 						 GFP_KERNEL);
5514 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
5515 			kfree(phba->sli4_hba.vfi_bmask);
5516 			rc = -ENOMEM;
5517 			goto err_exit;
5518 		}
5519 
5520 		/* Initialize local ptrs for common extent processing later. */
5521 		bmask = phba->sli4_hba.vfi_bmask;
5522 		ids = phba->sli4_hba.vfi_ids;
5523 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5524 		break;
5525 	default:
5526 		/* Unsupported Opcode.  Fail call. */
5527 		id_array = NULL;
5528 		bmask = NULL;
5529 		ids = NULL;
5530 		ext_blk_list = NULL;
5531 		goto err_exit;
5532 	}
5533 
5534 	/*
5535 	 * Complete initializing the extent configuration with the
5536 	 * allocated ids assigned to this function.  The bitmask serves
5537 	 * as an index into the array and manages the available ids.  The
5538 	 * array just stores the ids communicated to the port via the wqes.
5539 	 */
5540 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
5541 		if ((i % 2) == 0)
5542 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
5543 					 &id_array[k]);
5544 		else
5545 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
5546 					 &id_array[k]);
5547 
5548 		rsrc_blks = kzalloc(length, GFP_KERNEL);
5549 		if (unlikely(!rsrc_blks)) {
5550 			rc = -ENOMEM;
5551 			kfree(bmask);
5552 			kfree(ids);
5553 			goto err_exit;
5554 		}
5555 		rsrc_blks->rsrc_start = rsrc_id;
5556 		rsrc_blks->rsrc_size = rsrc_size;
5557 		list_add_tail(&rsrc_blks->list, ext_blk_list);
5558 		rsrc_start = rsrc_id;
5559 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0))
5560 			phba->sli4_hba.scsi_xri_start = rsrc_start +
5561 				lpfc_sli4_get_els_iocb_cnt(phba);
5562 
5563 		while (rsrc_id < (rsrc_start + rsrc_size)) {
5564 			ids[j] = rsrc_id;
5565 			rsrc_id++;
5566 			j++;
5567 		}
5568 		/* Entire word processed.  Get next word.*/
5569 		if ((i % 2) == 1)
5570 			k++;
5571 	}
5572  err_exit:
5573 	lpfc_sli4_mbox_cmd_free(phba, mbox);
5574 	return rc;
5575 }
5576 
5577 /**
5578  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
5579  * @phba: Pointer to HBA context object.
5580  * @type: the extent's type.
5581  *
5582  * This function deallocates all extents of a particular resource type.
5583  * SLI4 does not allow for deallocating a particular extent range.  It
5584  * is the caller's responsibility to release all kernel memory resources.
5585  **/
5586 static int
5587 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
5588 {
5589 	int rc;
5590 	uint32_t length, mbox_tmo = 0;
5591 	LPFC_MBOXQ_t *mbox;
5592 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
5593 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
5594 
5595 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5596 	if (!mbox)
5597 		return -ENOMEM;
5598 
5599 	/*
5600 	 * This function sends an embedded mailbox because it only sends the
5601 	 * the resource type.  All extents of this type are released by the
5602 	 * port.
5603 	 */
5604 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
5605 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5606 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5607 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
5608 			 length, LPFC_SLI4_MBX_EMBED);
5609 
5610 	/* Send an extents count of 0 - the dealloc doesn't use it. */
5611 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5612 					LPFC_SLI4_MBX_EMBED);
5613 	if (unlikely(rc)) {
5614 		rc = -EIO;
5615 		goto out_free_mbox;
5616 	}
5617 	if (!phba->sli4_hba.intr_enable)
5618 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5619 	else {
5620 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5621 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5622 	}
5623 	if (unlikely(rc)) {
5624 		rc = -EIO;
5625 		goto out_free_mbox;
5626 	}
5627 
5628 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
5629 	if (bf_get(lpfc_mbox_hdr_status,
5630 		   &dealloc_rsrc->header.cfg_shdr.response)) {
5631 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5632 				"2919 Failed to release resource extents "
5633 				"for type %d - Status 0x%x Add'l Status 0x%x. "
5634 				"Resource memory not released.\n",
5635 				type,
5636 				bf_get(lpfc_mbox_hdr_status,
5637 				    &dealloc_rsrc->header.cfg_shdr.response),
5638 				bf_get(lpfc_mbox_hdr_add_status,
5639 				    &dealloc_rsrc->header.cfg_shdr.response));
5640 		rc = -EIO;
5641 		goto out_free_mbox;
5642 	}
5643 
5644 	/* Release kernel memory resources for the specific type. */
5645 	switch (type) {
5646 	case LPFC_RSC_TYPE_FCOE_VPI:
5647 		kfree(phba->vpi_bmask);
5648 		kfree(phba->vpi_ids);
5649 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5650 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5651 				    &phba->lpfc_vpi_blk_list, list) {
5652 			list_del_init(&rsrc_blk->list);
5653 			kfree(rsrc_blk);
5654 		}
5655 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
5656 		break;
5657 	case LPFC_RSC_TYPE_FCOE_XRI:
5658 		kfree(phba->sli4_hba.xri_bmask);
5659 		kfree(phba->sli4_hba.xri_ids);
5660 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5661 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
5662 			list_del_init(&rsrc_blk->list);
5663 			kfree(rsrc_blk);
5664 		}
5665 		break;
5666 	case LPFC_RSC_TYPE_FCOE_VFI:
5667 		kfree(phba->sli4_hba.vfi_bmask);
5668 		kfree(phba->sli4_hba.vfi_ids);
5669 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5670 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5671 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
5672 			list_del_init(&rsrc_blk->list);
5673 			kfree(rsrc_blk);
5674 		}
5675 		break;
5676 	case LPFC_RSC_TYPE_FCOE_RPI:
5677 		/* RPI bitmask and physical id array are cleaned up earlier. */
5678 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5679 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
5680 			list_del_init(&rsrc_blk->list);
5681 			kfree(rsrc_blk);
5682 		}
5683 		break;
5684 	default:
5685 		break;
5686 	}
5687 
5688 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5689 
5690  out_free_mbox:
5691 	mempool_free(mbox, phba->mbox_mem_pool);
5692 	return rc;
5693 }
5694 
5695 void
5696 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
5697 		  uint32_t feature)
5698 {
5699 	uint32_t len;
5700 
5701 	len = sizeof(struct lpfc_mbx_set_feature) -
5702 		sizeof(struct lpfc_sli4_cfg_mhdr);
5703 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5704 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
5705 			 LPFC_SLI4_MBX_EMBED);
5706 
5707 	switch (feature) {
5708 	case LPFC_SET_UE_RECOVERY:
5709 		bf_set(lpfc_mbx_set_feature_UER,
5710 		       &mbox->u.mqe.un.set_feature, 1);
5711 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
5712 		mbox->u.mqe.un.set_feature.param_len = 8;
5713 		break;
5714 	case LPFC_SET_MDS_DIAGS:
5715 		bf_set(lpfc_mbx_set_feature_mds,
5716 		       &mbox->u.mqe.un.set_feature, 1);
5717 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
5718 		       &mbox->u.mqe.un.set_feature, 0);
5719 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
5720 		mbox->u.mqe.un.set_feature.param_len = 8;
5721 		break;
5722 	}
5723 
5724 	return;
5725 }
5726 
5727 /**
5728  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
5729  * @phba: Pointer to HBA context object.
5730  *
5731  * This function allocates all SLI4 resource identifiers.
5732  **/
5733 int
5734 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
5735 {
5736 	int i, rc, error = 0;
5737 	uint16_t count, base;
5738 	unsigned long longs;
5739 
5740 	if (!phba->sli4_hba.rpi_hdrs_in_use)
5741 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
5742 	if (phba->sli4_hba.extents_in_use) {
5743 		/*
5744 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
5745 		 * resource extent count must be read and allocated before
5746 		 * provisioning the resource id arrays.
5747 		 */
5748 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
5749 		    LPFC_IDX_RSRC_RDY) {
5750 			/*
5751 			 * Extent-based resources are set - the driver could
5752 			 * be in a port reset. Figure out if any corrective
5753 			 * actions need to be taken.
5754 			 */
5755 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5756 						 LPFC_RSC_TYPE_FCOE_VFI);
5757 			if (rc != 0)
5758 				error++;
5759 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5760 						 LPFC_RSC_TYPE_FCOE_VPI);
5761 			if (rc != 0)
5762 				error++;
5763 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5764 						 LPFC_RSC_TYPE_FCOE_XRI);
5765 			if (rc != 0)
5766 				error++;
5767 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5768 						 LPFC_RSC_TYPE_FCOE_RPI);
5769 			if (rc != 0)
5770 				error++;
5771 
5772 			/*
5773 			 * It's possible that the number of resources
5774 			 * provided to this port instance changed between
5775 			 * resets.  Detect this condition and reallocate
5776 			 * resources.  Otherwise, there is no action.
5777 			 */
5778 			if (error) {
5779 				lpfc_printf_log(phba, KERN_INFO,
5780 						LOG_MBOX | LOG_INIT,
5781 						"2931 Detected extent resource "
5782 						"change.  Reallocating all "
5783 						"extents.\n");
5784 				rc = lpfc_sli4_dealloc_extent(phba,
5785 						 LPFC_RSC_TYPE_FCOE_VFI);
5786 				rc = lpfc_sli4_dealloc_extent(phba,
5787 						 LPFC_RSC_TYPE_FCOE_VPI);
5788 				rc = lpfc_sli4_dealloc_extent(phba,
5789 						 LPFC_RSC_TYPE_FCOE_XRI);
5790 				rc = lpfc_sli4_dealloc_extent(phba,
5791 						 LPFC_RSC_TYPE_FCOE_RPI);
5792 			} else
5793 				return 0;
5794 		}
5795 
5796 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
5797 		if (unlikely(rc))
5798 			goto err_exit;
5799 
5800 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
5801 		if (unlikely(rc))
5802 			goto err_exit;
5803 
5804 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
5805 		if (unlikely(rc))
5806 			goto err_exit;
5807 
5808 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
5809 		if (unlikely(rc))
5810 			goto err_exit;
5811 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
5812 		       LPFC_IDX_RSRC_RDY);
5813 		return rc;
5814 	} else {
5815 		/*
5816 		 * The port does not support resource extents.  The XRI, VPI,
5817 		 * VFI, RPI resource ids were determined from READ_CONFIG.
5818 		 * Just allocate the bitmasks and provision the resource id
5819 		 * arrays.  If a port reset is active, the resources don't
5820 		 * need any action - just exit.
5821 		 */
5822 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
5823 		    LPFC_IDX_RSRC_RDY) {
5824 			lpfc_sli4_dealloc_resource_identifiers(phba);
5825 			lpfc_sli4_remove_rpis(phba);
5826 		}
5827 		/* RPIs. */
5828 		count = phba->sli4_hba.max_cfg_param.max_rpi;
5829 		if (count <= 0) {
5830 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5831 					"3279 Invalid provisioning of "
5832 					"rpi:%d\n", count);
5833 			rc = -EINVAL;
5834 			goto err_exit;
5835 		}
5836 		base = phba->sli4_hba.max_cfg_param.rpi_base;
5837 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5838 		phba->sli4_hba.rpi_bmask = kzalloc(longs *
5839 						   sizeof(unsigned long),
5840 						   GFP_KERNEL);
5841 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
5842 			rc = -ENOMEM;
5843 			goto err_exit;
5844 		}
5845 		phba->sli4_hba.rpi_ids = kzalloc(count *
5846 						 sizeof(uint16_t),
5847 						 GFP_KERNEL);
5848 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
5849 			rc = -ENOMEM;
5850 			goto free_rpi_bmask;
5851 		}
5852 
5853 		for (i = 0; i < count; i++)
5854 			phba->sli4_hba.rpi_ids[i] = base + i;
5855 
5856 		/* VPIs. */
5857 		count = phba->sli4_hba.max_cfg_param.max_vpi;
5858 		if (count <= 0) {
5859 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5860 					"3280 Invalid provisioning of "
5861 					"vpi:%d\n", count);
5862 			rc = -EINVAL;
5863 			goto free_rpi_ids;
5864 		}
5865 		base = phba->sli4_hba.max_cfg_param.vpi_base;
5866 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5867 		phba->vpi_bmask = kzalloc(longs *
5868 					  sizeof(unsigned long),
5869 					  GFP_KERNEL);
5870 		if (unlikely(!phba->vpi_bmask)) {
5871 			rc = -ENOMEM;
5872 			goto free_rpi_ids;
5873 		}
5874 		phba->vpi_ids = kzalloc(count *
5875 					sizeof(uint16_t),
5876 					GFP_KERNEL);
5877 		if (unlikely(!phba->vpi_ids)) {
5878 			rc = -ENOMEM;
5879 			goto free_vpi_bmask;
5880 		}
5881 
5882 		for (i = 0; i < count; i++)
5883 			phba->vpi_ids[i] = base + i;
5884 
5885 		/* XRIs. */
5886 		count = phba->sli4_hba.max_cfg_param.max_xri;
5887 		if (count <= 0) {
5888 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5889 					"3281 Invalid provisioning of "
5890 					"xri:%d\n", count);
5891 			rc = -EINVAL;
5892 			goto free_vpi_ids;
5893 		}
5894 		base = phba->sli4_hba.max_cfg_param.xri_base;
5895 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5896 		phba->sli4_hba.xri_bmask = kzalloc(longs *
5897 						   sizeof(unsigned long),
5898 						   GFP_KERNEL);
5899 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
5900 			rc = -ENOMEM;
5901 			goto free_vpi_ids;
5902 		}
5903 		phba->sli4_hba.max_cfg_param.xri_used = 0;
5904 		phba->sli4_hba.xri_ids = kzalloc(count *
5905 						 sizeof(uint16_t),
5906 						 GFP_KERNEL);
5907 		if (unlikely(!phba->sli4_hba.xri_ids)) {
5908 			rc = -ENOMEM;
5909 			goto free_xri_bmask;
5910 		}
5911 
5912 		for (i = 0; i < count; i++)
5913 			phba->sli4_hba.xri_ids[i] = base + i;
5914 
5915 		/* VFIs. */
5916 		count = phba->sli4_hba.max_cfg_param.max_vfi;
5917 		if (count <= 0) {
5918 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5919 					"3282 Invalid provisioning of "
5920 					"vfi:%d\n", count);
5921 			rc = -EINVAL;
5922 			goto free_xri_ids;
5923 		}
5924 		base = phba->sli4_hba.max_cfg_param.vfi_base;
5925 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5926 		phba->sli4_hba.vfi_bmask = kzalloc(longs *
5927 						   sizeof(unsigned long),
5928 						   GFP_KERNEL);
5929 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
5930 			rc = -ENOMEM;
5931 			goto free_xri_ids;
5932 		}
5933 		phba->sli4_hba.vfi_ids = kzalloc(count *
5934 						 sizeof(uint16_t),
5935 						 GFP_KERNEL);
5936 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
5937 			rc = -ENOMEM;
5938 			goto free_vfi_bmask;
5939 		}
5940 
5941 		for (i = 0; i < count; i++)
5942 			phba->sli4_hba.vfi_ids[i] = base + i;
5943 
5944 		/*
5945 		 * Mark all resources ready.  An HBA reset doesn't need
5946 		 * to reset the initialization.
5947 		 */
5948 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
5949 		       LPFC_IDX_RSRC_RDY);
5950 		return 0;
5951 	}
5952 
5953  free_vfi_bmask:
5954 	kfree(phba->sli4_hba.vfi_bmask);
5955  free_xri_ids:
5956 	kfree(phba->sli4_hba.xri_ids);
5957  free_xri_bmask:
5958 	kfree(phba->sli4_hba.xri_bmask);
5959  free_vpi_ids:
5960 	kfree(phba->vpi_ids);
5961  free_vpi_bmask:
5962 	kfree(phba->vpi_bmask);
5963  free_rpi_ids:
5964 	kfree(phba->sli4_hba.rpi_ids);
5965  free_rpi_bmask:
5966 	kfree(phba->sli4_hba.rpi_bmask);
5967  err_exit:
5968 	return rc;
5969 }
5970 
5971 /**
5972  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
5973  * @phba: Pointer to HBA context object.
5974  *
5975  * This function allocates the number of elements for the specified
5976  * resource type.
5977  **/
5978 int
5979 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
5980 {
5981 	if (phba->sli4_hba.extents_in_use) {
5982 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
5983 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
5984 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
5985 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
5986 	} else {
5987 		kfree(phba->vpi_bmask);
5988 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
5989 		kfree(phba->vpi_ids);
5990 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5991 		kfree(phba->sli4_hba.xri_bmask);
5992 		kfree(phba->sli4_hba.xri_ids);
5993 		kfree(phba->sli4_hba.vfi_bmask);
5994 		kfree(phba->sli4_hba.vfi_ids);
5995 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5996 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5997 	}
5998 
5999 	return 0;
6000 }
6001 
6002 /**
6003  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
6004  * @phba: Pointer to HBA context object.
6005  * @type: The resource extent type.
6006  * @extnt_count: buffer to hold port extent count response
6007  * @extnt_size: buffer to hold port extent size response.
6008  *
6009  * This function calls the port to read the host allocated extents
6010  * for a particular type.
6011  **/
6012 int
6013 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
6014 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
6015 {
6016 	bool emb;
6017 	int rc = 0;
6018 	uint16_t curr_blks = 0;
6019 	uint32_t req_len, emb_len;
6020 	uint32_t alloc_len, mbox_tmo;
6021 	struct list_head *blk_list_head;
6022 	struct lpfc_rsrc_blks *rsrc_blk;
6023 	LPFC_MBOXQ_t *mbox;
6024 	void *virtaddr = NULL;
6025 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6026 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6027 	union  lpfc_sli4_cfg_shdr *shdr;
6028 
6029 	switch (type) {
6030 	case LPFC_RSC_TYPE_FCOE_VPI:
6031 		blk_list_head = &phba->lpfc_vpi_blk_list;
6032 		break;
6033 	case LPFC_RSC_TYPE_FCOE_XRI:
6034 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
6035 		break;
6036 	case LPFC_RSC_TYPE_FCOE_VFI:
6037 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
6038 		break;
6039 	case LPFC_RSC_TYPE_FCOE_RPI:
6040 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
6041 		break;
6042 	default:
6043 		return -EIO;
6044 	}
6045 
6046 	/* Count the number of extents currently allocatd for this type. */
6047 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
6048 		if (curr_blks == 0) {
6049 			/*
6050 			 * The GET_ALLOCATED mailbox does not return the size,
6051 			 * just the count.  The size should be just the size
6052 			 * stored in the current allocated block and all sizes
6053 			 * for an extent type are the same so set the return
6054 			 * value now.
6055 			 */
6056 			*extnt_size = rsrc_blk->rsrc_size;
6057 		}
6058 		curr_blks++;
6059 	}
6060 
6061 	/*
6062 	 * Calculate the size of an embedded mailbox.  The uint32_t
6063 	 * accounts for extents-specific word.
6064 	 */
6065 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6066 		sizeof(uint32_t);
6067 
6068 	/*
6069 	 * Presume the allocation and response will fit into an embedded
6070 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6071 	 */
6072 	emb = LPFC_SLI4_MBX_EMBED;
6073 	req_len = emb_len;
6074 	if (req_len > emb_len) {
6075 		req_len = curr_blks * sizeof(uint16_t) +
6076 			sizeof(union lpfc_sli4_cfg_shdr) +
6077 			sizeof(uint32_t);
6078 		emb = LPFC_SLI4_MBX_NEMBED;
6079 	}
6080 
6081 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6082 	if (!mbox)
6083 		return -ENOMEM;
6084 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
6085 
6086 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6087 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
6088 				     req_len, emb);
6089 	if (alloc_len < req_len) {
6090 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6091 			"2983 Allocated DMA memory size (x%x) is "
6092 			"less than the requested DMA memory "
6093 			"size (x%x)\n", alloc_len, req_len);
6094 		rc = -ENOMEM;
6095 		goto err_exit;
6096 	}
6097 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
6098 	if (unlikely(rc)) {
6099 		rc = -EIO;
6100 		goto err_exit;
6101 	}
6102 
6103 	if (!phba->sli4_hba.intr_enable)
6104 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6105 	else {
6106 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6107 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6108 	}
6109 
6110 	if (unlikely(rc)) {
6111 		rc = -EIO;
6112 		goto err_exit;
6113 	}
6114 
6115 	/*
6116 	 * Figure out where the response is located.  Then get local pointers
6117 	 * to the response data.  The port does not guarantee to respond to
6118 	 * all extents counts request so update the local variable with the
6119 	 * allocated count from the port.
6120 	 */
6121 	if (emb == LPFC_SLI4_MBX_EMBED) {
6122 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6123 		shdr = &rsrc_ext->header.cfg_shdr;
6124 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6125 	} else {
6126 		virtaddr = mbox->sge_array->addr[0];
6127 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6128 		shdr = &n_rsrc->cfg_shdr;
6129 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6130 	}
6131 
6132 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
6133 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
6134 			"2984 Failed to read allocated resources "
6135 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
6136 			type,
6137 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
6138 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
6139 		rc = -EIO;
6140 		goto err_exit;
6141 	}
6142  err_exit:
6143 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6144 	return rc;
6145 }
6146 
6147 /**
6148  * lpfc_sli4_repost_els_sgl_list - Repsot the els buffers sgl pages as block
6149  * @phba: pointer to lpfc hba data structure.
6150  *
6151  * This routine walks the list of els buffers that have been allocated and
6152  * repost them to the port by using SGL block post. This is needed after a
6153  * pci_function_reset/warm_start or start. It attempts to construct blocks
6154  * of els buffer sgls which contains contiguous xris and uses the non-embedded
6155  * SGL block post mailbox commands to post them to the port. For single els
6156  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
6157  * mailbox command for posting.
6158  *
6159  * Returns: 0 = success, non-zero failure.
6160  **/
6161 static int
6162 lpfc_sli4_repost_els_sgl_list(struct lpfc_hba *phba)
6163 {
6164 	struct lpfc_sglq *sglq_entry = NULL;
6165 	struct lpfc_sglq *sglq_entry_next = NULL;
6166 	struct lpfc_sglq *sglq_entry_first = NULL;
6167 	int status, total_cnt, post_cnt = 0, num_posted = 0, block_cnt = 0;
6168 	int last_xritag = NO_XRI;
6169 	struct lpfc_sli_ring *pring;
6170 	LIST_HEAD(prep_sgl_list);
6171 	LIST_HEAD(blck_sgl_list);
6172 	LIST_HEAD(allc_sgl_list);
6173 	LIST_HEAD(post_sgl_list);
6174 	LIST_HEAD(free_sgl_list);
6175 
6176 	pring = &phba->sli.ring[LPFC_ELS_RING];
6177 	spin_lock_irq(&phba->hbalock);
6178 	spin_lock(&pring->ring_lock);
6179 	list_splice_init(&phba->sli4_hba.lpfc_sgl_list, &allc_sgl_list);
6180 	spin_unlock(&pring->ring_lock);
6181 	spin_unlock_irq(&phba->hbalock);
6182 
6183 	total_cnt = phba->sli4_hba.els_xri_cnt;
6184 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
6185 				 &allc_sgl_list, list) {
6186 		list_del_init(&sglq_entry->list);
6187 		block_cnt++;
6188 		if ((last_xritag != NO_XRI) &&
6189 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
6190 			/* a hole in xri block, form a sgl posting block */
6191 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
6192 			post_cnt = block_cnt - 1;
6193 			/* prepare list for next posting block */
6194 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
6195 			block_cnt = 1;
6196 		} else {
6197 			/* prepare list for next posting block */
6198 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
6199 			/* enough sgls for non-embed sgl mbox command */
6200 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
6201 				list_splice_init(&prep_sgl_list,
6202 						 &blck_sgl_list);
6203 				post_cnt = block_cnt;
6204 				block_cnt = 0;
6205 			}
6206 		}
6207 		num_posted++;
6208 
6209 		/* keep track of last sgl's xritag */
6210 		last_xritag = sglq_entry->sli4_xritag;
6211 
6212 		/* end of repost sgl list condition for els buffers */
6213 		if (num_posted == phba->sli4_hba.els_xri_cnt) {
6214 			if (post_cnt == 0) {
6215 				list_splice_init(&prep_sgl_list,
6216 						 &blck_sgl_list);
6217 				post_cnt = block_cnt;
6218 			} else if (block_cnt == 1) {
6219 				status = lpfc_sli4_post_sgl(phba,
6220 						sglq_entry->phys, 0,
6221 						sglq_entry->sli4_xritag);
6222 				if (!status) {
6223 					/* successful, put sgl to posted list */
6224 					list_add_tail(&sglq_entry->list,
6225 						      &post_sgl_list);
6226 				} else {
6227 					/* Failure, put sgl to free list */
6228 					lpfc_printf_log(phba, KERN_WARNING,
6229 						LOG_SLI,
6230 						"3159 Failed to post els "
6231 						"sgl, xritag:x%x\n",
6232 						sglq_entry->sli4_xritag);
6233 					list_add_tail(&sglq_entry->list,
6234 						      &free_sgl_list);
6235 					total_cnt--;
6236 				}
6237 			}
6238 		}
6239 
6240 		/* continue until a nembed page worth of sgls */
6241 		if (post_cnt == 0)
6242 			continue;
6243 
6244 		/* post the els buffer list sgls as a block */
6245 		status = lpfc_sli4_post_els_sgl_list(phba, &blck_sgl_list,
6246 						     post_cnt);
6247 
6248 		if (!status) {
6249 			/* success, put sgl list to posted sgl list */
6250 			list_splice_init(&blck_sgl_list, &post_sgl_list);
6251 		} else {
6252 			/* Failure, put sgl list to free sgl list */
6253 			sglq_entry_first = list_first_entry(&blck_sgl_list,
6254 							    struct lpfc_sglq,
6255 							    list);
6256 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6257 					"3160 Failed to post els sgl-list, "
6258 					"xritag:x%x-x%x\n",
6259 					sglq_entry_first->sli4_xritag,
6260 					(sglq_entry_first->sli4_xritag +
6261 					 post_cnt - 1));
6262 			list_splice_init(&blck_sgl_list, &free_sgl_list);
6263 			total_cnt -= post_cnt;
6264 		}
6265 
6266 		/* don't reset xirtag due to hole in xri block */
6267 		if (block_cnt == 0)
6268 			last_xritag = NO_XRI;
6269 
6270 		/* reset els sgl post count for next round of posting */
6271 		post_cnt = 0;
6272 	}
6273 	/* update the number of XRIs posted for ELS */
6274 	phba->sli4_hba.els_xri_cnt = total_cnt;
6275 
6276 	/* free the els sgls failed to post */
6277 	lpfc_free_sgl_list(phba, &free_sgl_list);
6278 
6279 	/* push els sgls posted to the availble list */
6280 	if (!list_empty(&post_sgl_list)) {
6281 		spin_lock_irq(&phba->hbalock);
6282 		spin_lock(&pring->ring_lock);
6283 		list_splice_init(&post_sgl_list,
6284 				 &phba->sli4_hba.lpfc_sgl_list);
6285 		spin_unlock(&pring->ring_lock);
6286 		spin_unlock_irq(&phba->hbalock);
6287 	} else {
6288 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6289 				"3161 Failure to post els sgl to port.\n");
6290 		return -EIO;
6291 	}
6292 	return 0;
6293 }
6294 
6295 /**
6296  * lpfc_sli4_hba_setup - SLI4 device intialization PCI function
6297  * @phba: Pointer to HBA context object.
6298  *
6299  * This function is the main SLI4 device intialization PCI function. This
6300  * function is called by the HBA intialization code, HBA reset code and
6301  * HBA error attention handler code. Caller is not required to hold any
6302  * locks.
6303  **/
6304 int
6305 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
6306 {
6307 	int rc;
6308 	LPFC_MBOXQ_t *mboxq;
6309 	struct lpfc_mqe *mqe;
6310 	uint8_t *vpd;
6311 	uint32_t vpd_size;
6312 	uint32_t ftr_rsp = 0;
6313 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
6314 	struct lpfc_vport *vport = phba->pport;
6315 	struct lpfc_dmabuf *mp;
6316 
6317 	/* Perform a PCI function reset to start from clean */
6318 	rc = lpfc_pci_function_reset(phba);
6319 	if (unlikely(rc))
6320 		return -ENODEV;
6321 
6322 	/* Check the HBA Host Status Register for readyness */
6323 	rc = lpfc_sli4_post_status_check(phba);
6324 	if (unlikely(rc))
6325 		return -ENODEV;
6326 	else {
6327 		spin_lock_irq(&phba->hbalock);
6328 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
6329 		spin_unlock_irq(&phba->hbalock);
6330 	}
6331 
6332 	/*
6333 	 * Allocate a single mailbox container for initializing the
6334 	 * port.
6335 	 */
6336 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6337 	if (!mboxq)
6338 		return -ENOMEM;
6339 
6340 	/* Issue READ_REV to collect vpd and FW information. */
6341 	vpd_size = SLI4_PAGE_SIZE;
6342 	vpd = kzalloc(vpd_size, GFP_KERNEL);
6343 	if (!vpd) {
6344 		rc = -ENOMEM;
6345 		goto out_free_mbox;
6346 	}
6347 
6348 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
6349 	if (unlikely(rc)) {
6350 		kfree(vpd);
6351 		goto out_free_mbox;
6352 	}
6353 
6354 	mqe = &mboxq->u.mqe;
6355 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
6356 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
6357 		phba->hba_flag |= HBA_FCOE_MODE;
6358 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
6359 	} else {
6360 		phba->hba_flag &= ~HBA_FCOE_MODE;
6361 	}
6362 
6363 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
6364 		LPFC_DCBX_CEE_MODE)
6365 		phba->hba_flag |= HBA_FIP_SUPPORT;
6366 	else
6367 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
6368 
6369 	phba->hba_flag &= ~HBA_FCP_IOQ_FLUSH;
6370 
6371 	if (phba->sli_rev != LPFC_SLI_REV4) {
6372 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6373 			"0376 READ_REV Error. SLI Level %d "
6374 			"FCoE enabled %d\n",
6375 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
6376 		rc = -EIO;
6377 		kfree(vpd);
6378 		goto out_free_mbox;
6379 	}
6380 
6381 	/*
6382 	 * Continue initialization with default values even if driver failed
6383 	 * to read FCoE param config regions, only read parameters if the
6384 	 * board is FCoE
6385 	 */
6386 	if (phba->hba_flag & HBA_FCOE_MODE &&
6387 	    lpfc_sli4_read_fcoe_params(phba))
6388 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
6389 			"2570 Failed to read FCoE parameters\n");
6390 
6391 	/*
6392 	 * Retrieve sli4 device physical port name, failure of doing it
6393 	 * is considered as non-fatal.
6394 	 */
6395 	rc = lpfc_sli4_retrieve_pport_name(phba);
6396 	if (!rc)
6397 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
6398 				"3080 Successful retrieving SLI4 device "
6399 				"physical port name: %s.\n", phba->Port);
6400 
6401 	/*
6402 	 * Evaluate the read rev and vpd data. Populate the driver
6403 	 * state with the results. If this routine fails, the failure
6404 	 * is not fatal as the driver will use generic values.
6405 	 */
6406 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
6407 	if (unlikely(!rc)) {
6408 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6409 				"0377 Error %d parsing vpd. "
6410 				"Using defaults.\n", rc);
6411 		rc = 0;
6412 	}
6413 	kfree(vpd);
6414 
6415 	/* Save information as VPD data */
6416 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
6417 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
6418 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
6419 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
6420 					 &mqe->un.read_rev);
6421 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
6422 				       &mqe->un.read_rev);
6423 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
6424 					    &mqe->un.read_rev);
6425 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
6426 					   &mqe->un.read_rev);
6427 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
6428 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
6429 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
6430 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
6431 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
6432 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
6433 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
6434 			"(%d):0380 READ_REV Status x%x "
6435 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
6436 			mboxq->vport ? mboxq->vport->vpi : 0,
6437 			bf_get(lpfc_mqe_status, mqe),
6438 			phba->vpd.rev.opFwName,
6439 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
6440 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
6441 
6442 	/* Reset the DFT_LUN_Q_DEPTH to (max xri >> 3)  */
6443 	rc = (phba->sli4_hba.max_cfg_param.max_xri >> 3);
6444 	if (phba->pport->cfg_lun_queue_depth > rc) {
6445 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6446 				"3362 LUN queue depth changed from %d to %d\n",
6447 				phba->pport->cfg_lun_queue_depth, rc);
6448 		phba->pport->cfg_lun_queue_depth = rc;
6449 	}
6450 
6451 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
6452 	    LPFC_SLI_INTF_IF_TYPE_0) {
6453 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
6454 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6455 		if (rc == MBX_SUCCESS) {
6456 			phba->hba_flag |= HBA_RECOVERABLE_UE;
6457 			/* Set 1Sec interval to detect UE */
6458 			phba->eratt_poll_interval = 1;
6459 			phba->sli4_hba.ue_to_sr = bf_get(
6460 					lpfc_mbx_set_feature_UESR,
6461 					&mboxq->u.mqe.un.set_feature);
6462 			phba->sli4_hba.ue_to_rp = bf_get(
6463 					lpfc_mbx_set_feature_UERP,
6464 					&mboxq->u.mqe.un.set_feature);
6465 		}
6466 	}
6467 
6468 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
6469 		/* Enable MDS Diagnostics only if the SLI Port supports it */
6470 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
6471 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6472 		if (rc != MBX_SUCCESS)
6473 			phba->mds_diags_support = 0;
6474 	}
6475 
6476 	/*
6477 	 * Discover the port's supported feature set and match it against the
6478 	 * hosts requests.
6479 	 */
6480 	lpfc_request_features(phba, mboxq);
6481 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6482 	if (unlikely(rc)) {
6483 		rc = -EIO;
6484 		goto out_free_mbox;
6485 	}
6486 
6487 	/*
6488 	 * The port must support FCP initiator mode as this is the
6489 	 * only mode running in the host.
6490 	 */
6491 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
6492 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
6493 				"0378 No support for fcpi mode.\n");
6494 		ftr_rsp++;
6495 	}
6496 	if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
6497 		phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
6498 	else
6499 		phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
6500 	/*
6501 	 * If the port cannot support the host's requested features
6502 	 * then turn off the global config parameters to disable the
6503 	 * feature in the driver.  This is not a fatal error.
6504 	 */
6505 	phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
6506 	if (phba->cfg_enable_bg) {
6507 		if (bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))
6508 			phba->sli3_options |= LPFC_SLI3_BG_ENABLED;
6509 		else
6510 			ftr_rsp++;
6511 	}
6512 
6513 	if (phba->max_vpi && phba->cfg_enable_npiv &&
6514 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
6515 		ftr_rsp++;
6516 
6517 	if (ftr_rsp) {
6518 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
6519 				"0379 Feature Mismatch Data: x%08x %08x "
6520 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
6521 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
6522 				phba->cfg_enable_npiv, phba->max_vpi);
6523 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
6524 			phba->cfg_enable_bg = 0;
6525 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
6526 			phba->cfg_enable_npiv = 0;
6527 	}
6528 
6529 	/* These SLI3 features are assumed in SLI4 */
6530 	spin_lock_irq(&phba->hbalock);
6531 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
6532 	spin_unlock_irq(&phba->hbalock);
6533 
6534 	/*
6535 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
6536 	 * calls depends on these resources to complete port setup.
6537 	 */
6538 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
6539 	if (rc) {
6540 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6541 				"2920 Failed to alloc Resource IDs "
6542 				"rc = x%x\n", rc);
6543 		goto out_free_mbox;
6544 	}
6545 
6546 	/* Read the port's service parameters. */
6547 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
6548 	if (rc) {
6549 		phba->link_state = LPFC_HBA_ERROR;
6550 		rc = -ENOMEM;
6551 		goto out_free_mbox;
6552 	}
6553 
6554 	mboxq->vport = vport;
6555 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6556 	mp = (struct lpfc_dmabuf *) mboxq->context1;
6557 	if (rc == MBX_SUCCESS) {
6558 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
6559 		rc = 0;
6560 	}
6561 
6562 	/*
6563 	 * This memory was allocated by the lpfc_read_sparam routine. Release
6564 	 * it to the mbuf pool.
6565 	 */
6566 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
6567 	kfree(mp);
6568 	mboxq->context1 = NULL;
6569 	if (unlikely(rc)) {
6570 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6571 				"0382 READ_SPARAM command failed "
6572 				"status %d, mbxStatus x%x\n",
6573 				rc, bf_get(lpfc_mqe_status, mqe));
6574 		phba->link_state = LPFC_HBA_ERROR;
6575 		rc = -EIO;
6576 		goto out_free_mbox;
6577 	}
6578 
6579 	lpfc_update_vport_wwn(vport);
6580 
6581 	/* Update the fc_host data structures with new wwn. */
6582 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
6583 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
6584 
6585 	/* update host els and scsi xri-sgl sizes and mappings */
6586 	rc = lpfc_sli4_xri_sgl_update(phba);
6587 	if (unlikely(rc)) {
6588 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6589 				"1400 Failed to update xri-sgl size and "
6590 				"mapping: %d\n", rc);
6591 		goto out_free_mbox;
6592 	}
6593 
6594 	/* register the els sgl pool to the port */
6595 	rc = lpfc_sli4_repost_els_sgl_list(phba);
6596 	if (unlikely(rc)) {
6597 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6598 				"0582 Error %d during els sgl post "
6599 				"operation\n", rc);
6600 		rc = -ENODEV;
6601 		goto out_free_mbox;
6602 	}
6603 
6604 	/* register the allocated scsi sgl pool to the port */
6605 	rc = lpfc_sli4_repost_scsi_sgl_list(phba);
6606 	if (unlikely(rc)) {
6607 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6608 				"0383 Error %d during scsi sgl post "
6609 				"operation\n", rc);
6610 		/* Some Scsi buffers were moved to the abort scsi list */
6611 		/* A pci function reset will repost them */
6612 		rc = -ENODEV;
6613 		goto out_free_mbox;
6614 	}
6615 
6616 	/* Post the rpi header region to the device. */
6617 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
6618 	if (unlikely(rc)) {
6619 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6620 				"0393 Error %d during rpi post operation\n",
6621 				rc);
6622 		rc = -ENODEV;
6623 		goto out_free_mbox;
6624 	}
6625 	lpfc_sli4_node_prep(phba);
6626 
6627 	/* Create all the SLI4 queues */
6628 	rc = lpfc_sli4_queue_create(phba);
6629 	if (rc) {
6630 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6631 				"3089 Failed to allocate queues\n");
6632 		rc = -ENODEV;
6633 		goto out_stop_timers;
6634 	}
6635 	/* Set up all the queues to the device */
6636 	rc = lpfc_sli4_queue_setup(phba);
6637 	if (unlikely(rc)) {
6638 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6639 				"0381 Error %d during queue setup.\n ", rc);
6640 		goto out_destroy_queue;
6641 	}
6642 
6643 	/* Arm the CQs and then EQs on device */
6644 	lpfc_sli4_arm_cqeq_intr(phba);
6645 
6646 	/* Indicate device interrupt mode */
6647 	phba->sli4_hba.intr_enable = 1;
6648 
6649 	/* Allow asynchronous mailbox command to go through */
6650 	spin_lock_irq(&phba->hbalock);
6651 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
6652 	spin_unlock_irq(&phba->hbalock);
6653 
6654 	/* Post receive buffers to the device */
6655 	lpfc_sli4_rb_setup(phba);
6656 
6657 	/* Reset HBA FCF states after HBA reset */
6658 	phba->fcf.fcf_flag = 0;
6659 	phba->fcf.current_rec.flag = 0;
6660 
6661 	/* Start the ELS watchdog timer */
6662 	mod_timer(&vport->els_tmofunc,
6663 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
6664 
6665 	/* Start heart beat timer */
6666 	mod_timer(&phba->hb_tmofunc,
6667 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
6668 	phba->hb_outstanding = 0;
6669 	phba->last_completion_time = jiffies;
6670 
6671 	/* Start error attention (ERATT) polling timer */
6672 	mod_timer(&phba->eratt_poll,
6673 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
6674 
6675 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
6676 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
6677 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
6678 		if (!rc) {
6679 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6680 					"2829 This device supports "
6681 					"Advanced Error Reporting (AER)\n");
6682 			spin_lock_irq(&phba->hbalock);
6683 			phba->hba_flag |= HBA_AER_ENABLED;
6684 			spin_unlock_irq(&phba->hbalock);
6685 		} else {
6686 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6687 					"2830 This device does not support "
6688 					"Advanced Error Reporting (AER)\n");
6689 			phba->cfg_aer_support = 0;
6690 		}
6691 		rc = 0;
6692 	}
6693 
6694 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
6695 		/*
6696 		 * The FC Port needs to register FCFI (index 0)
6697 		 */
6698 		lpfc_reg_fcfi(phba, mboxq);
6699 		mboxq->vport = phba->pport;
6700 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6701 		if (rc != MBX_SUCCESS)
6702 			goto out_unset_queue;
6703 		rc = 0;
6704 		phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
6705 					&mboxq->u.mqe.un.reg_fcfi);
6706 
6707 		/* Check if the port is configured to be disabled */
6708 		lpfc_sli_read_link_ste(phba);
6709 	}
6710 
6711 	/*
6712 	 * The port is ready, set the host's link state to LINK_DOWN
6713 	 * in preparation for link interrupts.
6714 	 */
6715 	spin_lock_irq(&phba->hbalock);
6716 	phba->link_state = LPFC_LINK_DOWN;
6717 	spin_unlock_irq(&phba->hbalock);
6718 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
6719 	    (phba->hba_flag & LINK_DISABLED)) {
6720 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
6721 				"3103 Adapter Link is disabled.\n");
6722 		lpfc_down_link(phba, mboxq);
6723 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6724 		if (rc != MBX_SUCCESS) {
6725 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
6726 					"3104 Adapter failed to issue "
6727 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
6728 			goto out_unset_queue;
6729 		}
6730 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
6731 		/* don't perform init_link on SLI4 FC port loopback test */
6732 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
6733 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
6734 			if (rc)
6735 				goto out_unset_queue;
6736 		}
6737 	}
6738 	mempool_free(mboxq, phba->mbox_mem_pool);
6739 	return rc;
6740 out_unset_queue:
6741 	/* Unset all the queues set up in this routine when error out */
6742 	lpfc_sli4_queue_unset(phba);
6743 out_destroy_queue:
6744 	lpfc_sli4_queue_destroy(phba);
6745 out_stop_timers:
6746 	lpfc_stop_hba_timers(phba);
6747 out_free_mbox:
6748 	mempool_free(mboxq, phba->mbox_mem_pool);
6749 	return rc;
6750 }
6751 
6752 /**
6753  * lpfc_mbox_timeout - Timeout call back function for mbox timer
6754  * @ptr: context object - pointer to hba structure.
6755  *
6756  * This is the callback function for mailbox timer. The mailbox
6757  * timer is armed when a new mailbox command is issued and the timer
6758  * is deleted when the mailbox complete. The function is called by
6759  * the kernel timer code when a mailbox does not complete within
6760  * expected time. This function wakes up the worker thread to
6761  * process the mailbox timeout and returns. All the processing is
6762  * done by the worker thread function lpfc_mbox_timeout_handler.
6763  **/
6764 void
6765 lpfc_mbox_timeout(unsigned long ptr)
6766 {
6767 	struct lpfc_hba  *phba = (struct lpfc_hba *) ptr;
6768 	unsigned long iflag;
6769 	uint32_t tmo_posted;
6770 
6771 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
6772 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
6773 	if (!tmo_posted)
6774 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
6775 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
6776 
6777 	if (!tmo_posted)
6778 		lpfc_worker_wake_up(phba);
6779 	return;
6780 }
6781 
6782 /**
6783  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
6784  *                                    are pending
6785  * @phba: Pointer to HBA context object.
6786  *
6787  * This function checks if any mailbox completions are present on the mailbox
6788  * completion queue.
6789  **/
6790 static bool
6791 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
6792 {
6793 
6794 	uint32_t idx;
6795 	struct lpfc_queue *mcq;
6796 	struct lpfc_mcqe *mcqe;
6797 	bool pending_completions = false;
6798 
6799 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
6800 		return false;
6801 
6802 	/* Check for completions on mailbox completion queue */
6803 
6804 	mcq = phba->sli4_hba.mbx_cq;
6805 	idx = mcq->hba_index;
6806 	while (bf_get_le32(lpfc_cqe_valid, mcq->qe[idx].cqe)) {
6807 		mcqe = (struct lpfc_mcqe *)mcq->qe[idx].cqe;
6808 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
6809 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
6810 			pending_completions = true;
6811 			break;
6812 		}
6813 		idx = (idx + 1) % mcq->entry_count;
6814 		if (mcq->hba_index == idx)
6815 			break;
6816 	}
6817 	return pending_completions;
6818 
6819 }
6820 
6821 /**
6822  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
6823  *					      that were missed.
6824  * @phba: Pointer to HBA context object.
6825  *
6826  * For sli4, it is possible to miss an interrupt. As such mbox completions
6827  * maybe missed causing erroneous mailbox timeouts to occur. This function
6828  * checks to see if mbox completions are on the mailbox completion queue
6829  * and will process all the completions associated with the eq for the
6830  * mailbox completion queue.
6831  **/
6832 bool
6833 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
6834 {
6835 
6836 	uint32_t eqidx;
6837 	struct lpfc_queue *fpeq = NULL;
6838 	struct lpfc_eqe *eqe;
6839 	bool mbox_pending;
6840 
6841 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
6842 		return false;
6843 
6844 	/* Find the eq associated with the mcq */
6845 
6846 	if (phba->sli4_hba.hba_eq)
6847 		for (eqidx = 0; eqidx < phba->cfg_fcp_io_channel; eqidx++)
6848 			if (phba->sli4_hba.hba_eq[eqidx]->queue_id ==
6849 			    phba->sli4_hba.mbx_cq->assoc_qid) {
6850 				fpeq = phba->sli4_hba.hba_eq[eqidx];
6851 				break;
6852 			}
6853 	if (!fpeq)
6854 		return false;
6855 
6856 	/* Turn off interrupts from this EQ */
6857 
6858 	lpfc_sli4_eq_clr_intr(fpeq);
6859 
6860 	/* Check to see if a mbox completion is pending */
6861 
6862 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
6863 
6864 	/*
6865 	 * If a mbox completion is pending, process all the events on EQ
6866 	 * associated with the mbox completion queue (this could include
6867 	 * mailbox commands, async events, els commands, receive queue data
6868 	 * and fcp commands)
6869 	 */
6870 
6871 	if (mbox_pending)
6872 		while ((eqe = lpfc_sli4_eq_get(fpeq))) {
6873 			lpfc_sli4_hba_handle_eqe(phba, eqe, eqidx);
6874 			fpeq->EQ_processed++;
6875 		}
6876 
6877 	/* Always clear and re-arm the EQ */
6878 
6879 	lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_REARM);
6880 
6881 	return mbox_pending;
6882 
6883 }
6884 
6885 /**
6886  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
6887  * @phba: Pointer to HBA context object.
6888  *
6889  * This function is called from worker thread when a mailbox command times out.
6890  * The caller is not required to hold any locks. This function will reset the
6891  * HBA and recover all the pending commands.
6892  **/
6893 void
6894 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
6895 {
6896 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
6897 	MAILBOX_t *mb = NULL;
6898 
6899 	struct lpfc_sli *psli = &phba->sli;
6900 
6901 	/* If the mailbox completed, process the completion and return */
6902 	if (lpfc_sli4_process_missed_mbox_completions(phba))
6903 		return;
6904 
6905 	if (pmbox != NULL)
6906 		mb = &pmbox->u.mb;
6907 	/* Check the pmbox pointer first.  There is a race condition
6908 	 * between the mbox timeout handler getting executed in the
6909 	 * worklist and the mailbox actually completing. When this
6910 	 * race condition occurs, the mbox_active will be NULL.
6911 	 */
6912 	spin_lock_irq(&phba->hbalock);
6913 	if (pmbox == NULL) {
6914 		lpfc_printf_log(phba, KERN_WARNING,
6915 				LOG_MBOX | LOG_SLI,
6916 				"0353 Active Mailbox cleared - mailbox timeout "
6917 				"exiting\n");
6918 		spin_unlock_irq(&phba->hbalock);
6919 		return;
6920 	}
6921 
6922 	/* Mbox cmd <mbxCommand> timeout */
6923 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6924 			"0310 Mailbox command x%x timeout Data: x%x x%x x%p\n",
6925 			mb->mbxCommand,
6926 			phba->pport->port_state,
6927 			phba->sli.sli_flag,
6928 			phba->sli.mbox_active);
6929 	spin_unlock_irq(&phba->hbalock);
6930 
6931 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
6932 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
6933 	 * it to fail all outstanding SCSI IO.
6934 	 */
6935 	spin_lock_irq(&phba->pport->work_port_lock);
6936 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
6937 	spin_unlock_irq(&phba->pport->work_port_lock);
6938 	spin_lock_irq(&phba->hbalock);
6939 	phba->link_state = LPFC_LINK_UNKNOWN;
6940 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
6941 	spin_unlock_irq(&phba->hbalock);
6942 
6943 	lpfc_sli_abort_fcp_rings(phba);
6944 
6945 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6946 			"0345 Resetting board due to mailbox timeout\n");
6947 
6948 	/* Reset the HBA device */
6949 	lpfc_reset_hba(phba);
6950 }
6951 
6952 /**
6953  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
6954  * @phba: Pointer to HBA context object.
6955  * @pmbox: Pointer to mailbox object.
6956  * @flag: Flag indicating how the mailbox need to be processed.
6957  *
6958  * This function is called by discovery code and HBA management code
6959  * to submit a mailbox command to firmware with SLI-3 interface spec. This
6960  * function gets the hbalock to protect the data structures.
6961  * The mailbox command can be submitted in polling mode, in which case
6962  * this function will wait in a polling loop for the completion of the
6963  * mailbox.
6964  * If the mailbox is submitted in no_wait mode (not polling) the
6965  * function will submit the command and returns immediately without waiting
6966  * for the mailbox completion. The no_wait is supported only when HBA
6967  * is in SLI2/SLI3 mode - interrupts are enabled.
6968  * The SLI interface allows only one mailbox pending at a time. If the
6969  * mailbox is issued in polling mode and there is already a mailbox
6970  * pending, then the function will return an error. If the mailbox is issued
6971  * in NO_WAIT mode and there is a mailbox pending already, the function
6972  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
6973  * The sli layer owns the mailbox object until the completion of mailbox
6974  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
6975  * return codes the caller owns the mailbox command after the return of
6976  * the function.
6977  **/
6978 static int
6979 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
6980 		       uint32_t flag)
6981 {
6982 	MAILBOX_t *mbx;
6983 	struct lpfc_sli *psli = &phba->sli;
6984 	uint32_t status, evtctr;
6985 	uint32_t ha_copy, hc_copy;
6986 	int i;
6987 	unsigned long timeout;
6988 	unsigned long drvr_flag = 0;
6989 	uint32_t word0, ldata;
6990 	void __iomem *to_slim;
6991 	int processing_queue = 0;
6992 
6993 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
6994 	if (!pmbox) {
6995 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
6996 		/* processing mbox queue from intr_handler */
6997 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
6998 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
6999 			return MBX_SUCCESS;
7000 		}
7001 		processing_queue = 1;
7002 		pmbox = lpfc_mbox_get(phba);
7003 		if (!pmbox) {
7004 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7005 			return MBX_SUCCESS;
7006 		}
7007 	}
7008 
7009 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
7010 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
7011 		if(!pmbox->vport) {
7012 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7013 			lpfc_printf_log(phba, KERN_ERR,
7014 					LOG_MBOX | LOG_VPORT,
7015 					"1806 Mbox x%x failed. No vport\n",
7016 					pmbox->u.mb.mbxCommand);
7017 			dump_stack();
7018 			goto out_not_finished;
7019 		}
7020 	}
7021 
7022 	/* If the PCI channel is in offline state, do not post mbox. */
7023 	if (unlikely(pci_channel_offline(phba->pcidev))) {
7024 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7025 		goto out_not_finished;
7026 	}
7027 
7028 	/* If HBA has a deferred error attention, fail the iocb. */
7029 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
7030 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7031 		goto out_not_finished;
7032 	}
7033 
7034 	psli = &phba->sli;
7035 
7036 	mbx = &pmbox->u.mb;
7037 	status = MBX_SUCCESS;
7038 
7039 	if (phba->link_state == LPFC_HBA_ERROR) {
7040 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7041 
7042 		/* Mbox command <mbxCommand> cannot issue */
7043 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7044 				"(%d):0311 Mailbox command x%x cannot "
7045 				"issue Data: x%x x%x\n",
7046 				pmbox->vport ? pmbox->vport->vpi : 0,
7047 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
7048 		goto out_not_finished;
7049 	}
7050 
7051 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
7052 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
7053 			!(hc_copy & HC_MBINT_ENA)) {
7054 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7055 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7056 				"(%d):2528 Mailbox command x%x cannot "
7057 				"issue Data: x%x x%x\n",
7058 				pmbox->vport ? pmbox->vport->vpi : 0,
7059 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
7060 			goto out_not_finished;
7061 		}
7062 	}
7063 
7064 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
7065 		/* Polling for a mbox command when another one is already active
7066 		 * is not allowed in SLI. Also, the driver must have established
7067 		 * SLI2 mode to queue and process multiple mbox commands.
7068 		 */
7069 
7070 		if (flag & MBX_POLL) {
7071 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7072 
7073 			/* Mbox command <mbxCommand> cannot issue */
7074 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7075 					"(%d):2529 Mailbox command x%x "
7076 					"cannot issue Data: x%x x%x\n",
7077 					pmbox->vport ? pmbox->vport->vpi : 0,
7078 					pmbox->u.mb.mbxCommand,
7079 					psli->sli_flag, flag);
7080 			goto out_not_finished;
7081 		}
7082 
7083 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
7084 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7085 			/* Mbox command <mbxCommand> cannot issue */
7086 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7087 					"(%d):2530 Mailbox command x%x "
7088 					"cannot issue Data: x%x x%x\n",
7089 					pmbox->vport ? pmbox->vport->vpi : 0,
7090 					pmbox->u.mb.mbxCommand,
7091 					psli->sli_flag, flag);
7092 			goto out_not_finished;
7093 		}
7094 
7095 		/* Another mailbox command is still being processed, queue this
7096 		 * command to be processed later.
7097 		 */
7098 		lpfc_mbox_put(phba, pmbox);
7099 
7100 		/* Mbox cmd issue - BUSY */
7101 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7102 				"(%d):0308 Mbox cmd issue - BUSY Data: "
7103 				"x%x x%x x%x x%x\n",
7104 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
7105 				mbx->mbxCommand, phba->pport->port_state,
7106 				psli->sli_flag, flag);
7107 
7108 		psli->slistat.mbox_busy++;
7109 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7110 
7111 		if (pmbox->vport) {
7112 			lpfc_debugfs_disc_trc(pmbox->vport,
7113 				LPFC_DISC_TRC_MBOX_VPORT,
7114 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
7115 				(uint32_t)mbx->mbxCommand,
7116 				mbx->un.varWords[0], mbx->un.varWords[1]);
7117 		}
7118 		else {
7119 			lpfc_debugfs_disc_trc(phba->pport,
7120 				LPFC_DISC_TRC_MBOX,
7121 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
7122 				(uint32_t)mbx->mbxCommand,
7123 				mbx->un.varWords[0], mbx->un.varWords[1]);
7124 		}
7125 
7126 		return MBX_BUSY;
7127 	}
7128 
7129 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
7130 
7131 	/* If we are not polling, we MUST be in SLI2 mode */
7132 	if (flag != MBX_POLL) {
7133 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
7134 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
7135 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7136 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7137 			/* Mbox command <mbxCommand> cannot issue */
7138 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7139 					"(%d):2531 Mailbox command x%x "
7140 					"cannot issue Data: x%x x%x\n",
7141 					pmbox->vport ? pmbox->vport->vpi : 0,
7142 					pmbox->u.mb.mbxCommand,
7143 					psli->sli_flag, flag);
7144 			goto out_not_finished;
7145 		}
7146 		/* timeout active mbox command */
7147 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
7148 					   1000);
7149 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
7150 	}
7151 
7152 	/* Mailbox cmd <cmd> issue */
7153 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7154 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
7155 			"x%x\n",
7156 			pmbox->vport ? pmbox->vport->vpi : 0,
7157 			mbx->mbxCommand, phba->pport->port_state,
7158 			psli->sli_flag, flag);
7159 
7160 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
7161 		if (pmbox->vport) {
7162 			lpfc_debugfs_disc_trc(pmbox->vport,
7163 				LPFC_DISC_TRC_MBOX_VPORT,
7164 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
7165 				(uint32_t)mbx->mbxCommand,
7166 				mbx->un.varWords[0], mbx->un.varWords[1]);
7167 		}
7168 		else {
7169 			lpfc_debugfs_disc_trc(phba->pport,
7170 				LPFC_DISC_TRC_MBOX,
7171 				"MBOX Send:       cmd:x%x mb:x%x x%x",
7172 				(uint32_t)mbx->mbxCommand,
7173 				mbx->un.varWords[0], mbx->un.varWords[1]);
7174 		}
7175 	}
7176 
7177 	psli->slistat.mbox_cmd++;
7178 	evtctr = psli->slistat.mbox_event;
7179 
7180 	/* next set own bit for the adapter and copy over command word */
7181 	mbx->mbxOwner = OWN_CHIP;
7182 
7183 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7184 		/* Populate mbox extension offset word. */
7185 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
7186 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
7187 				= (uint8_t *)phba->mbox_ext
7188 				  - (uint8_t *)phba->mbox;
7189 		}
7190 
7191 		/* Copy the mailbox extension data */
7192 		if (pmbox->in_ext_byte_len && pmbox->context2) {
7193 			lpfc_sli_pcimem_bcopy(pmbox->context2,
7194 				(uint8_t *)phba->mbox_ext,
7195 				pmbox->in_ext_byte_len);
7196 		}
7197 		/* Copy command data to host SLIM area */
7198 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
7199 	} else {
7200 		/* Populate mbox extension offset word. */
7201 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
7202 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
7203 				= MAILBOX_HBA_EXT_OFFSET;
7204 
7205 		/* Copy the mailbox extension data */
7206 		if (pmbox->in_ext_byte_len && pmbox->context2) {
7207 			lpfc_memcpy_to_slim(phba->MBslimaddr +
7208 				MAILBOX_HBA_EXT_OFFSET,
7209 				pmbox->context2, pmbox->in_ext_byte_len);
7210 
7211 		}
7212 		if (mbx->mbxCommand == MBX_CONFIG_PORT) {
7213 			/* copy command data into host mbox for cmpl */
7214 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
7215 		}
7216 
7217 		/* First copy mbox command data to HBA SLIM, skip past first
7218 		   word */
7219 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
7220 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
7221 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
7222 
7223 		/* Next copy over first word, with mbxOwner set */
7224 		ldata = *((uint32_t *)mbx);
7225 		to_slim = phba->MBslimaddr;
7226 		writel(ldata, to_slim);
7227 		readl(to_slim); /* flush */
7228 
7229 		if (mbx->mbxCommand == MBX_CONFIG_PORT) {
7230 			/* switch over to host mailbox */
7231 			psli->sli_flag |= LPFC_SLI_ACTIVE;
7232 		}
7233 	}
7234 
7235 	wmb();
7236 
7237 	switch (flag) {
7238 	case MBX_NOWAIT:
7239 		/* Set up reference to mailbox command */
7240 		psli->mbox_active = pmbox;
7241 		/* Interrupt board to do it */
7242 		writel(CA_MBATT, phba->CAregaddr);
7243 		readl(phba->CAregaddr); /* flush */
7244 		/* Don't wait for it to finish, just return */
7245 		break;
7246 
7247 	case MBX_POLL:
7248 		/* Set up null reference to mailbox command */
7249 		psli->mbox_active = NULL;
7250 		/* Interrupt board to do it */
7251 		writel(CA_MBATT, phba->CAregaddr);
7252 		readl(phba->CAregaddr); /* flush */
7253 
7254 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7255 			/* First read mbox status word */
7256 			word0 = *((uint32_t *)phba->mbox);
7257 			word0 = le32_to_cpu(word0);
7258 		} else {
7259 			/* First read mbox status word */
7260 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
7261 				spin_unlock_irqrestore(&phba->hbalock,
7262 						       drvr_flag);
7263 				goto out_not_finished;
7264 			}
7265 		}
7266 
7267 		/* Read the HBA Host Attention Register */
7268 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
7269 			spin_unlock_irqrestore(&phba->hbalock,
7270 						       drvr_flag);
7271 			goto out_not_finished;
7272 		}
7273 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
7274 							1000) + jiffies;
7275 		i = 0;
7276 		/* Wait for command to complete */
7277 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
7278 		       (!(ha_copy & HA_MBATT) &&
7279 			(phba->link_state > LPFC_WARM_START))) {
7280 			if (time_after(jiffies, timeout)) {
7281 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7282 				spin_unlock_irqrestore(&phba->hbalock,
7283 						       drvr_flag);
7284 				goto out_not_finished;
7285 			}
7286 
7287 			/* Check if we took a mbox interrupt while we were
7288 			   polling */
7289 			if (((word0 & OWN_CHIP) != OWN_CHIP)
7290 			    && (evtctr != psli->slistat.mbox_event))
7291 				break;
7292 
7293 			if (i++ > 10) {
7294 				spin_unlock_irqrestore(&phba->hbalock,
7295 						       drvr_flag);
7296 				msleep(1);
7297 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
7298 			}
7299 
7300 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7301 				/* First copy command data */
7302 				word0 = *((uint32_t *)phba->mbox);
7303 				word0 = le32_to_cpu(word0);
7304 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
7305 					MAILBOX_t *slimmb;
7306 					uint32_t slimword0;
7307 					/* Check real SLIM for any errors */
7308 					slimword0 = readl(phba->MBslimaddr);
7309 					slimmb = (MAILBOX_t *) & slimword0;
7310 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
7311 					    && slimmb->mbxStatus) {
7312 						psli->sli_flag &=
7313 						    ~LPFC_SLI_ACTIVE;
7314 						word0 = slimword0;
7315 					}
7316 				}
7317 			} else {
7318 				/* First copy command data */
7319 				word0 = readl(phba->MBslimaddr);
7320 			}
7321 			/* Read the HBA Host Attention Register */
7322 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
7323 				spin_unlock_irqrestore(&phba->hbalock,
7324 						       drvr_flag);
7325 				goto out_not_finished;
7326 			}
7327 		}
7328 
7329 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7330 			/* copy results back to user */
7331 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx, MAILBOX_CMD_SIZE);
7332 			/* Copy the mailbox extension data */
7333 			if (pmbox->out_ext_byte_len && pmbox->context2) {
7334 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
7335 						      pmbox->context2,
7336 						      pmbox->out_ext_byte_len);
7337 			}
7338 		} else {
7339 			/* First copy command data */
7340 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
7341 							MAILBOX_CMD_SIZE);
7342 			/* Copy the mailbox extension data */
7343 			if (pmbox->out_ext_byte_len && pmbox->context2) {
7344 				lpfc_memcpy_from_slim(pmbox->context2,
7345 					phba->MBslimaddr +
7346 					MAILBOX_HBA_EXT_OFFSET,
7347 					pmbox->out_ext_byte_len);
7348 			}
7349 		}
7350 
7351 		writel(HA_MBATT, phba->HAregaddr);
7352 		readl(phba->HAregaddr); /* flush */
7353 
7354 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7355 		status = mbx->mbxStatus;
7356 	}
7357 
7358 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7359 	return status;
7360 
7361 out_not_finished:
7362 	if (processing_queue) {
7363 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
7364 		lpfc_mbox_cmpl_put(phba, pmbox);
7365 	}
7366 	return MBX_NOT_FINISHED;
7367 }
7368 
7369 /**
7370  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
7371  * @phba: Pointer to HBA context object.
7372  *
7373  * The function blocks the posting of SLI4 asynchronous mailbox commands from
7374  * the driver internal pending mailbox queue. It will then try to wait out the
7375  * possible outstanding mailbox command before return.
7376  *
7377  * Returns:
7378  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
7379  * 	the outstanding mailbox command timed out.
7380  **/
7381 static int
7382 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
7383 {
7384 	struct lpfc_sli *psli = &phba->sli;
7385 	int rc = 0;
7386 	unsigned long timeout = 0;
7387 
7388 	/* Mark the asynchronous mailbox command posting as blocked */
7389 	spin_lock_irq(&phba->hbalock);
7390 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
7391 	/* Determine how long we might wait for the active mailbox
7392 	 * command to be gracefully completed by firmware.
7393 	 */
7394 	if (phba->sli.mbox_active)
7395 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
7396 						phba->sli.mbox_active) *
7397 						1000) + jiffies;
7398 	spin_unlock_irq(&phba->hbalock);
7399 
7400 	/* Make sure the mailbox is really active */
7401 	if (timeout)
7402 		lpfc_sli4_process_missed_mbox_completions(phba);
7403 
7404 	/* Wait for the outstnading mailbox command to complete */
7405 	while (phba->sli.mbox_active) {
7406 		/* Check active mailbox complete status every 2ms */
7407 		msleep(2);
7408 		if (time_after(jiffies, timeout)) {
7409 			/* Timeout, marked the outstanding cmd not complete */
7410 			rc = 1;
7411 			break;
7412 		}
7413 	}
7414 
7415 	/* Can not cleanly block async mailbox command, fails it */
7416 	if (rc) {
7417 		spin_lock_irq(&phba->hbalock);
7418 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7419 		spin_unlock_irq(&phba->hbalock);
7420 	}
7421 	return rc;
7422 }
7423 
7424 /**
7425  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
7426  * @phba: Pointer to HBA context object.
7427  *
7428  * The function unblocks and resume posting of SLI4 asynchronous mailbox
7429  * commands from the driver internal pending mailbox queue. It makes sure
7430  * that there is no outstanding mailbox command before resuming posting
7431  * asynchronous mailbox commands. If, for any reason, there is outstanding
7432  * mailbox command, it will try to wait it out before resuming asynchronous
7433  * mailbox command posting.
7434  **/
7435 static void
7436 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
7437 {
7438 	struct lpfc_sli *psli = &phba->sli;
7439 
7440 	spin_lock_irq(&phba->hbalock);
7441 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
7442 		/* Asynchronous mailbox posting is not blocked, do nothing */
7443 		spin_unlock_irq(&phba->hbalock);
7444 		return;
7445 	}
7446 
7447 	/* Outstanding synchronous mailbox command is guaranteed to be done,
7448 	 * successful or timeout, after timing-out the outstanding mailbox
7449 	 * command shall always be removed, so just unblock posting async
7450 	 * mailbox command and resume
7451 	 */
7452 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7453 	spin_unlock_irq(&phba->hbalock);
7454 
7455 	/* wake up worker thread to post asynchronlous mailbox command */
7456 	lpfc_worker_wake_up(phba);
7457 }
7458 
7459 /**
7460  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
7461  * @phba: Pointer to HBA context object.
7462  * @mboxq: Pointer to mailbox object.
7463  *
7464  * The function waits for the bootstrap mailbox register ready bit from
7465  * port for twice the regular mailbox command timeout value.
7466  *
7467  *      0 - no timeout on waiting for bootstrap mailbox register ready.
7468  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
7469  **/
7470 static int
7471 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
7472 {
7473 	uint32_t db_ready;
7474 	unsigned long timeout;
7475 	struct lpfc_register bmbx_reg;
7476 
7477 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
7478 				   * 1000) + jiffies;
7479 
7480 	do {
7481 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
7482 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
7483 		if (!db_ready)
7484 			msleep(2);
7485 
7486 		if (time_after(jiffies, timeout))
7487 			return MBXERR_ERROR;
7488 	} while (!db_ready);
7489 
7490 	return 0;
7491 }
7492 
7493 /**
7494  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
7495  * @phba: Pointer to HBA context object.
7496  * @mboxq: Pointer to mailbox object.
7497  *
7498  * The function posts a mailbox to the port.  The mailbox is expected
7499  * to be comletely filled in and ready for the port to operate on it.
7500  * This routine executes a synchronous completion operation on the
7501  * mailbox by polling for its completion.
7502  *
7503  * The caller must not be holding any locks when calling this routine.
7504  *
7505  * Returns:
7506  *	MBX_SUCCESS - mailbox posted successfully
7507  *	Any of the MBX error values.
7508  **/
7509 static int
7510 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
7511 {
7512 	int rc = MBX_SUCCESS;
7513 	unsigned long iflag;
7514 	uint32_t mcqe_status;
7515 	uint32_t mbx_cmnd;
7516 	struct lpfc_sli *psli = &phba->sli;
7517 	struct lpfc_mqe *mb = &mboxq->u.mqe;
7518 	struct lpfc_bmbx_create *mbox_rgn;
7519 	struct dma_address *dma_address;
7520 
7521 	/*
7522 	 * Only one mailbox can be active to the bootstrap mailbox region
7523 	 * at a time and there is no queueing provided.
7524 	 */
7525 	spin_lock_irqsave(&phba->hbalock, iflag);
7526 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
7527 		spin_unlock_irqrestore(&phba->hbalock, iflag);
7528 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7529 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
7530 				"cannot issue Data: x%x x%x\n",
7531 				mboxq->vport ? mboxq->vport->vpi : 0,
7532 				mboxq->u.mb.mbxCommand,
7533 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7534 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7535 				psli->sli_flag, MBX_POLL);
7536 		return MBXERR_ERROR;
7537 	}
7538 	/* The server grabs the token and owns it until release */
7539 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
7540 	phba->sli.mbox_active = mboxq;
7541 	spin_unlock_irqrestore(&phba->hbalock, iflag);
7542 
7543 	/* wait for bootstrap mbox register for readyness */
7544 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7545 	if (rc)
7546 		goto exit;
7547 
7548 	/*
7549 	 * Initialize the bootstrap memory region to avoid stale data areas
7550 	 * in the mailbox post.  Then copy the caller's mailbox contents to
7551 	 * the bmbx mailbox region.
7552 	 */
7553 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
7554 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
7555 	lpfc_sli_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
7556 			      sizeof(struct lpfc_mqe));
7557 
7558 	/* Post the high mailbox dma address to the port and wait for ready. */
7559 	dma_address = &phba->sli4_hba.bmbx.dma_address;
7560 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
7561 
7562 	/* wait for bootstrap mbox register for hi-address write done */
7563 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7564 	if (rc)
7565 		goto exit;
7566 
7567 	/* Post the low mailbox dma address to the port. */
7568 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
7569 
7570 	/* wait for bootstrap mbox register for low address write done */
7571 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7572 	if (rc)
7573 		goto exit;
7574 
7575 	/*
7576 	 * Read the CQ to ensure the mailbox has completed.
7577 	 * If so, update the mailbox status so that the upper layers
7578 	 * can complete the request normally.
7579 	 */
7580 	lpfc_sli_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
7581 			      sizeof(struct lpfc_mqe));
7582 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
7583 	lpfc_sli_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
7584 			      sizeof(struct lpfc_mcqe));
7585 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
7586 	/*
7587 	 * When the CQE status indicates a failure and the mailbox status
7588 	 * indicates success then copy the CQE status into the mailbox status
7589 	 * (and prefix it with x4000).
7590 	 */
7591 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
7592 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
7593 			bf_set(lpfc_mqe_status, mb,
7594 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
7595 		rc = MBXERR_ERROR;
7596 	} else
7597 		lpfc_sli4_swap_str(phba, mboxq);
7598 
7599 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7600 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
7601 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
7602 			" x%x x%x CQ: x%x x%x x%x x%x\n",
7603 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
7604 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7605 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7606 			bf_get(lpfc_mqe_status, mb),
7607 			mb->un.mb_words[0], mb->un.mb_words[1],
7608 			mb->un.mb_words[2], mb->un.mb_words[3],
7609 			mb->un.mb_words[4], mb->un.mb_words[5],
7610 			mb->un.mb_words[6], mb->un.mb_words[7],
7611 			mb->un.mb_words[8], mb->un.mb_words[9],
7612 			mb->un.mb_words[10], mb->un.mb_words[11],
7613 			mb->un.mb_words[12], mboxq->mcqe.word0,
7614 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
7615 			mboxq->mcqe.trailer);
7616 exit:
7617 	/* We are holding the token, no needed for lock when release */
7618 	spin_lock_irqsave(&phba->hbalock, iflag);
7619 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7620 	phba->sli.mbox_active = NULL;
7621 	spin_unlock_irqrestore(&phba->hbalock, iflag);
7622 	return rc;
7623 }
7624 
7625 /**
7626  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
7627  * @phba: Pointer to HBA context object.
7628  * @pmbox: Pointer to mailbox object.
7629  * @flag: Flag indicating how the mailbox need to be processed.
7630  *
7631  * This function is called by discovery code and HBA management code to submit
7632  * a mailbox command to firmware with SLI-4 interface spec.
7633  *
7634  * Return codes the caller owns the mailbox command after the return of the
7635  * function.
7636  **/
7637 static int
7638 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
7639 		       uint32_t flag)
7640 {
7641 	struct lpfc_sli *psli = &phba->sli;
7642 	unsigned long iflags;
7643 	int rc;
7644 
7645 	/* dump from issue mailbox command if setup */
7646 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
7647 
7648 	rc = lpfc_mbox_dev_check(phba);
7649 	if (unlikely(rc)) {
7650 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7651 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
7652 				"cannot issue Data: x%x x%x\n",
7653 				mboxq->vport ? mboxq->vport->vpi : 0,
7654 				mboxq->u.mb.mbxCommand,
7655 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7656 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7657 				psli->sli_flag, flag);
7658 		goto out_not_finished;
7659 	}
7660 
7661 	/* Detect polling mode and jump to a handler */
7662 	if (!phba->sli4_hba.intr_enable) {
7663 		if (flag == MBX_POLL)
7664 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
7665 		else
7666 			rc = -EIO;
7667 		if (rc != MBX_SUCCESS)
7668 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7669 					"(%d):2541 Mailbox command x%x "
7670 					"(x%x/x%x) failure: "
7671 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
7672 					"Data: x%x x%x\n,",
7673 					mboxq->vport ? mboxq->vport->vpi : 0,
7674 					mboxq->u.mb.mbxCommand,
7675 					lpfc_sli_config_mbox_subsys_get(phba,
7676 									mboxq),
7677 					lpfc_sli_config_mbox_opcode_get(phba,
7678 									mboxq),
7679 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
7680 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
7681 					bf_get(lpfc_mcqe_ext_status,
7682 					       &mboxq->mcqe),
7683 					psli->sli_flag, flag);
7684 		return rc;
7685 	} else if (flag == MBX_POLL) {
7686 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7687 				"(%d):2542 Try to issue mailbox command "
7688 				"x%x (x%x/x%x) synchronously ahead of async"
7689 				"mailbox command queue: x%x x%x\n",
7690 				mboxq->vport ? mboxq->vport->vpi : 0,
7691 				mboxq->u.mb.mbxCommand,
7692 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7693 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7694 				psli->sli_flag, flag);
7695 		/* Try to block the asynchronous mailbox posting */
7696 		rc = lpfc_sli4_async_mbox_block(phba);
7697 		if (!rc) {
7698 			/* Successfully blocked, now issue sync mbox cmd */
7699 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
7700 			if (rc != MBX_SUCCESS)
7701 				lpfc_printf_log(phba, KERN_WARNING,
7702 					LOG_MBOX | LOG_SLI,
7703 					"(%d):2597 Sync Mailbox command "
7704 					"x%x (x%x/x%x) failure: "
7705 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
7706 					"Data: x%x x%x\n,",
7707 					mboxq->vport ? mboxq->vport->vpi : 0,
7708 					mboxq->u.mb.mbxCommand,
7709 					lpfc_sli_config_mbox_subsys_get(phba,
7710 									mboxq),
7711 					lpfc_sli_config_mbox_opcode_get(phba,
7712 									mboxq),
7713 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
7714 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
7715 					bf_get(lpfc_mcqe_ext_status,
7716 					       &mboxq->mcqe),
7717 					psli->sli_flag, flag);
7718 			/* Unblock the async mailbox posting afterward */
7719 			lpfc_sli4_async_mbox_unblock(phba);
7720 		}
7721 		return rc;
7722 	}
7723 
7724 	/* Now, interrupt mode asynchrous mailbox command */
7725 	rc = lpfc_mbox_cmd_check(phba, mboxq);
7726 	if (rc) {
7727 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7728 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
7729 				"cannot issue Data: x%x x%x\n",
7730 				mboxq->vport ? mboxq->vport->vpi : 0,
7731 				mboxq->u.mb.mbxCommand,
7732 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7733 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7734 				psli->sli_flag, flag);
7735 		goto out_not_finished;
7736 	}
7737 
7738 	/* Put the mailbox command to the driver internal FIFO */
7739 	psli->slistat.mbox_busy++;
7740 	spin_lock_irqsave(&phba->hbalock, iflags);
7741 	lpfc_mbox_put(phba, mboxq);
7742 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7743 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7744 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
7745 			"x%x (x%x/x%x) x%x x%x x%x\n",
7746 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
7747 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7748 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7749 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7750 			phba->pport->port_state,
7751 			psli->sli_flag, MBX_NOWAIT);
7752 	/* Wake up worker thread to transport mailbox command from head */
7753 	lpfc_worker_wake_up(phba);
7754 
7755 	return MBX_BUSY;
7756 
7757 out_not_finished:
7758 	return MBX_NOT_FINISHED;
7759 }
7760 
7761 /**
7762  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
7763  * @phba: Pointer to HBA context object.
7764  *
7765  * This function is called by worker thread to send a mailbox command to
7766  * SLI4 HBA firmware.
7767  *
7768  **/
7769 int
7770 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
7771 {
7772 	struct lpfc_sli *psli = &phba->sli;
7773 	LPFC_MBOXQ_t *mboxq;
7774 	int rc = MBX_SUCCESS;
7775 	unsigned long iflags;
7776 	struct lpfc_mqe *mqe;
7777 	uint32_t mbx_cmnd;
7778 
7779 	/* Check interrupt mode before post async mailbox command */
7780 	if (unlikely(!phba->sli4_hba.intr_enable))
7781 		return MBX_NOT_FINISHED;
7782 
7783 	/* Check for mailbox command service token */
7784 	spin_lock_irqsave(&phba->hbalock, iflags);
7785 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
7786 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7787 		return MBX_NOT_FINISHED;
7788 	}
7789 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
7790 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7791 		return MBX_NOT_FINISHED;
7792 	}
7793 	if (unlikely(phba->sli.mbox_active)) {
7794 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7795 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7796 				"0384 There is pending active mailbox cmd\n");
7797 		return MBX_NOT_FINISHED;
7798 	}
7799 	/* Take the mailbox command service token */
7800 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
7801 
7802 	/* Get the next mailbox command from head of queue */
7803 	mboxq = lpfc_mbox_get(phba);
7804 
7805 	/* If no more mailbox command waiting for post, we're done */
7806 	if (!mboxq) {
7807 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7808 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7809 		return MBX_SUCCESS;
7810 	}
7811 	phba->sli.mbox_active = mboxq;
7812 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7813 
7814 	/* Check device readiness for posting mailbox command */
7815 	rc = lpfc_mbox_dev_check(phba);
7816 	if (unlikely(rc))
7817 		/* Driver clean routine will clean up pending mailbox */
7818 		goto out_not_finished;
7819 
7820 	/* Prepare the mbox command to be posted */
7821 	mqe = &mboxq->u.mqe;
7822 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
7823 
7824 	/* Start timer for the mbox_tmo and log some mailbox post messages */
7825 	mod_timer(&psli->mbox_tmo, (jiffies +
7826 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
7827 
7828 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7829 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
7830 			"x%x x%x\n",
7831 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
7832 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7833 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7834 			phba->pport->port_state, psli->sli_flag);
7835 
7836 	if (mbx_cmnd != MBX_HEARTBEAT) {
7837 		if (mboxq->vport) {
7838 			lpfc_debugfs_disc_trc(mboxq->vport,
7839 				LPFC_DISC_TRC_MBOX_VPORT,
7840 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
7841 				mbx_cmnd, mqe->un.mb_words[0],
7842 				mqe->un.mb_words[1]);
7843 		} else {
7844 			lpfc_debugfs_disc_trc(phba->pport,
7845 				LPFC_DISC_TRC_MBOX,
7846 				"MBOX Send: cmd:x%x mb:x%x x%x",
7847 				mbx_cmnd, mqe->un.mb_words[0],
7848 				mqe->un.mb_words[1]);
7849 		}
7850 	}
7851 	psli->slistat.mbox_cmd++;
7852 
7853 	/* Post the mailbox command to the port */
7854 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
7855 	if (rc != MBX_SUCCESS) {
7856 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7857 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
7858 				"cannot issue Data: x%x x%x\n",
7859 				mboxq->vport ? mboxq->vport->vpi : 0,
7860 				mboxq->u.mb.mbxCommand,
7861 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7862 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7863 				psli->sli_flag, MBX_NOWAIT);
7864 		goto out_not_finished;
7865 	}
7866 
7867 	return rc;
7868 
7869 out_not_finished:
7870 	spin_lock_irqsave(&phba->hbalock, iflags);
7871 	if (phba->sli.mbox_active) {
7872 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
7873 		__lpfc_mbox_cmpl_put(phba, mboxq);
7874 		/* Release the token */
7875 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7876 		phba->sli.mbox_active = NULL;
7877 	}
7878 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7879 
7880 	return MBX_NOT_FINISHED;
7881 }
7882 
7883 /**
7884  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
7885  * @phba: Pointer to HBA context object.
7886  * @pmbox: Pointer to mailbox object.
7887  * @flag: Flag indicating how the mailbox need to be processed.
7888  *
7889  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
7890  * the API jump table function pointer from the lpfc_hba struct.
7891  *
7892  * Return codes the caller owns the mailbox command after the return of the
7893  * function.
7894  **/
7895 int
7896 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
7897 {
7898 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
7899 }
7900 
7901 /**
7902  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
7903  * @phba: The hba struct for which this call is being executed.
7904  * @dev_grp: The HBA PCI-Device group number.
7905  *
7906  * This routine sets up the mbox interface API function jump table in @phba
7907  * struct.
7908  * Returns: 0 - success, -ENODEV - failure.
7909  **/
7910 int
7911 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
7912 {
7913 
7914 	switch (dev_grp) {
7915 	case LPFC_PCI_DEV_LP:
7916 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
7917 		phba->lpfc_sli_handle_slow_ring_event =
7918 				lpfc_sli_handle_slow_ring_event_s3;
7919 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
7920 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
7921 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
7922 		break;
7923 	case LPFC_PCI_DEV_OC:
7924 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
7925 		phba->lpfc_sli_handle_slow_ring_event =
7926 				lpfc_sli_handle_slow_ring_event_s4;
7927 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
7928 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
7929 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
7930 		break;
7931 	default:
7932 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7933 				"1420 Invalid HBA PCI-device group: 0x%x\n",
7934 				dev_grp);
7935 		return -ENODEV;
7936 		break;
7937 	}
7938 	return 0;
7939 }
7940 
7941 /**
7942  * __lpfc_sli_ringtx_put - Add an iocb to the txq
7943  * @phba: Pointer to HBA context object.
7944  * @pring: Pointer to driver SLI ring object.
7945  * @piocb: Pointer to address of newly added command iocb.
7946  *
7947  * This function is called with hbalock held to add a command
7948  * iocb to the txq when SLI layer cannot submit the command iocb
7949  * to the ring.
7950  **/
7951 void
7952 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
7953 		    struct lpfc_iocbq *piocb)
7954 {
7955 	lockdep_assert_held(&phba->hbalock);
7956 	/* Insert the caller's iocb in the txq tail for later processing. */
7957 	list_add_tail(&piocb->list, &pring->txq);
7958 }
7959 
7960 /**
7961  * lpfc_sli_next_iocb - Get the next iocb in the txq
7962  * @phba: Pointer to HBA context object.
7963  * @pring: Pointer to driver SLI ring object.
7964  * @piocb: Pointer to address of newly added command iocb.
7965  *
7966  * This function is called with hbalock held before a new
7967  * iocb is submitted to the firmware. This function checks
7968  * txq to flush the iocbs in txq to Firmware before
7969  * submitting new iocbs to the Firmware.
7970  * If there are iocbs in the txq which need to be submitted
7971  * to firmware, lpfc_sli_next_iocb returns the first element
7972  * of the txq after dequeuing it from txq.
7973  * If there is no iocb in the txq then the function will return
7974  * *piocb and *piocb is set to NULL. Caller needs to check
7975  * *piocb to find if there are more commands in the txq.
7976  **/
7977 static struct lpfc_iocbq *
7978 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
7979 		   struct lpfc_iocbq **piocb)
7980 {
7981 	struct lpfc_iocbq * nextiocb;
7982 
7983 	lockdep_assert_held(&phba->hbalock);
7984 
7985 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
7986 	if (!nextiocb) {
7987 		nextiocb = *piocb;
7988 		*piocb = NULL;
7989 	}
7990 
7991 	return nextiocb;
7992 }
7993 
7994 /**
7995  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
7996  * @phba: Pointer to HBA context object.
7997  * @ring_number: SLI ring number to issue iocb on.
7998  * @piocb: Pointer to command iocb.
7999  * @flag: Flag indicating if this command can be put into txq.
8000  *
8001  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
8002  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
8003  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
8004  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
8005  * this function allows only iocbs for posting buffers. This function finds
8006  * next available slot in the command ring and posts the command to the
8007  * available slot and writes the port attention register to request HBA start
8008  * processing new iocb. If there is no slot available in the ring and
8009  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
8010  * the function returns IOCB_BUSY.
8011  *
8012  * This function is called with hbalock held. The function will return success
8013  * after it successfully submit the iocb to firmware or after adding to the
8014  * txq.
8015  **/
8016 static int
8017 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
8018 		    struct lpfc_iocbq *piocb, uint32_t flag)
8019 {
8020 	struct lpfc_iocbq *nextiocb;
8021 	IOCB_t *iocb;
8022 	struct lpfc_sli_ring *pring = &phba->sli.ring[ring_number];
8023 
8024 	lockdep_assert_held(&phba->hbalock);
8025 
8026 	if (piocb->iocb_cmpl && (!piocb->vport) &&
8027 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
8028 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
8029 		lpfc_printf_log(phba, KERN_ERR,
8030 				LOG_SLI | LOG_VPORT,
8031 				"1807 IOCB x%x failed. No vport\n",
8032 				piocb->iocb.ulpCommand);
8033 		dump_stack();
8034 		return IOCB_ERROR;
8035 	}
8036 
8037 
8038 	/* If the PCI channel is in offline state, do not post iocbs. */
8039 	if (unlikely(pci_channel_offline(phba->pcidev)))
8040 		return IOCB_ERROR;
8041 
8042 	/* If HBA has a deferred error attention, fail the iocb. */
8043 	if (unlikely(phba->hba_flag & DEFER_ERATT))
8044 		return IOCB_ERROR;
8045 
8046 	/*
8047 	 * We should never get an IOCB if we are in a < LINK_DOWN state
8048 	 */
8049 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
8050 		return IOCB_ERROR;
8051 
8052 	/*
8053 	 * Check to see if we are blocking IOCB processing because of a
8054 	 * outstanding event.
8055 	 */
8056 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
8057 		goto iocb_busy;
8058 
8059 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
8060 		/*
8061 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
8062 		 * can be issued if the link is not up.
8063 		 */
8064 		switch (piocb->iocb.ulpCommand) {
8065 		case CMD_GEN_REQUEST64_CR:
8066 		case CMD_GEN_REQUEST64_CX:
8067 			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
8068 				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
8069 					FC_RCTL_DD_UNSOL_CMD) ||
8070 				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
8071 					MENLO_TRANSPORT_TYPE))
8072 
8073 				goto iocb_busy;
8074 			break;
8075 		case CMD_QUE_RING_BUF_CN:
8076 		case CMD_QUE_RING_BUF64_CN:
8077 			/*
8078 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
8079 			 * completion, iocb_cmpl MUST be 0.
8080 			 */
8081 			if (piocb->iocb_cmpl)
8082 				piocb->iocb_cmpl = NULL;
8083 			/*FALLTHROUGH*/
8084 		case CMD_CREATE_XRI_CR:
8085 		case CMD_CLOSE_XRI_CN:
8086 		case CMD_CLOSE_XRI_CX:
8087 			break;
8088 		default:
8089 			goto iocb_busy;
8090 		}
8091 
8092 	/*
8093 	 * For FCP commands, we must be in a state where we can process link
8094 	 * attention events.
8095 	 */
8096 	} else if (unlikely(pring->ringno == phba->sli.fcp_ring &&
8097 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
8098 		goto iocb_busy;
8099 	}
8100 
8101 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
8102 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
8103 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
8104 
8105 	if (iocb)
8106 		lpfc_sli_update_ring(phba, pring);
8107 	else
8108 		lpfc_sli_update_full_ring(phba, pring);
8109 
8110 	if (!piocb)
8111 		return IOCB_SUCCESS;
8112 
8113 	goto out_busy;
8114 
8115  iocb_busy:
8116 	pring->stats.iocb_cmd_delay++;
8117 
8118  out_busy:
8119 
8120 	if (!(flag & SLI_IOCB_RET_IOCB)) {
8121 		__lpfc_sli_ringtx_put(phba, pring, piocb);
8122 		return IOCB_SUCCESS;
8123 	}
8124 
8125 	return IOCB_BUSY;
8126 }
8127 
8128 /**
8129  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
8130  * @phba: Pointer to HBA context object.
8131  * @piocb: Pointer to command iocb.
8132  * @sglq: Pointer to the scatter gather queue object.
8133  *
8134  * This routine converts the bpl or bde that is in the IOCB
8135  * to a sgl list for the sli4 hardware. The physical address
8136  * of the bpl/bde is converted back to a virtual address.
8137  * If the IOCB contains a BPL then the list of BDE's is
8138  * converted to sli4_sge's. If the IOCB contains a single
8139  * BDE then it is converted to a single sli_sge.
8140  * The IOCB is still in cpu endianess so the contents of
8141  * the bpl can be used without byte swapping.
8142  *
8143  * Returns valid XRI = Success, NO_XRI = Failure.
8144 **/
8145 static uint16_t
8146 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
8147 		struct lpfc_sglq *sglq)
8148 {
8149 	uint16_t xritag = NO_XRI;
8150 	struct ulp_bde64 *bpl = NULL;
8151 	struct ulp_bde64 bde;
8152 	struct sli4_sge *sgl  = NULL;
8153 	struct lpfc_dmabuf *dmabuf;
8154 	IOCB_t *icmd;
8155 	int numBdes = 0;
8156 	int i = 0;
8157 	uint32_t offset = 0; /* accumulated offset in the sg request list */
8158 	int inbound = 0; /* number of sg reply entries inbound from firmware */
8159 
8160 	if (!piocbq || !sglq)
8161 		return xritag;
8162 
8163 	sgl  = (struct sli4_sge *)sglq->sgl;
8164 	icmd = &piocbq->iocb;
8165 	if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
8166 		return sglq->sli4_xritag;
8167 	if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
8168 		numBdes = icmd->un.genreq64.bdl.bdeSize /
8169 				sizeof(struct ulp_bde64);
8170 		/* The addrHigh and addrLow fields within the IOCB
8171 		 * have not been byteswapped yet so there is no
8172 		 * need to swap them back.
8173 		 */
8174 		if (piocbq->context3)
8175 			dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
8176 		else
8177 			return xritag;
8178 
8179 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
8180 		if (!bpl)
8181 			return xritag;
8182 
8183 		for (i = 0; i < numBdes; i++) {
8184 			/* Should already be byte swapped. */
8185 			sgl->addr_hi = bpl->addrHigh;
8186 			sgl->addr_lo = bpl->addrLow;
8187 
8188 			sgl->word2 = le32_to_cpu(sgl->word2);
8189 			if ((i+1) == numBdes)
8190 				bf_set(lpfc_sli4_sge_last, sgl, 1);
8191 			else
8192 				bf_set(lpfc_sli4_sge_last, sgl, 0);
8193 			/* swap the size field back to the cpu so we
8194 			 * can assign it to the sgl.
8195 			 */
8196 			bde.tus.w = le32_to_cpu(bpl->tus.w);
8197 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
8198 			/* The offsets in the sgl need to be accumulated
8199 			 * separately for the request and reply lists.
8200 			 * The request is always first, the reply follows.
8201 			 */
8202 			if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
8203 				/* add up the reply sg entries */
8204 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
8205 					inbound++;
8206 				/* first inbound? reset the offset */
8207 				if (inbound == 1)
8208 					offset = 0;
8209 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
8210 				bf_set(lpfc_sli4_sge_type, sgl,
8211 					LPFC_SGE_TYPE_DATA);
8212 				offset += bde.tus.f.bdeSize;
8213 			}
8214 			sgl->word2 = cpu_to_le32(sgl->word2);
8215 			bpl++;
8216 			sgl++;
8217 		}
8218 	} else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
8219 			/* The addrHigh and addrLow fields of the BDE have not
8220 			 * been byteswapped yet so they need to be swapped
8221 			 * before putting them in the sgl.
8222 			 */
8223 			sgl->addr_hi =
8224 				cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
8225 			sgl->addr_lo =
8226 				cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
8227 			sgl->word2 = le32_to_cpu(sgl->word2);
8228 			bf_set(lpfc_sli4_sge_last, sgl, 1);
8229 			sgl->word2 = cpu_to_le32(sgl->word2);
8230 			sgl->sge_len =
8231 				cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
8232 	}
8233 	return sglq->sli4_xritag;
8234 }
8235 
8236 /**
8237  * lpfc_sli_iocb2wqe - Convert the IOCB to a work queue entry.
8238  * @phba: Pointer to HBA context object.
8239  * @piocb: Pointer to command iocb.
8240  * @wqe: Pointer to the work queue entry.
8241  *
8242  * This routine converts the iocb command to its Work Queue Entry
8243  * equivalent. The wqe pointer should not have any fields set when
8244  * this routine is called because it will memcpy over them.
8245  * This routine does not set the CQ_ID or the WQEC bits in the
8246  * wqe.
8247  *
8248  * Returns: 0 = Success, IOCB_ERROR = Failure.
8249  **/
8250 static int
8251 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
8252 		union lpfc_wqe *wqe)
8253 {
8254 	uint32_t xmit_len = 0, total_len = 0;
8255 	uint8_t ct = 0;
8256 	uint32_t fip;
8257 	uint32_t abort_tag;
8258 	uint8_t command_type = ELS_COMMAND_NON_FIP;
8259 	uint8_t cmnd;
8260 	uint16_t xritag;
8261 	uint16_t abrt_iotag;
8262 	struct lpfc_iocbq *abrtiocbq;
8263 	struct ulp_bde64 *bpl = NULL;
8264 	uint32_t els_id = LPFC_ELS_ID_DEFAULT;
8265 	int numBdes, i;
8266 	struct ulp_bde64 bde;
8267 	struct lpfc_nodelist *ndlp;
8268 	uint32_t *pcmd;
8269 	uint32_t if_type;
8270 
8271 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
8272 	/* The fcp commands will set command type */
8273 	if (iocbq->iocb_flag &  LPFC_IO_FCP)
8274 		command_type = FCP_COMMAND;
8275 	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
8276 		command_type = ELS_COMMAND_FIP;
8277 	else
8278 		command_type = ELS_COMMAND_NON_FIP;
8279 
8280 	if (phba->fcp_embed_io)
8281 		memset(wqe, 0, sizeof(union lpfc_wqe128));
8282 	/* Some of the fields are in the right position already */
8283 	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
8284 	wqe->generic.wqe_com.word7 = 0; /* The ct field has moved so reset */
8285 	wqe->generic.wqe_com.word10 = 0;
8286 
8287 	abort_tag = (uint32_t) iocbq->iotag;
8288 	xritag = iocbq->sli4_xritag;
8289 	/* words0-2 bpl convert bde */
8290 	if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
8291 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
8292 				sizeof(struct ulp_bde64);
8293 		bpl  = (struct ulp_bde64 *)
8294 			((struct lpfc_dmabuf *)iocbq->context3)->virt;
8295 		if (!bpl)
8296 			return IOCB_ERROR;
8297 
8298 		/* Should already be byte swapped. */
8299 		wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
8300 		wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
8301 		/* swap the size field back to the cpu so we
8302 		 * can assign it to the sgl.
8303 		 */
8304 		wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
8305 		xmit_len = wqe->generic.bde.tus.f.bdeSize;
8306 		total_len = 0;
8307 		for (i = 0; i < numBdes; i++) {
8308 			bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
8309 			total_len += bde.tus.f.bdeSize;
8310 		}
8311 	} else
8312 		xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
8313 
8314 	iocbq->iocb.ulpIoTag = iocbq->iotag;
8315 	cmnd = iocbq->iocb.ulpCommand;
8316 
8317 	switch (iocbq->iocb.ulpCommand) {
8318 	case CMD_ELS_REQUEST64_CR:
8319 		if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
8320 			ndlp = iocbq->context_un.ndlp;
8321 		else
8322 			ndlp = (struct lpfc_nodelist *)iocbq->context1;
8323 		if (!iocbq->iocb.ulpLe) {
8324 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8325 				"2007 Only Limited Edition cmd Format"
8326 				" supported 0x%x\n",
8327 				iocbq->iocb.ulpCommand);
8328 			return IOCB_ERROR;
8329 		}
8330 
8331 		wqe->els_req.payload_len = xmit_len;
8332 		/* Els_reguest64 has a TMO */
8333 		bf_set(wqe_tmo, &wqe->els_req.wqe_com,
8334 			iocbq->iocb.ulpTimeout);
8335 		/* Need a VF for word 4 set the vf bit*/
8336 		bf_set(els_req64_vf, &wqe->els_req, 0);
8337 		/* And a VFID for word 12 */
8338 		bf_set(els_req64_vfid, &wqe->els_req, 0);
8339 		ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
8340 		bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8341 		       iocbq->iocb.ulpContext);
8342 		bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
8343 		bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
8344 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
8345 		if (command_type == ELS_COMMAND_FIP)
8346 			els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
8347 					>> LPFC_FIP_ELS_ID_SHIFT);
8348 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
8349 					iocbq->context2)->virt);
8350 		if_type = bf_get(lpfc_sli_intf_if_type,
8351 					&phba->sli4_hba.sli_intf);
8352 		if (if_type == LPFC_SLI_INTF_IF_TYPE_2) {
8353 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
8354 				*pcmd == ELS_CMD_SCR ||
8355 				*pcmd == ELS_CMD_FDISC ||
8356 				*pcmd == ELS_CMD_LOGO ||
8357 				*pcmd == ELS_CMD_PLOGI)) {
8358 				bf_set(els_req64_sp, &wqe->els_req, 1);
8359 				bf_set(els_req64_sid, &wqe->els_req,
8360 					iocbq->vport->fc_myDID);
8361 				if ((*pcmd == ELS_CMD_FLOGI) &&
8362 					!(phba->fc_topology ==
8363 						LPFC_TOPOLOGY_LOOP))
8364 					bf_set(els_req64_sid, &wqe->els_req, 0);
8365 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
8366 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8367 					phba->vpi_ids[iocbq->vport->vpi]);
8368 			} else if (pcmd && iocbq->context1) {
8369 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
8370 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8371 					phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
8372 			}
8373 		}
8374 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
8375 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
8376 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
8377 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
8378 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
8379 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
8380 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
8381 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
8382 		wqe->els_req.max_response_payload_len = total_len - xmit_len;
8383 		break;
8384 	case CMD_XMIT_SEQUENCE64_CX:
8385 		bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
8386 		       iocbq->iocb.un.ulpWord[3]);
8387 		bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
8388 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
8389 		/* The entire sequence is transmitted for this IOCB */
8390 		xmit_len = total_len;
8391 		cmnd = CMD_XMIT_SEQUENCE64_CR;
8392 		if (phba->link_flag & LS_LOOPBACK_MODE)
8393 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
8394 	case CMD_XMIT_SEQUENCE64_CR:
8395 		/* word3 iocb=io_tag32 wqe=reserved */
8396 		wqe->xmit_sequence.rsvd3 = 0;
8397 		/* word4 relative_offset memcpy */
8398 		/* word5 r_ctl/df_ctl memcpy */
8399 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
8400 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
8401 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
8402 		       LPFC_WQE_IOD_WRITE);
8403 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
8404 		       LPFC_WQE_LENLOC_WORD12);
8405 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
8406 		wqe->xmit_sequence.xmit_len = xmit_len;
8407 		command_type = OTHER_COMMAND;
8408 		break;
8409 	case CMD_XMIT_BCAST64_CN:
8410 		/* word3 iocb=iotag32 wqe=seq_payload_len */
8411 		wqe->xmit_bcast64.seq_payload_len = xmit_len;
8412 		/* word4 iocb=rsvd wqe=rsvd */
8413 		/* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
8414 		/* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
8415 		bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
8416 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
8417 		bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
8418 		bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
8419 		bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
8420 		       LPFC_WQE_LENLOC_WORD3);
8421 		bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
8422 		break;
8423 	case CMD_FCP_IWRITE64_CR:
8424 		command_type = FCP_COMMAND_DATA_OUT;
8425 		/* word3 iocb=iotag wqe=payload_offset_len */
8426 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8427 		bf_set(payload_offset_len, &wqe->fcp_iwrite,
8428 		       xmit_len + sizeof(struct fcp_rsp));
8429 		bf_set(cmd_buff_len, &wqe->fcp_iwrite,
8430 		       0);
8431 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
8432 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
8433 		bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
8434 		       iocbq->iocb.ulpFCP2Rcvy);
8435 		bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
8436 		/* Always open the exchange */
8437 		bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
8438 		bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
8439 		       LPFC_WQE_LENLOC_WORD4);
8440 		bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
8441 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
8442 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8443 			bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
8444 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
8445 			if (iocbq->priority) {
8446 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
8447 				       (iocbq->priority << 1));
8448 			} else {
8449 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
8450 				       (phba->cfg_XLanePriority << 1));
8451 			}
8452 		}
8453 		/* Note, word 10 is already initialized to 0 */
8454 
8455 		if (phba->fcp_embed_io) {
8456 			struct lpfc_scsi_buf *lpfc_cmd;
8457 			struct sli4_sge *sgl;
8458 			union lpfc_wqe128 *wqe128;
8459 			struct fcp_cmnd *fcp_cmnd;
8460 			uint32_t *ptr;
8461 
8462 			/* 128 byte wqe support here */
8463 			wqe128 = (union lpfc_wqe128 *)wqe;
8464 
8465 			lpfc_cmd = iocbq->context1;
8466 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
8467 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
8468 
8469 			/* Word 0-2 - FCP_CMND */
8470 			wqe128->generic.bde.tus.f.bdeFlags =
8471 				BUFF_TYPE_BDE_IMMED;
8472 			wqe128->generic.bde.tus.f.bdeSize = sgl->sge_len;
8473 			wqe128->generic.bde.addrHigh = 0;
8474 			wqe128->generic.bde.addrLow =  88;  /* Word 22 */
8475 
8476 			bf_set(wqe_wqes, &wqe128->fcp_iwrite.wqe_com, 1);
8477 
8478 			/* Word 22-29  FCP CMND Payload */
8479 			ptr = &wqe128->words[22];
8480 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
8481 		}
8482 		break;
8483 	case CMD_FCP_IREAD64_CR:
8484 		/* word3 iocb=iotag wqe=payload_offset_len */
8485 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8486 		bf_set(payload_offset_len, &wqe->fcp_iread,
8487 		       xmit_len + sizeof(struct fcp_rsp));
8488 		bf_set(cmd_buff_len, &wqe->fcp_iread,
8489 		       0);
8490 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
8491 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
8492 		bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
8493 		       iocbq->iocb.ulpFCP2Rcvy);
8494 		bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
8495 		/* Always open the exchange */
8496 		bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
8497 		bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
8498 		       LPFC_WQE_LENLOC_WORD4);
8499 		bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
8500 		bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
8501 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8502 			bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
8503 			bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
8504 			if (iocbq->priority) {
8505 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
8506 				       (iocbq->priority << 1));
8507 			} else {
8508 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
8509 				       (phba->cfg_XLanePriority << 1));
8510 			}
8511 		}
8512 		/* Note, word 10 is already initialized to 0 */
8513 
8514 		if (phba->fcp_embed_io) {
8515 			struct lpfc_scsi_buf *lpfc_cmd;
8516 			struct sli4_sge *sgl;
8517 			union lpfc_wqe128 *wqe128;
8518 			struct fcp_cmnd *fcp_cmnd;
8519 			uint32_t *ptr;
8520 
8521 			/* 128 byte wqe support here */
8522 			wqe128 = (union lpfc_wqe128 *)wqe;
8523 
8524 			lpfc_cmd = iocbq->context1;
8525 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
8526 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
8527 
8528 			/* Word 0-2 - FCP_CMND */
8529 			wqe128->generic.bde.tus.f.bdeFlags =
8530 				BUFF_TYPE_BDE_IMMED;
8531 			wqe128->generic.bde.tus.f.bdeSize = sgl->sge_len;
8532 			wqe128->generic.bde.addrHigh = 0;
8533 			wqe128->generic.bde.addrLow =  88;  /* Word 22 */
8534 
8535 			bf_set(wqe_wqes, &wqe128->fcp_iread.wqe_com, 1);
8536 
8537 			/* Word 22-29  FCP CMND Payload */
8538 			ptr = &wqe128->words[22];
8539 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
8540 		}
8541 		break;
8542 	case CMD_FCP_ICMND64_CR:
8543 		/* word3 iocb=iotag wqe=payload_offset_len */
8544 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8545 		bf_set(payload_offset_len, &wqe->fcp_icmd,
8546 		       xmit_len + sizeof(struct fcp_rsp));
8547 		bf_set(cmd_buff_len, &wqe->fcp_icmd,
8548 		       0);
8549 		/* word3 iocb=IO_TAG wqe=reserved */
8550 		bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
8551 		/* Always open the exchange */
8552 		bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
8553 		bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
8554 		bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
8555 		bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
8556 		       LPFC_WQE_LENLOC_NONE);
8557 		bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
8558 		       iocbq->iocb.ulpFCP2Rcvy);
8559 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8560 			bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
8561 			bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
8562 			if (iocbq->priority) {
8563 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
8564 				       (iocbq->priority << 1));
8565 			} else {
8566 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
8567 				       (phba->cfg_XLanePriority << 1));
8568 			}
8569 		}
8570 		/* Note, word 10 is already initialized to 0 */
8571 
8572 		if (phba->fcp_embed_io) {
8573 			struct lpfc_scsi_buf *lpfc_cmd;
8574 			struct sli4_sge *sgl;
8575 			union lpfc_wqe128 *wqe128;
8576 			struct fcp_cmnd *fcp_cmnd;
8577 			uint32_t *ptr;
8578 
8579 			/* 128 byte wqe support here */
8580 			wqe128 = (union lpfc_wqe128 *)wqe;
8581 
8582 			lpfc_cmd = iocbq->context1;
8583 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
8584 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
8585 
8586 			/* Word 0-2 - FCP_CMND */
8587 			wqe128->generic.bde.tus.f.bdeFlags =
8588 				BUFF_TYPE_BDE_IMMED;
8589 			wqe128->generic.bde.tus.f.bdeSize = sgl->sge_len;
8590 			wqe128->generic.bde.addrHigh = 0;
8591 			wqe128->generic.bde.addrLow =  88;  /* Word 22 */
8592 
8593 			bf_set(wqe_wqes, &wqe128->fcp_icmd.wqe_com, 1);
8594 
8595 			/* Word 22-29  FCP CMND Payload */
8596 			ptr = &wqe128->words[22];
8597 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
8598 		}
8599 		break;
8600 	case CMD_GEN_REQUEST64_CR:
8601 		/* For this command calculate the xmit length of the
8602 		 * request bde.
8603 		 */
8604 		xmit_len = 0;
8605 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
8606 			sizeof(struct ulp_bde64);
8607 		for (i = 0; i < numBdes; i++) {
8608 			bde.tus.w = le32_to_cpu(bpl[i].tus.w);
8609 			if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
8610 				break;
8611 			xmit_len += bde.tus.f.bdeSize;
8612 		}
8613 		/* word3 iocb=IO_TAG wqe=request_payload_len */
8614 		wqe->gen_req.request_payload_len = xmit_len;
8615 		/* word4 iocb=parameter wqe=relative_offset memcpy */
8616 		/* word5 [rctl, type, df_ctl, la] copied in memcpy */
8617 		/* word6 context tag copied in memcpy */
8618 		if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
8619 			ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
8620 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8621 				"2015 Invalid CT %x command 0x%x\n",
8622 				ct, iocbq->iocb.ulpCommand);
8623 			return IOCB_ERROR;
8624 		}
8625 		bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
8626 		bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
8627 		bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
8628 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
8629 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
8630 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
8631 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
8632 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
8633 		wqe->gen_req.max_response_payload_len = total_len - xmit_len;
8634 		command_type = OTHER_COMMAND;
8635 		break;
8636 	case CMD_XMIT_ELS_RSP64_CX:
8637 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
8638 		/* words0-2 BDE memcpy */
8639 		/* word3 iocb=iotag32 wqe=response_payload_len */
8640 		wqe->xmit_els_rsp.response_payload_len = xmit_len;
8641 		/* word4 */
8642 		wqe->xmit_els_rsp.word4 = 0;
8643 		/* word5 iocb=rsvd wge=did */
8644 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
8645 			 iocbq->iocb.un.xseq64.xmit_els_remoteID);
8646 
8647 		if_type = bf_get(lpfc_sli_intf_if_type,
8648 					&phba->sli4_hba.sli_intf);
8649 		if (if_type == LPFC_SLI_INTF_IF_TYPE_2) {
8650 			if (iocbq->vport->fc_flag & FC_PT2PT) {
8651 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
8652 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
8653 					iocbq->vport->fc_myDID);
8654 				if (iocbq->vport->fc_myDID == Fabric_DID) {
8655 					bf_set(wqe_els_did,
8656 						&wqe->xmit_els_rsp.wqe_dest, 0);
8657 				}
8658 			}
8659 		}
8660 		bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
8661 		       ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
8662 		bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
8663 		bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
8664 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
8665 		if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
8666 			bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
8667 			       phba->vpi_ids[iocbq->vport->vpi]);
8668 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
8669 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
8670 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
8671 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
8672 		       LPFC_WQE_LENLOC_WORD3);
8673 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
8674 		bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
8675 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
8676 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
8677 					iocbq->context2)->virt);
8678 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
8679 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
8680 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
8681 					iocbq->vport->fc_myDID);
8682 				bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
8683 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
8684 					phba->vpi_ids[phba->pport->vpi]);
8685 		}
8686 		command_type = OTHER_COMMAND;
8687 		break;
8688 	case CMD_CLOSE_XRI_CN:
8689 	case CMD_ABORT_XRI_CN:
8690 	case CMD_ABORT_XRI_CX:
8691 		/* words 0-2 memcpy should be 0 rserved */
8692 		/* port will send abts */
8693 		abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
8694 		if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
8695 			abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
8696 			fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
8697 		} else
8698 			fip = 0;
8699 
8700 		if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
8701 			/*
8702 			 * The link is down, or the command was ELS_FIP
8703 			 * so the fw does not need to send abts
8704 			 * on the wire.
8705 			 */
8706 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
8707 		else
8708 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
8709 		bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
8710 		/* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
8711 		wqe->abort_cmd.rsrvd5 = 0;
8712 		bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
8713 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
8714 		abort_tag = iocbq->iocb.un.acxri.abortIoTag;
8715 		/*
8716 		 * The abort handler will send us CMD_ABORT_XRI_CN or
8717 		 * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
8718 		 */
8719 		bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
8720 		bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
8721 		bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
8722 		       LPFC_WQE_LENLOC_NONE);
8723 		cmnd = CMD_ABORT_XRI_CX;
8724 		command_type = OTHER_COMMAND;
8725 		xritag = 0;
8726 		break;
8727 	case CMD_XMIT_BLS_RSP64_CX:
8728 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
8729 		/* As BLS ABTS RSP WQE is very different from other WQEs,
8730 		 * we re-construct this WQE here based on information in
8731 		 * iocbq from scratch.
8732 		 */
8733 		memset(wqe, 0, sizeof(union lpfc_wqe));
8734 		/* OX_ID is invariable to who sent ABTS to CT exchange */
8735 		bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
8736 		       bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
8737 		if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
8738 		    LPFC_ABTS_UNSOL_INT) {
8739 			/* ABTS sent by initiator to CT exchange, the
8740 			 * RX_ID field will be filled with the newly
8741 			 * allocated responder XRI.
8742 			 */
8743 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
8744 			       iocbq->sli4_xritag);
8745 		} else {
8746 			/* ABTS sent by responder to CT exchange, the
8747 			 * RX_ID field will be filled with the responder
8748 			 * RX_ID from ABTS.
8749 			 */
8750 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
8751 			       bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
8752 		}
8753 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
8754 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
8755 
8756 		/* Use CT=VPI */
8757 		bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
8758 			ndlp->nlp_DID);
8759 		bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
8760 			iocbq->iocb.ulpContext);
8761 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
8762 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
8763 			phba->vpi_ids[phba->pport->vpi]);
8764 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
8765 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
8766 		       LPFC_WQE_LENLOC_NONE);
8767 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
8768 		command_type = OTHER_COMMAND;
8769 		if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
8770 			bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
8771 			       bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
8772 			bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
8773 			       bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
8774 			bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
8775 			       bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
8776 		}
8777 
8778 		break;
8779 	case CMD_XRI_ABORTED_CX:
8780 	case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
8781 	case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
8782 	case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
8783 	case CMD_FCP_TRSP64_CX: /* Target mode rcv */
8784 	case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
8785 	default:
8786 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8787 				"2014 Invalid command 0x%x\n",
8788 				iocbq->iocb.ulpCommand);
8789 		return IOCB_ERROR;
8790 		break;
8791 	}
8792 
8793 	if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
8794 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
8795 	else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
8796 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
8797 	else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
8798 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
8799 	iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
8800 			      LPFC_IO_DIF_INSERT);
8801 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
8802 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
8803 	wqe->generic.wqe_com.abort_tag = abort_tag;
8804 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
8805 	bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
8806 	bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
8807 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
8808 	return 0;
8809 }
8810 
8811 /**
8812  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
8813  * @phba: Pointer to HBA context object.
8814  * @ring_number: SLI ring number to issue iocb on.
8815  * @piocb: Pointer to command iocb.
8816  * @flag: Flag indicating if this command can be put into txq.
8817  *
8818  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
8819  * an iocb command to an HBA with SLI-4 interface spec.
8820  *
8821  * This function is called with hbalock held. The function will return success
8822  * after it successfully submit the iocb to firmware or after adding to the
8823  * txq.
8824  **/
8825 static int
8826 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
8827 			 struct lpfc_iocbq *piocb, uint32_t flag)
8828 {
8829 	struct lpfc_sglq *sglq;
8830 	union lpfc_wqe *wqe;
8831 	union lpfc_wqe128 wqe128;
8832 	struct lpfc_queue *wq;
8833 	struct lpfc_sli_ring *pring = &phba->sli.ring[ring_number];
8834 
8835 	lockdep_assert_held(&phba->hbalock);
8836 
8837 	/*
8838 	 * The WQE can be either 64 or 128 bytes,
8839 	 * so allocate space on the stack assuming the largest.
8840 	 */
8841 	wqe = (union lpfc_wqe *)&wqe128;
8842 
8843 	if (piocb->sli4_xritag == NO_XRI) {
8844 		if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
8845 		    piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
8846 			sglq = NULL;
8847 		else {
8848 			if (!list_empty(&pring->txq)) {
8849 				if (!(flag & SLI_IOCB_RET_IOCB)) {
8850 					__lpfc_sli_ringtx_put(phba,
8851 						pring, piocb);
8852 					return IOCB_SUCCESS;
8853 				} else {
8854 					return IOCB_BUSY;
8855 				}
8856 			} else {
8857 				sglq = __lpfc_sli_get_sglq(phba, piocb);
8858 				if (!sglq) {
8859 					if (!(flag & SLI_IOCB_RET_IOCB)) {
8860 						__lpfc_sli_ringtx_put(phba,
8861 								pring,
8862 								piocb);
8863 						return IOCB_SUCCESS;
8864 					} else
8865 						return IOCB_BUSY;
8866 				}
8867 			}
8868 		}
8869 	} else if (piocb->iocb_flag &  LPFC_IO_FCP) {
8870 		/* These IO's already have an XRI and a mapped sgl. */
8871 		sglq = NULL;
8872 	} else {
8873 		/*
8874 		 * This is a continuation of a commandi,(CX) so this
8875 		 * sglq is on the active list
8876 		 */
8877 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
8878 		if (!sglq)
8879 			return IOCB_ERROR;
8880 	}
8881 
8882 	if (sglq) {
8883 		piocb->sli4_lxritag = sglq->sli4_lxritag;
8884 		piocb->sli4_xritag = sglq->sli4_xritag;
8885 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
8886 			return IOCB_ERROR;
8887 	}
8888 
8889 	if (lpfc_sli4_iocb2wqe(phba, piocb, wqe))
8890 		return IOCB_ERROR;
8891 
8892 	if ((piocb->iocb_flag & LPFC_IO_FCP) ||
8893 	    (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
8894 		if (!phba->cfg_fof || (!(piocb->iocb_flag & LPFC_IO_OAS))) {
8895 			wq = phba->sli4_hba.fcp_wq[piocb->fcp_wqidx];
8896 		} else {
8897 			wq = phba->sli4_hba.oas_wq;
8898 		}
8899 		if (lpfc_sli4_wq_put(wq, wqe))
8900 			return IOCB_ERROR;
8901 	} else {
8902 		if (unlikely(!phba->sli4_hba.els_wq))
8903 			return IOCB_ERROR;
8904 		if (lpfc_sli4_wq_put(phba->sli4_hba.els_wq, wqe))
8905 			return IOCB_ERROR;
8906 	}
8907 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
8908 
8909 	return 0;
8910 }
8911 
8912 /**
8913  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
8914  *
8915  * This routine wraps the actual lockless version for issusing IOCB function
8916  * pointer from the lpfc_hba struct.
8917  *
8918  * Return codes:
8919  * IOCB_ERROR - Error
8920  * IOCB_SUCCESS - Success
8921  * IOCB_BUSY - Busy
8922  **/
8923 int
8924 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
8925 		struct lpfc_iocbq *piocb, uint32_t flag)
8926 {
8927 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
8928 }
8929 
8930 /**
8931  * lpfc_sli_api_table_setup - Set up sli api function jump table
8932  * @phba: The hba struct for which this call is being executed.
8933  * @dev_grp: The HBA PCI-Device group number.
8934  *
8935  * This routine sets up the SLI interface API function jump table in @phba
8936  * struct.
8937  * Returns: 0 - success, -ENODEV - failure.
8938  **/
8939 int
8940 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8941 {
8942 
8943 	switch (dev_grp) {
8944 	case LPFC_PCI_DEV_LP:
8945 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
8946 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
8947 		break;
8948 	case LPFC_PCI_DEV_OC:
8949 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
8950 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
8951 		break;
8952 	default:
8953 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8954 				"1419 Invalid HBA PCI-device group: 0x%x\n",
8955 				dev_grp);
8956 		return -ENODEV;
8957 		break;
8958 	}
8959 	phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
8960 	return 0;
8961 }
8962 
8963 /**
8964  * lpfc_sli_calc_ring - Calculates which ring to use
8965  * @phba: Pointer to HBA context object.
8966  * @ring_number: Initial ring
8967  * @piocb: Pointer to command iocb.
8968  *
8969  * For SLI4, FCP IO can deferred to one fo many WQs, based on
8970  * fcp_wqidx, thus we need to calculate the corresponding ring.
8971  * Since ABORTS must go on the same WQ of the command they are
8972  * aborting, we use command's fcp_wqidx.
8973  */
8974 int
8975 lpfc_sli_calc_ring(struct lpfc_hba *phba, uint32_t ring_number,
8976 		    struct lpfc_iocbq *piocb)
8977 {
8978 	if (phba->sli_rev < LPFC_SLI_REV4)
8979 		return ring_number;
8980 
8981 	if (piocb->iocb_flag &  (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
8982 		if (!(phba->cfg_fof) ||
8983 				(!(piocb->iocb_flag & LPFC_IO_FOF))) {
8984 			if (unlikely(!phba->sli4_hba.fcp_wq))
8985 				return LPFC_HBA_ERROR;
8986 			/*
8987 			 * for abort iocb fcp_wqidx should already
8988 			 * be setup based on what work queue we used.
8989 			 */
8990 			if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX))
8991 				piocb->fcp_wqidx =
8992 					lpfc_sli4_scmd_to_wqidx_distr(phba,
8993 							      piocb->context1);
8994 			ring_number = MAX_SLI3_CONFIGURED_RINGS +
8995 				piocb->fcp_wqidx;
8996 		} else {
8997 			if (unlikely(!phba->sli4_hba.oas_wq))
8998 				return LPFC_HBA_ERROR;
8999 			piocb->fcp_wqidx = 0;
9000 			ring_number =  LPFC_FCP_OAS_RING;
9001 		}
9002 	}
9003 	return ring_number;
9004 }
9005 
9006 /**
9007  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
9008  * @phba: Pointer to HBA context object.
9009  * @pring: Pointer to driver SLI ring object.
9010  * @piocb: Pointer to command iocb.
9011  * @flag: Flag indicating if this command can be put into txq.
9012  *
9013  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
9014  * function. This function gets the hbalock and calls
9015  * __lpfc_sli_issue_iocb function and will return the error returned
9016  * by __lpfc_sli_issue_iocb function. This wrapper is used by
9017  * functions which do not hold hbalock.
9018  **/
9019 int
9020 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
9021 		    struct lpfc_iocbq *piocb, uint32_t flag)
9022 {
9023 	struct lpfc_fcp_eq_hdl *fcp_eq_hdl;
9024 	struct lpfc_sli_ring *pring;
9025 	struct lpfc_queue *fpeq;
9026 	struct lpfc_eqe *eqe;
9027 	unsigned long iflags;
9028 	int rc, idx;
9029 
9030 	if (phba->sli_rev == LPFC_SLI_REV4) {
9031 		ring_number = lpfc_sli_calc_ring(phba, ring_number, piocb);
9032 		if (unlikely(ring_number == LPFC_HBA_ERROR))
9033 			return IOCB_ERROR;
9034 		idx = piocb->fcp_wqidx;
9035 
9036 		pring = &phba->sli.ring[ring_number];
9037 		spin_lock_irqsave(&pring->ring_lock, iflags);
9038 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
9039 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
9040 
9041 		if (lpfc_fcp_look_ahead && (piocb->iocb_flag &  LPFC_IO_FCP)) {
9042 			fcp_eq_hdl = &phba->sli4_hba.fcp_eq_hdl[idx];
9043 
9044 			if (atomic_dec_and_test(&fcp_eq_hdl->
9045 				fcp_eq_in_use)) {
9046 
9047 				/* Get associated EQ with this index */
9048 				fpeq = phba->sli4_hba.hba_eq[idx];
9049 
9050 				/* Turn off interrupts from this EQ */
9051 				lpfc_sli4_eq_clr_intr(fpeq);
9052 
9053 				/*
9054 				 * Process all the events on FCP EQ
9055 				 */
9056 				while ((eqe = lpfc_sli4_eq_get(fpeq))) {
9057 					lpfc_sli4_hba_handle_eqe(phba,
9058 						eqe, idx);
9059 					fpeq->EQ_processed++;
9060 				}
9061 
9062 				/* Always clear and re-arm the EQ */
9063 				lpfc_sli4_eq_release(fpeq,
9064 					LPFC_QUEUE_REARM);
9065 			}
9066 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
9067 		}
9068 	} else {
9069 		/* For now, SLI2/3 will still use hbalock */
9070 		spin_lock_irqsave(&phba->hbalock, iflags);
9071 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
9072 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9073 	}
9074 	return rc;
9075 }
9076 
9077 /**
9078  * lpfc_extra_ring_setup - Extra ring setup function
9079  * @phba: Pointer to HBA context object.
9080  *
9081  * This function is called while driver attaches with the
9082  * HBA to setup the extra ring. The extra ring is used
9083  * only when driver needs to support target mode functionality
9084  * or IP over FC functionalities.
9085  *
9086  * This function is called with no lock held.
9087  **/
9088 static int
9089 lpfc_extra_ring_setup( struct lpfc_hba *phba)
9090 {
9091 	struct lpfc_sli *psli;
9092 	struct lpfc_sli_ring *pring;
9093 
9094 	psli = &phba->sli;
9095 
9096 	/* Adjust cmd/rsp ring iocb entries more evenly */
9097 
9098 	/* Take some away from the FCP ring */
9099 	pring = &psli->ring[psli->fcp_ring];
9100 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
9101 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
9102 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
9103 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
9104 
9105 	/* and give them to the extra ring */
9106 	pring = &psli->ring[psli->extra_ring];
9107 
9108 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
9109 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
9110 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
9111 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
9112 
9113 	/* Setup default profile for this ring */
9114 	pring->iotag_max = 4096;
9115 	pring->num_mask = 1;
9116 	pring->prt[0].profile = 0;      /* Mask 0 */
9117 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
9118 	pring->prt[0].type = phba->cfg_multi_ring_type;
9119 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
9120 	return 0;
9121 }
9122 
9123 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
9124  * @phba: Pointer to HBA context object.
9125  * @iocbq: Pointer to iocb object.
9126  *
9127  * The async_event handler calls this routine when it receives
9128  * an ASYNC_STATUS_CN event from the port.  The port generates
9129  * this event when an Abort Sequence request to an rport fails
9130  * twice in succession.  The abort could be originated by the
9131  * driver or by the port.  The ABTS could have been for an ELS
9132  * or FCP IO.  The port only generates this event when an ABTS
9133  * fails to complete after one retry.
9134  */
9135 static void
9136 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
9137 			  struct lpfc_iocbq *iocbq)
9138 {
9139 	struct lpfc_nodelist *ndlp = NULL;
9140 	uint16_t rpi = 0, vpi = 0;
9141 	struct lpfc_vport *vport = NULL;
9142 
9143 	/* The rpi in the ulpContext is vport-sensitive. */
9144 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
9145 	rpi = iocbq->iocb.ulpContext;
9146 
9147 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9148 			"3092 Port generated ABTS async event "
9149 			"on vpi %d rpi %d status 0x%x\n",
9150 			vpi, rpi, iocbq->iocb.ulpStatus);
9151 
9152 	vport = lpfc_find_vport_by_vpid(phba, vpi);
9153 	if (!vport)
9154 		goto err_exit;
9155 	ndlp = lpfc_findnode_rpi(vport, rpi);
9156 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp))
9157 		goto err_exit;
9158 
9159 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
9160 		lpfc_sli_abts_recover_port(vport, ndlp);
9161 	return;
9162 
9163  err_exit:
9164 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9165 			"3095 Event Context not found, no "
9166 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
9167 			iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
9168 			vpi, rpi);
9169 }
9170 
9171 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
9172  * @phba: pointer to HBA context object.
9173  * @ndlp: nodelist pointer for the impacted rport.
9174  * @axri: pointer to the wcqe containing the failed exchange.
9175  *
9176  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
9177  * port.  The port generates this event when an abort exchange request to an
9178  * rport fails twice in succession with no reply.  The abort could be originated
9179  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
9180  */
9181 void
9182 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
9183 			   struct lpfc_nodelist *ndlp,
9184 			   struct sli4_wcqe_xri_aborted *axri)
9185 {
9186 	struct lpfc_vport *vport;
9187 	uint32_t ext_status = 0;
9188 
9189 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)) {
9190 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9191 				"3115 Node Context not found, driver "
9192 				"ignoring abts err event\n");
9193 		return;
9194 	}
9195 
9196 	vport = ndlp->vport;
9197 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9198 			"3116 Port generated FCP XRI ABORT event on "
9199 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
9200 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
9201 			bf_get(lpfc_wcqe_xa_xri, axri),
9202 			bf_get(lpfc_wcqe_xa_status, axri),
9203 			axri->parameter);
9204 
9205 	/*
9206 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
9207 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
9208 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
9209 	 */
9210 	ext_status = axri->parameter & IOERR_PARAM_MASK;
9211 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
9212 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
9213 		lpfc_sli_abts_recover_port(vport, ndlp);
9214 }
9215 
9216 /**
9217  * lpfc_sli_async_event_handler - ASYNC iocb handler function
9218  * @phba: Pointer to HBA context object.
9219  * @pring: Pointer to driver SLI ring object.
9220  * @iocbq: Pointer to iocb object.
9221  *
9222  * This function is called by the slow ring event handler
9223  * function when there is an ASYNC event iocb in the ring.
9224  * This function is called with no lock held.
9225  * Currently this function handles only temperature related
9226  * ASYNC events. The function decodes the temperature sensor
9227  * event message and posts events for the management applications.
9228  **/
9229 static void
9230 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
9231 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
9232 {
9233 	IOCB_t *icmd;
9234 	uint16_t evt_code;
9235 	struct temp_event temp_event_data;
9236 	struct Scsi_Host *shost;
9237 	uint32_t *iocb_w;
9238 
9239 	icmd = &iocbq->iocb;
9240 	evt_code = icmd->un.asyncstat.evt_code;
9241 
9242 	switch (evt_code) {
9243 	case ASYNC_TEMP_WARN:
9244 	case ASYNC_TEMP_SAFE:
9245 		temp_event_data.data = (uint32_t) icmd->ulpContext;
9246 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
9247 		if (evt_code == ASYNC_TEMP_WARN) {
9248 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
9249 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
9250 				"0347 Adapter is very hot, please take "
9251 				"corrective action. temperature : %d Celsius\n",
9252 				(uint32_t) icmd->ulpContext);
9253 		} else {
9254 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
9255 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
9256 				"0340 Adapter temperature is OK now. "
9257 				"temperature : %d Celsius\n",
9258 				(uint32_t) icmd->ulpContext);
9259 		}
9260 
9261 		/* Send temperature change event to applications */
9262 		shost = lpfc_shost_from_vport(phba->pport);
9263 		fc_host_post_vendor_event(shost, fc_get_event_number(),
9264 			sizeof(temp_event_data), (char *) &temp_event_data,
9265 			LPFC_NL_VENDOR_ID);
9266 		break;
9267 	case ASYNC_STATUS_CN:
9268 		lpfc_sli_abts_err_handler(phba, iocbq);
9269 		break;
9270 	default:
9271 		iocb_w = (uint32_t *) icmd;
9272 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9273 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
9274 			" evt_code 0x%x\n"
9275 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
9276 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
9277 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
9278 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
9279 			pring->ringno, icmd->un.asyncstat.evt_code,
9280 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
9281 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
9282 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
9283 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
9284 
9285 		break;
9286 	}
9287 }
9288 
9289 
9290 /**
9291  * lpfc_sli_setup - SLI ring setup function
9292  * @phba: Pointer to HBA context object.
9293  *
9294  * lpfc_sli_setup sets up rings of the SLI interface with
9295  * number of iocbs per ring and iotags. This function is
9296  * called while driver attach to the HBA and before the
9297  * interrupts are enabled. So there is no need for locking.
9298  *
9299  * This function always returns 0.
9300  **/
9301 int
9302 lpfc_sli_setup(struct lpfc_hba *phba)
9303 {
9304 	int i, totiocbsize = 0;
9305 	struct lpfc_sli *psli = &phba->sli;
9306 	struct lpfc_sli_ring *pring;
9307 
9308 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
9309 	if (phba->sli_rev == LPFC_SLI_REV4)
9310 		psli->num_rings += phba->cfg_fcp_io_channel;
9311 	psli->sli_flag = 0;
9312 	psli->fcp_ring = LPFC_FCP_RING;
9313 	psli->next_ring = LPFC_FCP_NEXT_RING;
9314 	psli->extra_ring = LPFC_EXTRA_RING;
9315 
9316 	psli->iocbq_lookup = NULL;
9317 	psli->iocbq_lookup_len = 0;
9318 	psli->last_iotag = 0;
9319 
9320 	for (i = 0; i < psli->num_rings; i++) {
9321 		pring = &psli->ring[i];
9322 		switch (i) {
9323 		case LPFC_FCP_RING:	/* ring 0 - FCP */
9324 			/* numCiocb and numRiocb are used in config_port */
9325 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
9326 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
9327 			pring->sli.sli3.numCiocb +=
9328 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
9329 			pring->sli.sli3.numRiocb +=
9330 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
9331 			pring->sli.sli3.numCiocb +=
9332 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
9333 			pring->sli.sli3.numRiocb +=
9334 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
9335 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9336 							SLI3_IOCB_CMD_SIZE :
9337 							SLI2_IOCB_CMD_SIZE;
9338 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9339 							SLI3_IOCB_RSP_SIZE :
9340 							SLI2_IOCB_RSP_SIZE;
9341 			pring->iotag_ctr = 0;
9342 			pring->iotag_max =
9343 			    (phba->cfg_hba_queue_depth * 2);
9344 			pring->fast_iotag = pring->iotag_max;
9345 			pring->num_mask = 0;
9346 			break;
9347 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
9348 			/* numCiocb and numRiocb are used in config_port */
9349 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
9350 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
9351 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9352 							SLI3_IOCB_CMD_SIZE :
9353 							SLI2_IOCB_CMD_SIZE;
9354 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9355 							SLI3_IOCB_RSP_SIZE :
9356 							SLI2_IOCB_RSP_SIZE;
9357 			pring->iotag_max = phba->cfg_hba_queue_depth;
9358 			pring->num_mask = 0;
9359 			break;
9360 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
9361 			/* numCiocb and numRiocb are used in config_port */
9362 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
9363 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
9364 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9365 							SLI3_IOCB_CMD_SIZE :
9366 							SLI2_IOCB_CMD_SIZE;
9367 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9368 							SLI3_IOCB_RSP_SIZE :
9369 							SLI2_IOCB_RSP_SIZE;
9370 			pring->fast_iotag = 0;
9371 			pring->iotag_ctr = 0;
9372 			pring->iotag_max = 4096;
9373 			pring->lpfc_sli_rcv_async_status =
9374 				lpfc_sli_async_event_handler;
9375 			pring->num_mask = LPFC_MAX_RING_MASK;
9376 			pring->prt[0].profile = 0;	/* Mask 0 */
9377 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
9378 			pring->prt[0].type = FC_TYPE_ELS;
9379 			pring->prt[0].lpfc_sli_rcv_unsol_event =
9380 			    lpfc_els_unsol_event;
9381 			pring->prt[1].profile = 0;	/* Mask 1 */
9382 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
9383 			pring->prt[1].type = FC_TYPE_ELS;
9384 			pring->prt[1].lpfc_sli_rcv_unsol_event =
9385 			    lpfc_els_unsol_event;
9386 			pring->prt[2].profile = 0;	/* Mask 2 */
9387 			/* NameServer Inquiry */
9388 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
9389 			/* NameServer */
9390 			pring->prt[2].type = FC_TYPE_CT;
9391 			pring->prt[2].lpfc_sli_rcv_unsol_event =
9392 			    lpfc_ct_unsol_event;
9393 			pring->prt[3].profile = 0;	/* Mask 3 */
9394 			/* NameServer response */
9395 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
9396 			/* NameServer */
9397 			pring->prt[3].type = FC_TYPE_CT;
9398 			pring->prt[3].lpfc_sli_rcv_unsol_event =
9399 			    lpfc_ct_unsol_event;
9400 			break;
9401 		}
9402 		totiocbsize += (pring->sli.sli3.numCiocb *
9403 			pring->sli.sli3.sizeCiocb) +
9404 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
9405 	}
9406 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
9407 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
9408 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
9409 		       "SLI2 SLIM Data: x%x x%lx\n",
9410 		       phba->brd_no, totiocbsize,
9411 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
9412 	}
9413 	if (phba->cfg_multi_ring_support == 2)
9414 		lpfc_extra_ring_setup(phba);
9415 
9416 	return 0;
9417 }
9418 
9419 /**
9420  * lpfc_sli_queue_setup - Queue initialization function
9421  * @phba: Pointer to HBA context object.
9422  *
9423  * lpfc_sli_queue_setup sets up mailbox queues and iocb queues for each
9424  * ring. This function also initializes ring indices of each ring.
9425  * This function is called during the initialization of the SLI
9426  * interface of an HBA.
9427  * This function is called with no lock held and always returns
9428  * 1.
9429  **/
9430 int
9431 lpfc_sli_queue_setup(struct lpfc_hba *phba)
9432 {
9433 	struct lpfc_sli *psli;
9434 	struct lpfc_sli_ring *pring;
9435 	int i;
9436 
9437 	psli = &phba->sli;
9438 	spin_lock_irq(&phba->hbalock);
9439 	INIT_LIST_HEAD(&psli->mboxq);
9440 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
9441 	/* Initialize list headers for txq and txcmplq as double linked lists */
9442 	for (i = 0; i < psli->num_rings; i++) {
9443 		pring = &psli->ring[i];
9444 		pring->ringno = i;
9445 		pring->sli.sli3.next_cmdidx  = 0;
9446 		pring->sli.sli3.local_getidx = 0;
9447 		pring->sli.sli3.cmdidx = 0;
9448 		pring->flag = 0;
9449 		INIT_LIST_HEAD(&pring->txq);
9450 		INIT_LIST_HEAD(&pring->txcmplq);
9451 		INIT_LIST_HEAD(&pring->iocb_continueq);
9452 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
9453 		INIT_LIST_HEAD(&pring->postbufq);
9454 		spin_lock_init(&pring->ring_lock);
9455 	}
9456 	spin_unlock_irq(&phba->hbalock);
9457 	return 1;
9458 }
9459 
9460 /**
9461  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
9462  * @phba: Pointer to HBA context object.
9463  *
9464  * This routine flushes the mailbox command subsystem. It will unconditionally
9465  * flush all the mailbox commands in the three possible stages in the mailbox
9466  * command sub-system: pending mailbox command queue; the outstanding mailbox
9467  * command; and completed mailbox command queue. It is caller's responsibility
9468  * to make sure that the driver is in the proper state to flush the mailbox
9469  * command sub-system. Namely, the posting of mailbox commands into the
9470  * pending mailbox command queue from the various clients must be stopped;
9471  * either the HBA is in a state that it will never works on the outstanding
9472  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
9473  * mailbox command has been completed.
9474  **/
9475 static void
9476 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
9477 {
9478 	LIST_HEAD(completions);
9479 	struct lpfc_sli *psli = &phba->sli;
9480 	LPFC_MBOXQ_t *pmb;
9481 	unsigned long iflag;
9482 
9483 	/* Flush all the mailbox commands in the mbox system */
9484 	spin_lock_irqsave(&phba->hbalock, iflag);
9485 	/* The pending mailbox command queue */
9486 	list_splice_init(&phba->sli.mboxq, &completions);
9487 	/* The outstanding active mailbox command */
9488 	if (psli->mbox_active) {
9489 		list_add_tail(&psli->mbox_active->list, &completions);
9490 		psli->mbox_active = NULL;
9491 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9492 	}
9493 	/* The completed mailbox command queue */
9494 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
9495 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9496 
9497 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
9498 	while (!list_empty(&completions)) {
9499 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
9500 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
9501 		if (pmb->mbox_cmpl)
9502 			pmb->mbox_cmpl(phba, pmb);
9503 	}
9504 }
9505 
9506 /**
9507  * lpfc_sli_host_down - Vport cleanup function
9508  * @vport: Pointer to virtual port object.
9509  *
9510  * lpfc_sli_host_down is called to clean up the resources
9511  * associated with a vport before destroying virtual
9512  * port data structures.
9513  * This function does following operations:
9514  * - Free discovery resources associated with this virtual
9515  *   port.
9516  * - Free iocbs associated with this virtual port in
9517  *   the txq.
9518  * - Send abort for all iocb commands associated with this
9519  *   vport in txcmplq.
9520  *
9521  * This function is called with no lock held and always returns 1.
9522  **/
9523 int
9524 lpfc_sli_host_down(struct lpfc_vport *vport)
9525 {
9526 	LIST_HEAD(completions);
9527 	struct lpfc_hba *phba = vport->phba;
9528 	struct lpfc_sli *psli = &phba->sli;
9529 	struct lpfc_sli_ring *pring;
9530 	struct lpfc_iocbq *iocb, *next_iocb;
9531 	int i;
9532 	unsigned long flags = 0;
9533 	uint16_t prev_pring_flag;
9534 
9535 	lpfc_cleanup_discovery_resources(vport);
9536 
9537 	spin_lock_irqsave(&phba->hbalock, flags);
9538 	for (i = 0; i < psli->num_rings; i++) {
9539 		pring = &psli->ring[i];
9540 		prev_pring_flag = pring->flag;
9541 		/* Only slow rings */
9542 		if (pring->ringno == LPFC_ELS_RING) {
9543 			pring->flag |= LPFC_DEFERRED_RING_EVENT;
9544 			/* Set the lpfc data pending flag */
9545 			set_bit(LPFC_DATA_READY, &phba->data_flags);
9546 		}
9547 		/*
9548 		 * Error everything on the txq since these iocbs have not been
9549 		 * given to the FW yet.
9550 		 */
9551 		list_for_each_entry_safe(iocb, next_iocb, &pring->txq, list) {
9552 			if (iocb->vport != vport)
9553 				continue;
9554 			list_move_tail(&iocb->list, &completions);
9555 		}
9556 
9557 		/* Next issue ABTS for everything on the txcmplq */
9558 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq,
9559 									list) {
9560 			if (iocb->vport != vport)
9561 				continue;
9562 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
9563 		}
9564 
9565 		pring->flag = prev_pring_flag;
9566 	}
9567 
9568 	spin_unlock_irqrestore(&phba->hbalock, flags);
9569 
9570 	/* Cancel all the IOCBs from the completions list */
9571 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
9572 			      IOERR_SLI_DOWN);
9573 	return 1;
9574 }
9575 
9576 /**
9577  * lpfc_sli_hba_down - Resource cleanup function for the HBA
9578  * @phba: Pointer to HBA context object.
9579  *
9580  * This function cleans up all iocb, buffers, mailbox commands
9581  * while shutting down the HBA. This function is called with no
9582  * lock held and always returns 1.
9583  * This function does the following to cleanup driver resources:
9584  * - Free discovery resources for each virtual port
9585  * - Cleanup any pending fabric iocbs
9586  * - Iterate through the iocb txq and free each entry
9587  *   in the list.
9588  * - Free up any buffer posted to the HBA
9589  * - Free mailbox commands in the mailbox queue.
9590  **/
9591 int
9592 lpfc_sli_hba_down(struct lpfc_hba *phba)
9593 {
9594 	LIST_HEAD(completions);
9595 	struct lpfc_sli *psli = &phba->sli;
9596 	struct lpfc_sli_ring *pring;
9597 	struct lpfc_dmabuf *buf_ptr;
9598 	unsigned long flags = 0;
9599 	int i;
9600 
9601 	/* Shutdown the mailbox command sub-system */
9602 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
9603 
9604 	lpfc_hba_down_prep(phba);
9605 
9606 	lpfc_fabric_abort_hba(phba);
9607 
9608 	spin_lock_irqsave(&phba->hbalock, flags);
9609 	for (i = 0; i < psli->num_rings; i++) {
9610 		pring = &psli->ring[i];
9611 		/* Only slow rings */
9612 		if (pring->ringno == LPFC_ELS_RING) {
9613 			pring->flag |= LPFC_DEFERRED_RING_EVENT;
9614 			/* Set the lpfc data pending flag */
9615 			set_bit(LPFC_DATA_READY, &phba->data_flags);
9616 		}
9617 
9618 		/*
9619 		 * Error everything on the txq since these iocbs have not been
9620 		 * given to the FW yet.
9621 		 */
9622 		list_splice_init(&pring->txq, &completions);
9623 	}
9624 	spin_unlock_irqrestore(&phba->hbalock, flags);
9625 
9626 	/* Cancel all the IOCBs from the completions list */
9627 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
9628 			      IOERR_SLI_DOWN);
9629 
9630 	spin_lock_irqsave(&phba->hbalock, flags);
9631 	list_splice_init(&phba->elsbuf, &completions);
9632 	phba->elsbuf_cnt = 0;
9633 	phba->elsbuf_prev_cnt = 0;
9634 	spin_unlock_irqrestore(&phba->hbalock, flags);
9635 
9636 	while (!list_empty(&completions)) {
9637 		list_remove_head(&completions, buf_ptr,
9638 			struct lpfc_dmabuf, list);
9639 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
9640 		kfree(buf_ptr);
9641 	}
9642 
9643 	/* Return any active mbox cmds */
9644 	del_timer_sync(&psli->mbox_tmo);
9645 
9646 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
9647 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
9648 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
9649 
9650 	return 1;
9651 }
9652 
9653 /**
9654  * lpfc_sli_pcimem_bcopy - SLI memory copy function
9655  * @srcp: Source memory pointer.
9656  * @destp: Destination memory pointer.
9657  * @cnt: Number of words required to be copied.
9658  *
9659  * This function is used for copying data between driver memory
9660  * and the SLI memory. This function also changes the endianness
9661  * of each word if native endianness is different from SLI
9662  * endianness. This function can be called with or without
9663  * lock.
9664  **/
9665 void
9666 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
9667 {
9668 	uint32_t *src = srcp;
9669 	uint32_t *dest = destp;
9670 	uint32_t ldata;
9671 	int i;
9672 
9673 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
9674 		ldata = *src;
9675 		ldata = le32_to_cpu(ldata);
9676 		*dest = ldata;
9677 		src++;
9678 		dest++;
9679 	}
9680 }
9681 
9682 
9683 /**
9684  * lpfc_sli_bemem_bcopy - SLI memory copy function
9685  * @srcp: Source memory pointer.
9686  * @destp: Destination memory pointer.
9687  * @cnt: Number of words required to be copied.
9688  *
9689  * This function is used for copying data between a data structure
9690  * with big endian representation to local endianness.
9691  * This function can be called with or without lock.
9692  **/
9693 void
9694 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
9695 {
9696 	uint32_t *src = srcp;
9697 	uint32_t *dest = destp;
9698 	uint32_t ldata;
9699 	int i;
9700 
9701 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
9702 		ldata = *src;
9703 		ldata = be32_to_cpu(ldata);
9704 		*dest = ldata;
9705 		src++;
9706 		dest++;
9707 	}
9708 }
9709 
9710 /**
9711  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
9712  * @phba: Pointer to HBA context object.
9713  * @pring: Pointer to driver SLI ring object.
9714  * @mp: Pointer to driver buffer object.
9715  *
9716  * This function is called with no lock held.
9717  * It always return zero after adding the buffer to the postbufq
9718  * buffer list.
9719  **/
9720 int
9721 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9722 			 struct lpfc_dmabuf *mp)
9723 {
9724 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
9725 	   later */
9726 	spin_lock_irq(&phba->hbalock);
9727 	list_add_tail(&mp->list, &pring->postbufq);
9728 	pring->postbufq_cnt++;
9729 	spin_unlock_irq(&phba->hbalock);
9730 	return 0;
9731 }
9732 
9733 /**
9734  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
9735  * @phba: Pointer to HBA context object.
9736  *
9737  * When HBQ is enabled, buffers are searched based on tags. This function
9738  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
9739  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
9740  * does not conflict with tags of buffer posted for unsolicited events.
9741  * The function returns the allocated tag. The function is called with
9742  * no locks held.
9743  **/
9744 uint32_t
9745 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
9746 {
9747 	spin_lock_irq(&phba->hbalock);
9748 	phba->buffer_tag_count++;
9749 	/*
9750 	 * Always set the QUE_BUFTAG_BIT to distiguish between
9751 	 * a tag assigned by HBQ.
9752 	 */
9753 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
9754 	spin_unlock_irq(&phba->hbalock);
9755 	return phba->buffer_tag_count;
9756 }
9757 
9758 /**
9759  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
9760  * @phba: Pointer to HBA context object.
9761  * @pring: Pointer to driver SLI ring object.
9762  * @tag: Buffer tag.
9763  *
9764  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
9765  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
9766  * iocb is posted to the response ring with the tag of the buffer.
9767  * This function searches the pring->postbufq list using the tag
9768  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
9769  * iocb. If the buffer is found then lpfc_dmabuf object of the
9770  * buffer is returned to the caller else NULL is returned.
9771  * This function is called with no lock held.
9772  **/
9773 struct lpfc_dmabuf *
9774 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9775 			uint32_t tag)
9776 {
9777 	struct lpfc_dmabuf *mp, *next_mp;
9778 	struct list_head *slp = &pring->postbufq;
9779 
9780 	/* Search postbufq, from the beginning, looking for a match on tag */
9781 	spin_lock_irq(&phba->hbalock);
9782 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
9783 		if (mp->buffer_tag == tag) {
9784 			list_del_init(&mp->list);
9785 			pring->postbufq_cnt--;
9786 			spin_unlock_irq(&phba->hbalock);
9787 			return mp;
9788 		}
9789 	}
9790 
9791 	spin_unlock_irq(&phba->hbalock);
9792 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9793 			"0402 Cannot find virtual addr for buffer tag on "
9794 			"ring %d Data x%lx x%p x%p x%x\n",
9795 			pring->ringno, (unsigned long) tag,
9796 			slp->next, slp->prev, pring->postbufq_cnt);
9797 
9798 	return NULL;
9799 }
9800 
9801 /**
9802  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
9803  * @phba: Pointer to HBA context object.
9804  * @pring: Pointer to driver SLI ring object.
9805  * @phys: DMA address of the buffer.
9806  *
9807  * This function searches the buffer list using the dma_address
9808  * of unsolicited event to find the driver's lpfc_dmabuf object
9809  * corresponding to the dma_address. The function returns the
9810  * lpfc_dmabuf object if a buffer is found else it returns NULL.
9811  * This function is called by the ct and els unsolicited event
9812  * handlers to get the buffer associated with the unsolicited
9813  * event.
9814  *
9815  * This function is called with no lock held.
9816  **/
9817 struct lpfc_dmabuf *
9818 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9819 			 dma_addr_t phys)
9820 {
9821 	struct lpfc_dmabuf *mp, *next_mp;
9822 	struct list_head *slp = &pring->postbufq;
9823 
9824 	/* Search postbufq, from the beginning, looking for a match on phys */
9825 	spin_lock_irq(&phba->hbalock);
9826 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
9827 		if (mp->phys == phys) {
9828 			list_del_init(&mp->list);
9829 			pring->postbufq_cnt--;
9830 			spin_unlock_irq(&phba->hbalock);
9831 			return mp;
9832 		}
9833 	}
9834 
9835 	spin_unlock_irq(&phba->hbalock);
9836 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9837 			"0410 Cannot find virtual addr for mapped buf on "
9838 			"ring %d Data x%llx x%p x%p x%x\n",
9839 			pring->ringno, (unsigned long long)phys,
9840 			slp->next, slp->prev, pring->postbufq_cnt);
9841 	return NULL;
9842 }
9843 
9844 /**
9845  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
9846  * @phba: Pointer to HBA context object.
9847  * @cmdiocb: Pointer to driver command iocb object.
9848  * @rspiocb: Pointer to driver response iocb object.
9849  *
9850  * This function is the completion handler for the abort iocbs for
9851  * ELS commands. This function is called from the ELS ring event
9852  * handler with no lock held. This function frees memory resources
9853  * associated with the abort iocb.
9854  **/
9855 static void
9856 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
9857 			struct lpfc_iocbq *rspiocb)
9858 {
9859 	IOCB_t *irsp = &rspiocb->iocb;
9860 	uint16_t abort_iotag, abort_context;
9861 	struct lpfc_iocbq *abort_iocb = NULL;
9862 
9863 	if (irsp->ulpStatus) {
9864 
9865 		/*
9866 		 * Assume that the port already completed and returned, or
9867 		 * will return the iocb. Just Log the message.
9868 		 */
9869 		abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
9870 		abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
9871 
9872 		spin_lock_irq(&phba->hbalock);
9873 		if (phba->sli_rev < LPFC_SLI_REV4) {
9874 			if (abort_iotag != 0 &&
9875 				abort_iotag <= phba->sli.last_iotag)
9876 				abort_iocb =
9877 					phba->sli.iocbq_lookup[abort_iotag];
9878 		} else
9879 			/* For sli4 the abort_tag is the XRI,
9880 			 * so the abort routine puts the iotag  of the iocb
9881 			 * being aborted in the context field of the abort
9882 			 * IOCB.
9883 			 */
9884 			abort_iocb = phba->sli.iocbq_lookup[abort_context];
9885 
9886 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
9887 				"0327 Cannot abort els iocb %p "
9888 				"with tag %x context %x, abort status %x, "
9889 				"abort code %x\n",
9890 				abort_iocb, abort_iotag, abort_context,
9891 				irsp->ulpStatus, irsp->un.ulpWord[4]);
9892 
9893 		spin_unlock_irq(&phba->hbalock);
9894 	}
9895 	lpfc_sli_release_iocbq(phba, cmdiocb);
9896 	return;
9897 }
9898 
9899 /**
9900  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
9901  * @phba: Pointer to HBA context object.
9902  * @cmdiocb: Pointer to driver command iocb object.
9903  * @rspiocb: Pointer to driver response iocb object.
9904  *
9905  * The function is called from SLI ring event handler with no
9906  * lock held. This function is the completion handler for ELS commands
9907  * which are aborted. The function frees memory resources used for
9908  * the aborted ELS commands.
9909  **/
9910 static void
9911 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
9912 		     struct lpfc_iocbq *rspiocb)
9913 {
9914 	IOCB_t *irsp = &rspiocb->iocb;
9915 
9916 	/* ELS cmd tag <ulpIoTag> completes */
9917 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
9918 			"0139 Ignoring ELS cmd tag x%x completion Data: "
9919 			"x%x x%x x%x\n",
9920 			irsp->ulpIoTag, irsp->ulpStatus,
9921 			irsp->un.ulpWord[4], irsp->ulpTimeout);
9922 	if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
9923 		lpfc_ct_free_iocb(phba, cmdiocb);
9924 	else
9925 		lpfc_els_free_iocb(phba, cmdiocb);
9926 	return;
9927 }
9928 
9929 /**
9930  * lpfc_sli_abort_iotag_issue - Issue abort for a command iocb
9931  * @phba: Pointer to HBA context object.
9932  * @pring: Pointer to driver SLI ring object.
9933  * @cmdiocb: Pointer to driver command iocb object.
9934  *
9935  * This function issues an abort iocb for the provided command iocb down to
9936  * the port. Other than the case the outstanding command iocb is an abort
9937  * request, this function issues abort out unconditionally. This function is
9938  * called with hbalock held. The function returns 0 when it fails due to
9939  * memory allocation failure or when the command iocb is an abort request.
9940  **/
9941 static int
9942 lpfc_sli_abort_iotag_issue(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9943 			   struct lpfc_iocbq *cmdiocb)
9944 {
9945 	struct lpfc_vport *vport = cmdiocb->vport;
9946 	struct lpfc_iocbq *abtsiocbp;
9947 	IOCB_t *icmd = NULL;
9948 	IOCB_t *iabt = NULL;
9949 	int ring_number;
9950 	int retval;
9951 	unsigned long iflags;
9952 
9953 	lockdep_assert_held(&phba->hbalock);
9954 
9955 	/*
9956 	 * There are certain command types we don't want to abort.  And we
9957 	 * don't want to abort commands that are already in the process of
9958 	 * being aborted.
9959 	 */
9960 	icmd = &cmdiocb->iocb;
9961 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
9962 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
9963 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
9964 		return 0;
9965 
9966 	/* issue ABTS for this IOCB based on iotag */
9967 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
9968 	if (abtsiocbp == NULL)
9969 		return 0;
9970 
9971 	/* This signals the response to set the correct status
9972 	 * before calling the completion handler
9973 	 */
9974 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
9975 
9976 	iabt = &abtsiocbp->iocb;
9977 	iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
9978 	iabt->un.acxri.abortContextTag = icmd->ulpContext;
9979 	if (phba->sli_rev == LPFC_SLI_REV4) {
9980 		iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
9981 		iabt->un.acxri.abortContextTag = cmdiocb->iotag;
9982 	}
9983 	else
9984 		iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
9985 	iabt->ulpLe = 1;
9986 	iabt->ulpClass = icmd->ulpClass;
9987 
9988 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
9989 	abtsiocbp->fcp_wqidx = cmdiocb->fcp_wqidx;
9990 	if (cmdiocb->iocb_flag & LPFC_IO_FCP)
9991 		abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
9992 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
9993 		abtsiocbp->iocb_flag |= LPFC_IO_FOF;
9994 
9995 	if (phba->link_state >= LPFC_LINK_UP)
9996 		iabt->ulpCommand = CMD_ABORT_XRI_CN;
9997 	else
9998 		iabt->ulpCommand = CMD_CLOSE_XRI_CN;
9999 
10000 	abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
10001 
10002 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
10003 			 "0339 Abort xri x%x, original iotag x%x, "
10004 			 "abort cmd iotag x%x\n",
10005 			 iabt->un.acxri.abortIoTag,
10006 			 iabt->un.acxri.abortContextTag,
10007 			 abtsiocbp->iotag);
10008 
10009 	if (phba->sli_rev == LPFC_SLI_REV4) {
10010 		ring_number =
10011 			lpfc_sli_calc_ring(phba, pring->ringno, abtsiocbp);
10012 		if (unlikely(ring_number == LPFC_HBA_ERROR))
10013 			return 0;
10014 		pring = &phba->sli.ring[ring_number];
10015 		/* Note: both hbalock and ring_lock need to be set here */
10016 		spin_lock_irqsave(&pring->ring_lock, iflags);
10017 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
10018 			abtsiocbp, 0);
10019 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
10020 	} else {
10021 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
10022 			abtsiocbp, 0);
10023 	}
10024 
10025 	if (retval)
10026 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
10027 
10028 	/*
10029 	 * Caller to this routine should check for IOCB_ERROR
10030 	 * and handle it properly.  This routine no longer removes
10031 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
10032 	 */
10033 	return retval;
10034 }
10035 
10036 /**
10037  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
10038  * @phba: Pointer to HBA context object.
10039  * @pring: Pointer to driver SLI ring object.
10040  * @cmdiocb: Pointer to driver command iocb object.
10041  *
10042  * This function issues an abort iocb for the provided command iocb. In case
10043  * of unloading, the abort iocb will not be issued to commands on the ELS
10044  * ring. Instead, the callback function shall be changed to those commands
10045  * so that nothing happens when them finishes. This function is called with
10046  * hbalock held. The function returns 0 when the command iocb is an abort
10047  * request.
10048  **/
10049 int
10050 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10051 			   struct lpfc_iocbq *cmdiocb)
10052 {
10053 	struct lpfc_vport *vport = cmdiocb->vport;
10054 	int retval = IOCB_ERROR;
10055 	IOCB_t *icmd = NULL;
10056 
10057 	lockdep_assert_held(&phba->hbalock);
10058 
10059 	/*
10060 	 * There are certain command types we don't want to abort.  And we
10061 	 * don't want to abort commands that are already in the process of
10062 	 * being aborted.
10063 	 */
10064 	icmd = &cmdiocb->iocb;
10065 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
10066 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
10067 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
10068 		return 0;
10069 
10070 	/*
10071 	 * If we're unloading, don't abort iocb on the ELS ring, but change
10072 	 * the callback so that nothing happens when it finishes.
10073 	 */
10074 	if ((vport->load_flag & FC_UNLOADING) &&
10075 	    (pring->ringno == LPFC_ELS_RING)) {
10076 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
10077 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
10078 		else
10079 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
10080 		goto abort_iotag_exit;
10081 	}
10082 
10083 	/* Now, we try to issue the abort to the cmdiocb out */
10084 	retval = lpfc_sli_abort_iotag_issue(phba, pring, cmdiocb);
10085 
10086 abort_iotag_exit:
10087 	/*
10088 	 * Caller to this routine should check for IOCB_ERROR
10089 	 * and handle it properly.  This routine no longer removes
10090 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
10091 	 */
10092 	return retval;
10093 }
10094 
10095 /**
10096  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
10097  * @phba: pointer to lpfc HBA data structure.
10098  *
10099  * This routine will abort all pending and outstanding iocbs to an HBA.
10100  **/
10101 void
10102 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
10103 {
10104 	struct lpfc_sli *psli = &phba->sli;
10105 	struct lpfc_sli_ring *pring;
10106 	int i;
10107 
10108 	for (i = 0; i < psli->num_rings; i++) {
10109 		pring = &psli->ring[i];
10110 		lpfc_sli_abort_iocb_ring(phba, pring);
10111 	}
10112 }
10113 
10114 /**
10115  * lpfc_sli_validate_fcp_iocb - find commands associated with a vport or LUN
10116  * @iocbq: Pointer to driver iocb object.
10117  * @vport: Pointer to driver virtual port object.
10118  * @tgt_id: SCSI ID of the target.
10119  * @lun_id: LUN ID of the scsi device.
10120  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
10121  *
10122  * This function acts as an iocb filter for functions which abort or count
10123  * all FCP iocbs pending on a lun/SCSI target/SCSI host. It will return
10124  * 0 if the filtering criteria is met for the given iocb and will return
10125  * 1 if the filtering criteria is not met.
10126  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
10127  * given iocb is for the SCSI device specified by vport, tgt_id and
10128  * lun_id parameter.
10129  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
10130  * given iocb is for the SCSI target specified by vport and tgt_id
10131  * parameters.
10132  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
10133  * given iocb is for the SCSI host associated with the given vport.
10134  * This function is called with no locks held.
10135  **/
10136 static int
10137 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
10138 			   uint16_t tgt_id, uint64_t lun_id,
10139 			   lpfc_ctx_cmd ctx_cmd)
10140 {
10141 	struct lpfc_scsi_buf *lpfc_cmd;
10142 	int rc = 1;
10143 
10144 	if (!(iocbq->iocb_flag &  LPFC_IO_FCP))
10145 		return rc;
10146 
10147 	if (iocbq->vport != vport)
10148 		return rc;
10149 
10150 	lpfc_cmd = container_of(iocbq, struct lpfc_scsi_buf, cur_iocbq);
10151 
10152 	if (lpfc_cmd->pCmd == NULL)
10153 		return rc;
10154 
10155 	switch (ctx_cmd) {
10156 	case LPFC_CTX_LUN:
10157 		if ((lpfc_cmd->rdata->pnode) &&
10158 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
10159 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
10160 			rc = 0;
10161 		break;
10162 	case LPFC_CTX_TGT:
10163 		if ((lpfc_cmd->rdata->pnode) &&
10164 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
10165 			rc = 0;
10166 		break;
10167 	case LPFC_CTX_HOST:
10168 		rc = 0;
10169 		break;
10170 	default:
10171 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
10172 			__func__, ctx_cmd);
10173 		break;
10174 	}
10175 
10176 	return rc;
10177 }
10178 
10179 /**
10180  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
10181  * @vport: Pointer to virtual port.
10182  * @tgt_id: SCSI ID of the target.
10183  * @lun_id: LUN ID of the scsi device.
10184  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
10185  *
10186  * This function returns number of FCP commands pending for the vport.
10187  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
10188  * commands pending on the vport associated with SCSI device specified
10189  * by tgt_id and lun_id parameters.
10190  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
10191  * commands pending on the vport associated with SCSI target specified
10192  * by tgt_id parameter.
10193  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
10194  * commands pending on the vport.
10195  * This function returns the number of iocbs which satisfy the filter.
10196  * This function is called without any lock held.
10197  **/
10198 int
10199 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
10200 		  lpfc_ctx_cmd ctx_cmd)
10201 {
10202 	struct lpfc_hba *phba = vport->phba;
10203 	struct lpfc_iocbq *iocbq;
10204 	int sum, i;
10205 
10206 	spin_lock_irq(&phba->hbalock);
10207 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
10208 		iocbq = phba->sli.iocbq_lookup[i];
10209 
10210 		if (lpfc_sli_validate_fcp_iocb (iocbq, vport, tgt_id, lun_id,
10211 						ctx_cmd) == 0)
10212 			sum++;
10213 	}
10214 	spin_unlock_irq(&phba->hbalock);
10215 
10216 	return sum;
10217 }
10218 
10219 /**
10220  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
10221  * @phba: Pointer to HBA context object
10222  * @cmdiocb: Pointer to command iocb object.
10223  * @rspiocb: Pointer to response iocb object.
10224  *
10225  * This function is called when an aborted FCP iocb completes. This
10226  * function is called by the ring event handler with no lock held.
10227  * This function frees the iocb.
10228  **/
10229 void
10230 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
10231 			struct lpfc_iocbq *rspiocb)
10232 {
10233 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10234 			"3096 ABORT_XRI_CN completing on rpi x%x "
10235 			"original iotag x%x, abort cmd iotag x%x "
10236 			"status 0x%x, reason 0x%x\n",
10237 			cmdiocb->iocb.un.acxri.abortContextTag,
10238 			cmdiocb->iocb.un.acxri.abortIoTag,
10239 			cmdiocb->iotag, rspiocb->iocb.ulpStatus,
10240 			rspiocb->iocb.un.ulpWord[4]);
10241 	lpfc_sli_release_iocbq(phba, cmdiocb);
10242 	return;
10243 }
10244 
10245 /**
10246  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
10247  * @vport: Pointer to virtual port.
10248  * @pring: Pointer to driver SLI ring object.
10249  * @tgt_id: SCSI ID of the target.
10250  * @lun_id: LUN ID of the scsi device.
10251  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
10252  *
10253  * This function sends an abort command for every SCSI command
10254  * associated with the given virtual port pending on the ring
10255  * filtered by lpfc_sli_validate_fcp_iocb function.
10256  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
10257  * FCP iocbs associated with lun specified by tgt_id and lun_id
10258  * parameters
10259  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
10260  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
10261  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
10262  * FCP iocbs associated with virtual port.
10263  * This function returns number of iocbs it failed to abort.
10264  * This function is called with no locks held.
10265  **/
10266 int
10267 lpfc_sli_abort_iocb(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
10268 		    uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd abort_cmd)
10269 {
10270 	struct lpfc_hba *phba = vport->phba;
10271 	struct lpfc_iocbq *iocbq;
10272 	struct lpfc_iocbq *abtsiocb;
10273 	IOCB_t *cmd = NULL;
10274 	int errcnt = 0, ret_val = 0;
10275 	int i;
10276 
10277 	for (i = 1; i <= phba->sli.last_iotag; i++) {
10278 		iocbq = phba->sli.iocbq_lookup[i];
10279 
10280 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
10281 					       abort_cmd) != 0)
10282 			continue;
10283 
10284 		/*
10285 		 * If the iocbq is already being aborted, don't take a second
10286 		 * action, but do count it.
10287 		 */
10288 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
10289 			continue;
10290 
10291 		/* issue ABTS for this IOCB based on iotag */
10292 		abtsiocb = lpfc_sli_get_iocbq(phba);
10293 		if (abtsiocb == NULL) {
10294 			errcnt++;
10295 			continue;
10296 		}
10297 
10298 		/* indicate the IO is being aborted by the driver. */
10299 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
10300 
10301 		cmd = &iocbq->iocb;
10302 		abtsiocb->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
10303 		abtsiocb->iocb.un.acxri.abortContextTag = cmd->ulpContext;
10304 		if (phba->sli_rev == LPFC_SLI_REV4)
10305 			abtsiocb->iocb.un.acxri.abortIoTag = iocbq->sli4_xritag;
10306 		else
10307 			abtsiocb->iocb.un.acxri.abortIoTag = cmd->ulpIoTag;
10308 		abtsiocb->iocb.ulpLe = 1;
10309 		abtsiocb->iocb.ulpClass = cmd->ulpClass;
10310 		abtsiocb->vport = vport;
10311 
10312 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
10313 		abtsiocb->fcp_wqidx = iocbq->fcp_wqidx;
10314 		if (iocbq->iocb_flag & LPFC_IO_FCP)
10315 			abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
10316 		if (iocbq->iocb_flag & LPFC_IO_FOF)
10317 			abtsiocb->iocb_flag |= LPFC_IO_FOF;
10318 
10319 		if (lpfc_is_link_up(phba))
10320 			abtsiocb->iocb.ulpCommand = CMD_ABORT_XRI_CN;
10321 		else
10322 			abtsiocb->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
10323 
10324 		/* Setup callback routine and issue the command. */
10325 		abtsiocb->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
10326 		ret_val = lpfc_sli_issue_iocb(phba, pring->ringno,
10327 					      abtsiocb, 0);
10328 		if (ret_val == IOCB_ERROR) {
10329 			lpfc_sli_release_iocbq(phba, abtsiocb);
10330 			errcnt++;
10331 			continue;
10332 		}
10333 	}
10334 
10335 	return errcnt;
10336 }
10337 
10338 /**
10339  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
10340  * @vport: Pointer to virtual port.
10341  * @pring: Pointer to driver SLI ring object.
10342  * @tgt_id: SCSI ID of the target.
10343  * @lun_id: LUN ID of the scsi device.
10344  * @taskmgmt_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
10345  *
10346  * This function sends an abort command for every SCSI command
10347  * associated with the given virtual port pending on the ring
10348  * filtered by lpfc_sli_validate_fcp_iocb function.
10349  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
10350  * FCP iocbs associated with lun specified by tgt_id and lun_id
10351  * parameters
10352  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
10353  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
10354  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
10355  * FCP iocbs associated with virtual port.
10356  * This function returns number of iocbs it aborted .
10357  * This function is called with no locks held right after a taskmgmt
10358  * command is sent.
10359  **/
10360 int
10361 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
10362 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
10363 {
10364 	struct lpfc_hba *phba = vport->phba;
10365 	struct lpfc_scsi_buf *lpfc_cmd;
10366 	struct lpfc_iocbq *abtsiocbq;
10367 	struct lpfc_nodelist *ndlp;
10368 	struct lpfc_iocbq *iocbq;
10369 	IOCB_t *icmd;
10370 	int sum, i, ret_val;
10371 	unsigned long iflags;
10372 	struct lpfc_sli_ring *pring_s4;
10373 	uint32_t ring_number;
10374 
10375 	spin_lock_irq(&phba->hbalock);
10376 
10377 	/* all I/Os are in process of being flushed */
10378 	if (phba->hba_flag & HBA_FCP_IOQ_FLUSH) {
10379 		spin_unlock_irq(&phba->hbalock);
10380 		return 0;
10381 	}
10382 	sum = 0;
10383 
10384 	for (i = 1; i <= phba->sli.last_iotag; i++) {
10385 		iocbq = phba->sli.iocbq_lookup[i];
10386 
10387 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
10388 					       cmd) != 0)
10389 			continue;
10390 
10391 		/*
10392 		 * If the iocbq is already being aborted, don't take a second
10393 		 * action, but do count it.
10394 		 */
10395 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
10396 			continue;
10397 
10398 		/* issue ABTS for this IOCB based on iotag */
10399 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
10400 		if (abtsiocbq == NULL)
10401 			continue;
10402 
10403 		icmd = &iocbq->iocb;
10404 		abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
10405 		abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
10406 		if (phba->sli_rev == LPFC_SLI_REV4)
10407 			abtsiocbq->iocb.un.acxri.abortIoTag =
10408 							 iocbq->sli4_xritag;
10409 		else
10410 			abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
10411 		abtsiocbq->iocb.ulpLe = 1;
10412 		abtsiocbq->iocb.ulpClass = icmd->ulpClass;
10413 		abtsiocbq->vport = vport;
10414 
10415 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
10416 		abtsiocbq->fcp_wqidx = iocbq->fcp_wqidx;
10417 		if (iocbq->iocb_flag & LPFC_IO_FCP)
10418 			abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
10419 		if (iocbq->iocb_flag & LPFC_IO_FOF)
10420 			abtsiocbq->iocb_flag |= LPFC_IO_FOF;
10421 
10422 		lpfc_cmd = container_of(iocbq, struct lpfc_scsi_buf, cur_iocbq);
10423 		ndlp = lpfc_cmd->rdata->pnode;
10424 
10425 		if (lpfc_is_link_up(phba) &&
10426 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
10427 			abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
10428 		else
10429 			abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
10430 
10431 		/* Setup callback routine and issue the command. */
10432 		abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
10433 
10434 		/*
10435 		 * Indicate the IO is being aborted by the driver and set
10436 		 * the caller's flag into the aborted IO.
10437 		 */
10438 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
10439 
10440 		if (phba->sli_rev == LPFC_SLI_REV4) {
10441 			ring_number = MAX_SLI3_CONFIGURED_RINGS +
10442 					 iocbq->fcp_wqidx;
10443 			pring_s4 = &phba->sli.ring[ring_number];
10444 			/* Note: both hbalock and ring_lock must be set here */
10445 			spin_lock_irqsave(&pring_s4->ring_lock, iflags);
10446 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
10447 							abtsiocbq, 0);
10448 			spin_unlock_irqrestore(&pring_s4->ring_lock, iflags);
10449 		} else {
10450 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
10451 							abtsiocbq, 0);
10452 		}
10453 
10454 
10455 		if (ret_val == IOCB_ERROR)
10456 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
10457 		else
10458 			sum++;
10459 	}
10460 	spin_unlock_irq(&phba->hbalock);
10461 	return sum;
10462 }
10463 
10464 /**
10465  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
10466  * @phba: Pointer to HBA context object.
10467  * @cmdiocbq: Pointer to command iocb.
10468  * @rspiocbq: Pointer to response iocb.
10469  *
10470  * This function is the completion handler for iocbs issued using
10471  * lpfc_sli_issue_iocb_wait function. This function is called by the
10472  * ring event handler function without any lock held. This function
10473  * can be called from both worker thread context and interrupt
10474  * context. This function also can be called from other thread which
10475  * cleans up the SLI layer objects.
10476  * This function copy the contents of the response iocb to the
10477  * response iocb memory object provided by the caller of
10478  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
10479  * sleeps for the iocb completion.
10480  **/
10481 static void
10482 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
10483 			struct lpfc_iocbq *cmdiocbq,
10484 			struct lpfc_iocbq *rspiocbq)
10485 {
10486 	wait_queue_head_t *pdone_q;
10487 	unsigned long iflags;
10488 	struct lpfc_scsi_buf *lpfc_cmd;
10489 
10490 	spin_lock_irqsave(&phba->hbalock, iflags);
10491 	if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
10492 
10493 		/*
10494 		 * A time out has occurred for the iocb.  If a time out
10495 		 * completion handler has been supplied, call it.  Otherwise,
10496 		 * just free the iocbq.
10497 		 */
10498 
10499 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10500 		cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
10501 		cmdiocbq->wait_iocb_cmpl = NULL;
10502 		if (cmdiocbq->iocb_cmpl)
10503 			(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
10504 		else
10505 			lpfc_sli_release_iocbq(phba, cmdiocbq);
10506 		return;
10507 	}
10508 
10509 	cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
10510 	if (cmdiocbq->context2 && rspiocbq)
10511 		memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
10512 		       &rspiocbq->iocb, sizeof(IOCB_t));
10513 
10514 	/* Set the exchange busy flag for task management commands */
10515 	if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
10516 		!(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
10517 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_scsi_buf,
10518 			cur_iocbq);
10519 		lpfc_cmd->exch_busy = rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY;
10520 	}
10521 
10522 	pdone_q = cmdiocbq->context_un.wait_queue;
10523 	if (pdone_q)
10524 		wake_up(pdone_q);
10525 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10526 	return;
10527 }
10528 
10529 /**
10530  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
10531  * @phba: Pointer to HBA context object..
10532  * @piocbq: Pointer to command iocb.
10533  * @flag: Flag to test.
10534  *
10535  * This routine grabs the hbalock and then test the iocb_flag to
10536  * see if the passed in flag is set.
10537  * Returns:
10538  * 1 if flag is set.
10539  * 0 if flag is not set.
10540  **/
10541 static int
10542 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
10543 		 struct lpfc_iocbq *piocbq, uint32_t flag)
10544 {
10545 	unsigned long iflags;
10546 	int ret;
10547 
10548 	spin_lock_irqsave(&phba->hbalock, iflags);
10549 	ret = piocbq->iocb_flag & flag;
10550 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10551 	return ret;
10552 
10553 }
10554 
10555 /**
10556  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
10557  * @phba: Pointer to HBA context object..
10558  * @pring: Pointer to sli ring.
10559  * @piocb: Pointer to command iocb.
10560  * @prspiocbq: Pointer to response iocb.
10561  * @timeout: Timeout in number of seconds.
10562  *
10563  * This function issues the iocb to firmware and waits for the
10564  * iocb to complete. The iocb_cmpl field of the shall be used
10565  * to handle iocbs which time out. If the field is NULL, the
10566  * function shall free the iocbq structure.  If more clean up is
10567  * needed, the caller is expected to provide a completion function
10568  * that will provide the needed clean up.  If the iocb command is
10569  * not completed within timeout seconds, the function will either
10570  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
10571  * completion function set in the iocb_cmpl field and then return
10572  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
10573  * resources if this function returns IOCB_TIMEDOUT.
10574  * The function waits for the iocb completion using an
10575  * non-interruptible wait.
10576  * This function will sleep while waiting for iocb completion.
10577  * So, this function should not be called from any context which
10578  * does not allow sleeping. Due to the same reason, this function
10579  * cannot be called with interrupt disabled.
10580  * This function assumes that the iocb completions occur while
10581  * this function sleep. So, this function cannot be called from
10582  * the thread which process iocb completion for this ring.
10583  * This function clears the iocb_flag of the iocb object before
10584  * issuing the iocb and the iocb completion handler sets this
10585  * flag and wakes this thread when the iocb completes.
10586  * The contents of the response iocb will be copied to prspiocbq
10587  * by the completion handler when the command completes.
10588  * This function returns IOCB_SUCCESS when success.
10589  * This function is called with no lock held.
10590  **/
10591 int
10592 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
10593 			 uint32_t ring_number,
10594 			 struct lpfc_iocbq *piocb,
10595 			 struct lpfc_iocbq *prspiocbq,
10596 			 uint32_t timeout)
10597 {
10598 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
10599 	long timeleft, timeout_req = 0;
10600 	int retval = IOCB_SUCCESS;
10601 	uint32_t creg_val;
10602 	struct lpfc_iocbq *iocb;
10603 	int txq_cnt = 0;
10604 	int txcmplq_cnt = 0;
10605 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
10606 	unsigned long iflags;
10607 	bool iocb_completed = true;
10608 
10609 	/*
10610 	 * If the caller has provided a response iocbq buffer, then context2
10611 	 * is NULL or its an error.
10612 	 */
10613 	if (prspiocbq) {
10614 		if (piocb->context2)
10615 			return IOCB_ERROR;
10616 		piocb->context2 = prspiocbq;
10617 	}
10618 
10619 	piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
10620 	piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
10621 	piocb->context_un.wait_queue = &done_q;
10622 	piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
10623 
10624 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
10625 		if (lpfc_readl(phba->HCregaddr, &creg_val))
10626 			return IOCB_ERROR;
10627 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
10628 		writel(creg_val, phba->HCregaddr);
10629 		readl(phba->HCregaddr); /* flush */
10630 	}
10631 
10632 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
10633 				     SLI_IOCB_RET_IOCB);
10634 	if (retval == IOCB_SUCCESS) {
10635 		timeout_req = msecs_to_jiffies(timeout * 1000);
10636 		timeleft = wait_event_timeout(done_q,
10637 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
10638 				timeout_req);
10639 		spin_lock_irqsave(&phba->hbalock, iflags);
10640 		if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
10641 
10642 			/*
10643 			 * IOCB timed out.  Inform the wake iocb wait
10644 			 * completion function and set local status
10645 			 */
10646 
10647 			iocb_completed = false;
10648 			piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
10649 		}
10650 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10651 		if (iocb_completed) {
10652 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10653 					"0331 IOCB wake signaled\n");
10654 			/* Note: we are not indicating if the IOCB has a success
10655 			 * status or not - that's for the caller to check.
10656 			 * IOCB_SUCCESS means just that the command was sent and
10657 			 * completed. Not that it completed successfully.
10658 			 * */
10659 		} else if (timeleft == 0) {
10660 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10661 					"0338 IOCB wait timeout error - no "
10662 					"wake response Data x%x\n", timeout);
10663 			retval = IOCB_TIMEDOUT;
10664 		} else {
10665 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10666 					"0330 IOCB wake NOT set, "
10667 					"Data x%x x%lx\n",
10668 					timeout, (timeleft / jiffies));
10669 			retval = IOCB_TIMEDOUT;
10670 		}
10671 	} else if (retval == IOCB_BUSY) {
10672 		if (phba->cfg_log_verbose & LOG_SLI) {
10673 			list_for_each_entry(iocb, &pring->txq, list) {
10674 				txq_cnt++;
10675 			}
10676 			list_for_each_entry(iocb, &pring->txcmplq, list) {
10677 				txcmplq_cnt++;
10678 			}
10679 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10680 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
10681 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
10682 		}
10683 		return retval;
10684 	} else {
10685 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10686 				"0332 IOCB wait issue failed, Data x%x\n",
10687 				retval);
10688 		retval = IOCB_ERROR;
10689 	}
10690 
10691 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
10692 		if (lpfc_readl(phba->HCregaddr, &creg_val))
10693 			return IOCB_ERROR;
10694 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
10695 		writel(creg_val, phba->HCregaddr);
10696 		readl(phba->HCregaddr); /* flush */
10697 	}
10698 
10699 	if (prspiocbq)
10700 		piocb->context2 = NULL;
10701 
10702 	piocb->context_un.wait_queue = NULL;
10703 	piocb->iocb_cmpl = NULL;
10704 	return retval;
10705 }
10706 
10707 /**
10708  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
10709  * @phba: Pointer to HBA context object.
10710  * @pmboxq: Pointer to driver mailbox object.
10711  * @timeout: Timeout in number of seconds.
10712  *
10713  * This function issues the mailbox to firmware and waits for the
10714  * mailbox command to complete. If the mailbox command is not
10715  * completed within timeout seconds, it returns MBX_TIMEOUT.
10716  * The function waits for the mailbox completion using an
10717  * interruptible wait. If the thread is woken up due to a
10718  * signal, MBX_TIMEOUT error is returned to the caller. Caller
10719  * should not free the mailbox resources, if this function returns
10720  * MBX_TIMEOUT.
10721  * This function will sleep while waiting for mailbox completion.
10722  * So, this function should not be called from any context which
10723  * does not allow sleeping. Due to the same reason, this function
10724  * cannot be called with interrupt disabled.
10725  * This function assumes that the mailbox completion occurs while
10726  * this function sleep. So, this function cannot be called from
10727  * the worker thread which processes mailbox completion.
10728  * This function is called in the context of HBA management
10729  * applications.
10730  * This function returns MBX_SUCCESS when successful.
10731  * This function is called with no lock held.
10732  **/
10733 int
10734 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
10735 			 uint32_t timeout)
10736 {
10737 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
10738 	MAILBOX_t *mb = NULL;
10739 	int retval;
10740 	unsigned long flag;
10741 
10742 	/* The caller might set context1 for extended buffer */
10743 	if (pmboxq->context1)
10744 		mb = (MAILBOX_t *)pmboxq->context1;
10745 
10746 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
10747 	/* setup wake call as IOCB callback */
10748 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
10749 	/* setup context field to pass wait_queue pointer to wake function  */
10750 	pmboxq->context1 = &done_q;
10751 
10752 	/* now issue the command */
10753 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
10754 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
10755 		wait_event_interruptible_timeout(done_q,
10756 				pmboxq->mbox_flag & LPFC_MBX_WAKE,
10757 				msecs_to_jiffies(timeout * 1000));
10758 
10759 		spin_lock_irqsave(&phba->hbalock, flag);
10760 		/* restore the possible extended buffer for free resource */
10761 		pmboxq->context1 = (uint8_t *)mb;
10762 		/*
10763 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
10764 		 * else do not free the resources.
10765 		 */
10766 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
10767 			retval = MBX_SUCCESS;
10768 		} else {
10769 			retval = MBX_TIMEOUT;
10770 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
10771 		}
10772 		spin_unlock_irqrestore(&phba->hbalock, flag);
10773 	} else {
10774 		/* restore the possible extended buffer for free resource */
10775 		pmboxq->context1 = (uint8_t *)mb;
10776 	}
10777 
10778 	return retval;
10779 }
10780 
10781 /**
10782  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
10783  * @phba: Pointer to HBA context.
10784  *
10785  * This function is called to shutdown the driver's mailbox sub-system.
10786  * It first marks the mailbox sub-system is in a block state to prevent
10787  * the asynchronous mailbox command from issued off the pending mailbox
10788  * command queue. If the mailbox command sub-system shutdown is due to
10789  * HBA error conditions such as EEH or ERATT, this routine shall invoke
10790  * the mailbox sub-system flush routine to forcefully bring down the
10791  * mailbox sub-system. Otherwise, if it is due to normal condition (such
10792  * as with offline or HBA function reset), this routine will wait for the
10793  * outstanding mailbox command to complete before invoking the mailbox
10794  * sub-system flush routine to gracefully bring down mailbox sub-system.
10795  **/
10796 void
10797 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
10798 {
10799 	struct lpfc_sli *psli = &phba->sli;
10800 	unsigned long timeout;
10801 
10802 	if (mbx_action == LPFC_MBX_NO_WAIT) {
10803 		/* delay 100ms for port state */
10804 		msleep(100);
10805 		lpfc_sli_mbox_sys_flush(phba);
10806 		return;
10807 	}
10808 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
10809 
10810 	spin_lock_irq(&phba->hbalock);
10811 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
10812 
10813 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
10814 		/* Determine how long we might wait for the active mailbox
10815 		 * command to be gracefully completed by firmware.
10816 		 */
10817 		if (phba->sli.mbox_active)
10818 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
10819 						phba->sli.mbox_active) *
10820 						1000) + jiffies;
10821 		spin_unlock_irq(&phba->hbalock);
10822 
10823 		while (phba->sli.mbox_active) {
10824 			/* Check active mailbox complete status every 2ms */
10825 			msleep(2);
10826 			if (time_after(jiffies, timeout))
10827 				/* Timeout, let the mailbox flush routine to
10828 				 * forcefully release active mailbox command
10829 				 */
10830 				break;
10831 		}
10832 	} else
10833 		spin_unlock_irq(&phba->hbalock);
10834 
10835 	lpfc_sli_mbox_sys_flush(phba);
10836 }
10837 
10838 /**
10839  * lpfc_sli_eratt_read - read sli-3 error attention events
10840  * @phba: Pointer to HBA context.
10841  *
10842  * This function is called to read the SLI3 device error attention registers
10843  * for possible error attention events. The caller must hold the hostlock
10844  * with spin_lock_irq().
10845  *
10846  * This function returns 1 when there is Error Attention in the Host Attention
10847  * Register and returns 0 otherwise.
10848  **/
10849 static int
10850 lpfc_sli_eratt_read(struct lpfc_hba *phba)
10851 {
10852 	uint32_t ha_copy;
10853 
10854 	/* Read chip Host Attention (HA) register */
10855 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
10856 		goto unplug_err;
10857 
10858 	if (ha_copy & HA_ERATT) {
10859 		/* Read host status register to retrieve error event */
10860 		if (lpfc_sli_read_hs(phba))
10861 			goto unplug_err;
10862 
10863 		/* Check if there is a deferred error condition is active */
10864 		if ((HS_FFER1 & phba->work_hs) &&
10865 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
10866 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
10867 			phba->hba_flag |= DEFER_ERATT;
10868 			/* Clear all interrupt enable conditions */
10869 			writel(0, phba->HCregaddr);
10870 			readl(phba->HCregaddr);
10871 		}
10872 
10873 		/* Set the driver HA work bitmap */
10874 		phba->work_ha |= HA_ERATT;
10875 		/* Indicate polling handles this ERATT */
10876 		phba->hba_flag |= HBA_ERATT_HANDLED;
10877 		return 1;
10878 	}
10879 	return 0;
10880 
10881 unplug_err:
10882 	/* Set the driver HS work bitmap */
10883 	phba->work_hs |= UNPLUG_ERR;
10884 	/* Set the driver HA work bitmap */
10885 	phba->work_ha |= HA_ERATT;
10886 	/* Indicate polling handles this ERATT */
10887 	phba->hba_flag |= HBA_ERATT_HANDLED;
10888 	return 1;
10889 }
10890 
10891 /**
10892  * lpfc_sli4_eratt_read - read sli-4 error attention events
10893  * @phba: Pointer to HBA context.
10894  *
10895  * This function is called to read the SLI4 device error attention registers
10896  * for possible error attention events. The caller must hold the hostlock
10897  * with spin_lock_irq().
10898  *
10899  * This function returns 1 when there is Error Attention in the Host Attention
10900  * Register and returns 0 otherwise.
10901  **/
10902 static int
10903 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
10904 {
10905 	uint32_t uerr_sta_hi, uerr_sta_lo;
10906 	uint32_t if_type, portsmphr;
10907 	struct lpfc_register portstat_reg;
10908 
10909 	/*
10910 	 * For now, use the SLI4 device internal unrecoverable error
10911 	 * registers for error attention. This can be changed later.
10912 	 */
10913 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10914 	switch (if_type) {
10915 	case LPFC_SLI_INTF_IF_TYPE_0:
10916 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
10917 			&uerr_sta_lo) ||
10918 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
10919 			&uerr_sta_hi)) {
10920 			phba->work_hs |= UNPLUG_ERR;
10921 			phba->work_ha |= HA_ERATT;
10922 			phba->hba_flag |= HBA_ERATT_HANDLED;
10923 			return 1;
10924 		}
10925 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
10926 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
10927 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10928 					"1423 HBA Unrecoverable error: "
10929 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
10930 					"ue_mask_lo_reg=0x%x, "
10931 					"ue_mask_hi_reg=0x%x\n",
10932 					uerr_sta_lo, uerr_sta_hi,
10933 					phba->sli4_hba.ue_mask_lo,
10934 					phba->sli4_hba.ue_mask_hi);
10935 			phba->work_status[0] = uerr_sta_lo;
10936 			phba->work_status[1] = uerr_sta_hi;
10937 			phba->work_ha |= HA_ERATT;
10938 			phba->hba_flag |= HBA_ERATT_HANDLED;
10939 			return 1;
10940 		}
10941 		break;
10942 	case LPFC_SLI_INTF_IF_TYPE_2:
10943 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
10944 			&portstat_reg.word0) ||
10945 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
10946 			&portsmphr)){
10947 			phba->work_hs |= UNPLUG_ERR;
10948 			phba->work_ha |= HA_ERATT;
10949 			phba->hba_flag |= HBA_ERATT_HANDLED;
10950 			return 1;
10951 		}
10952 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
10953 			phba->work_status[0] =
10954 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
10955 			phba->work_status[1] =
10956 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
10957 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10958 					"2885 Port Status Event: "
10959 					"port status reg 0x%x, "
10960 					"port smphr reg 0x%x, "
10961 					"error 1=0x%x, error 2=0x%x\n",
10962 					portstat_reg.word0,
10963 					portsmphr,
10964 					phba->work_status[0],
10965 					phba->work_status[1]);
10966 			phba->work_ha |= HA_ERATT;
10967 			phba->hba_flag |= HBA_ERATT_HANDLED;
10968 			return 1;
10969 		}
10970 		break;
10971 	case LPFC_SLI_INTF_IF_TYPE_1:
10972 	default:
10973 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10974 				"2886 HBA Error Attention on unsupported "
10975 				"if type %d.", if_type);
10976 		return 1;
10977 	}
10978 
10979 	return 0;
10980 }
10981 
10982 /**
10983  * lpfc_sli_check_eratt - check error attention events
10984  * @phba: Pointer to HBA context.
10985  *
10986  * This function is called from timer soft interrupt context to check HBA's
10987  * error attention register bit for error attention events.
10988  *
10989  * This function returns 1 when there is Error Attention in the Host Attention
10990  * Register and returns 0 otherwise.
10991  **/
10992 int
10993 lpfc_sli_check_eratt(struct lpfc_hba *phba)
10994 {
10995 	uint32_t ha_copy;
10996 
10997 	/* If somebody is waiting to handle an eratt, don't process it
10998 	 * here. The brdkill function will do this.
10999 	 */
11000 	if (phba->link_flag & LS_IGNORE_ERATT)
11001 		return 0;
11002 
11003 	/* Check if interrupt handler handles this ERATT */
11004 	spin_lock_irq(&phba->hbalock);
11005 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
11006 		/* Interrupt handler has handled ERATT */
11007 		spin_unlock_irq(&phba->hbalock);
11008 		return 0;
11009 	}
11010 
11011 	/*
11012 	 * If there is deferred error attention, do not check for error
11013 	 * attention
11014 	 */
11015 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11016 		spin_unlock_irq(&phba->hbalock);
11017 		return 0;
11018 	}
11019 
11020 	/* If PCI channel is offline, don't process it */
11021 	if (unlikely(pci_channel_offline(phba->pcidev))) {
11022 		spin_unlock_irq(&phba->hbalock);
11023 		return 0;
11024 	}
11025 
11026 	switch (phba->sli_rev) {
11027 	case LPFC_SLI_REV2:
11028 	case LPFC_SLI_REV3:
11029 		/* Read chip Host Attention (HA) register */
11030 		ha_copy = lpfc_sli_eratt_read(phba);
11031 		break;
11032 	case LPFC_SLI_REV4:
11033 		/* Read device Uncoverable Error (UERR) registers */
11034 		ha_copy = lpfc_sli4_eratt_read(phba);
11035 		break;
11036 	default:
11037 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11038 				"0299 Invalid SLI revision (%d)\n",
11039 				phba->sli_rev);
11040 		ha_copy = 0;
11041 		break;
11042 	}
11043 	spin_unlock_irq(&phba->hbalock);
11044 
11045 	return ha_copy;
11046 }
11047 
11048 /**
11049  * lpfc_intr_state_check - Check device state for interrupt handling
11050  * @phba: Pointer to HBA context.
11051  *
11052  * This inline routine checks whether a device or its PCI slot is in a state
11053  * that the interrupt should be handled.
11054  *
11055  * This function returns 0 if the device or the PCI slot is in a state that
11056  * interrupt should be handled, otherwise -EIO.
11057  */
11058 static inline int
11059 lpfc_intr_state_check(struct lpfc_hba *phba)
11060 {
11061 	/* If the pci channel is offline, ignore all the interrupts */
11062 	if (unlikely(pci_channel_offline(phba->pcidev)))
11063 		return -EIO;
11064 
11065 	/* Update device level interrupt statistics */
11066 	phba->sli.slistat.sli_intr++;
11067 
11068 	/* Ignore all interrupts during initialization. */
11069 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
11070 		return -EIO;
11071 
11072 	return 0;
11073 }
11074 
11075 /**
11076  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
11077  * @irq: Interrupt number.
11078  * @dev_id: The device context pointer.
11079  *
11080  * This function is directly called from the PCI layer as an interrupt
11081  * service routine when device with SLI-3 interface spec is enabled with
11082  * MSI-X multi-message interrupt mode and there are slow-path events in
11083  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
11084  * interrupt mode, this function is called as part of the device-level
11085  * interrupt handler. When the PCI slot is in error recovery or the HBA
11086  * is undergoing initialization, the interrupt handler will not process
11087  * the interrupt. The link attention and ELS ring attention events are
11088  * handled by the worker thread. The interrupt handler signals the worker
11089  * thread and returns for these events. This function is called without
11090  * any lock held. It gets the hbalock to access and update SLI data
11091  * structures.
11092  *
11093  * This function returns IRQ_HANDLED when interrupt is handled else it
11094  * returns IRQ_NONE.
11095  **/
11096 irqreturn_t
11097 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
11098 {
11099 	struct lpfc_hba  *phba;
11100 	uint32_t ha_copy, hc_copy;
11101 	uint32_t work_ha_copy;
11102 	unsigned long status;
11103 	unsigned long iflag;
11104 	uint32_t control;
11105 
11106 	MAILBOX_t *mbox, *pmbox;
11107 	struct lpfc_vport *vport;
11108 	struct lpfc_nodelist *ndlp;
11109 	struct lpfc_dmabuf *mp;
11110 	LPFC_MBOXQ_t *pmb;
11111 	int rc;
11112 
11113 	/*
11114 	 * Get the driver's phba structure from the dev_id and
11115 	 * assume the HBA is not interrupting.
11116 	 */
11117 	phba = (struct lpfc_hba *)dev_id;
11118 
11119 	if (unlikely(!phba))
11120 		return IRQ_NONE;
11121 
11122 	/*
11123 	 * Stuff needs to be attented to when this function is invoked as an
11124 	 * individual interrupt handler in MSI-X multi-message interrupt mode
11125 	 */
11126 	if (phba->intr_type == MSIX) {
11127 		/* Check device state for handling interrupt */
11128 		if (lpfc_intr_state_check(phba))
11129 			return IRQ_NONE;
11130 		/* Need to read HA REG for slow-path events */
11131 		spin_lock_irqsave(&phba->hbalock, iflag);
11132 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
11133 			goto unplug_error;
11134 		/* If somebody is waiting to handle an eratt don't process it
11135 		 * here. The brdkill function will do this.
11136 		 */
11137 		if (phba->link_flag & LS_IGNORE_ERATT)
11138 			ha_copy &= ~HA_ERATT;
11139 		/* Check the need for handling ERATT in interrupt handler */
11140 		if (ha_copy & HA_ERATT) {
11141 			if (phba->hba_flag & HBA_ERATT_HANDLED)
11142 				/* ERATT polling has handled ERATT */
11143 				ha_copy &= ~HA_ERATT;
11144 			else
11145 				/* Indicate interrupt handler handles ERATT */
11146 				phba->hba_flag |= HBA_ERATT_HANDLED;
11147 		}
11148 
11149 		/*
11150 		 * If there is deferred error attention, do not check for any
11151 		 * interrupt.
11152 		 */
11153 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11154 			spin_unlock_irqrestore(&phba->hbalock, iflag);
11155 			return IRQ_NONE;
11156 		}
11157 
11158 		/* Clear up only attention source related to slow-path */
11159 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
11160 			goto unplug_error;
11161 
11162 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
11163 			HC_LAINT_ENA | HC_ERINT_ENA),
11164 			phba->HCregaddr);
11165 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
11166 			phba->HAregaddr);
11167 		writel(hc_copy, phba->HCregaddr);
11168 		readl(phba->HAregaddr); /* flush */
11169 		spin_unlock_irqrestore(&phba->hbalock, iflag);
11170 	} else
11171 		ha_copy = phba->ha_copy;
11172 
11173 	work_ha_copy = ha_copy & phba->work_ha_mask;
11174 
11175 	if (work_ha_copy) {
11176 		if (work_ha_copy & HA_LATT) {
11177 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
11178 				/*
11179 				 * Turn off Link Attention interrupts
11180 				 * until CLEAR_LA done
11181 				 */
11182 				spin_lock_irqsave(&phba->hbalock, iflag);
11183 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
11184 				if (lpfc_readl(phba->HCregaddr, &control))
11185 					goto unplug_error;
11186 				control &= ~HC_LAINT_ENA;
11187 				writel(control, phba->HCregaddr);
11188 				readl(phba->HCregaddr); /* flush */
11189 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11190 			}
11191 			else
11192 				work_ha_copy &= ~HA_LATT;
11193 		}
11194 
11195 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
11196 			/*
11197 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
11198 			 * the only slow ring.
11199 			 */
11200 			status = (work_ha_copy &
11201 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
11202 			status >>= (4*LPFC_ELS_RING);
11203 			if (status & HA_RXMASK) {
11204 				spin_lock_irqsave(&phba->hbalock, iflag);
11205 				if (lpfc_readl(phba->HCregaddr, &control))
11206 					goto unplug_error;
11207 
11208 				lpfc_debugfs_slow_ring_trc(phba,
11209 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
11210 				control, status,
11211 				(uint32_t)phba->sli.slistat.sli_intr);
11212 
11213 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
11214 					lpfc_debugfs_slow_ring_trc(phba,
11215 						"ISR Disable ring:"
11216 						"pwork:x%x hawork:x%x wait:x%x",
11217 						phba->work_ha, work_ha_copy,
11218 						(uint32_t)((unsigned long)
11219 						&phba->work_waitq));
11220 
11221 					control &=
11222 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
11223 					writel(control, phba->HCregaddr);
11224 					readl(phba->HCregaddr); /* flush */
11225 				}
11226 				else {
11227 					lpfc_debugfs_slow_ring_trc(phba,
11228 						"ISR slow ring:   pwork:"
11229 						"x%x hawork:x%x wait:x%x",
11230 						phba->work_ha, work_ha_copy,
11231 						(uint32_t)((unsigned long)
11232 						&phba->work_waitq));
11233 				}
11234 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11235 			}
11236 		}
11237 		spin_lock_irqsave(&phba->hbalock, iflag);
11238 		if (work_ha_copy & HA_ERATT) {
11239 			if (lpfc_sli_read_hs(phba))
11240 				goto unplug_error;
11241 			/*
11242 			 * Check if there is a deferred error condition
11243 			 * is active
11244 			 */
11245 			if ((HS_FFER1 & phba->work_hs) &&
11246 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
11247 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
11248 				  phba->work_hs)) {
11249 				phba->hba_flag |= DEFER_ERATT;
11250 				/* Clear all interrupt enable conditions */
11251 				writel(0, phba->HCregaddr);
11252 				readl(phba->HCregaddr);
11253 			}
11254 		}
11255 
11256 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
11257 			pmb = phba->sli.mbox_active;
11258 			pmbox = &pmb->u.mb;
11259 			mbox = phba->mbox;
11260 			vport = pmb->vport;
11261 
11262 			/* First check out the status word */
11263 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
11264 			if (pmbox->mbxOwner != OWN_HOST) {
11265 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11266 				/*
11267 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
11268 				 * mbxStatus <status>
11269 				 */
11270 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
11271 						LOG_SLI,
11272 						"(%d):0304 Stray Mailbox "
11273 						"Interrupt mbxCommand x%x "
11274 						"mbxStatus x%x\n",
11275 						(vport ? vport->vpi : 0),
11276 						pmbox->mbxCommand,
11277 						pmbox->mbxStatus);
11278 				/* clear mailbox attention bit */
11279 				work_ha_copy &= ~HA_MBATT;
11280 			} else {
11281 				phba->sli.mbox_active = NULL;
11282 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11283 				phba->last_completion_time = jiffies;
11284 				del_timer(&phba->sli.mbox_tmo);
11285 				if (pmb->mbox_cmpl) {
11286 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
11287 							MAILBOX_CMD_SIZE);
11288 					if (pmb->out_ext_byte_len &&
11289 						pmb->context2)
11290 						lpfc_sli_pcimem_bcopy(
11291 						phba->mbox_ext,
11292 						pmb->context2,
11293 						pmb->out_ext_byte_len);
11294 				}
11295 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
11296 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
11297 
11298 					lpfc_debugfs_disc_trc(vport,
11299 						LPFC_DISC_TRC_MBOX_VPORT,
11300 						"MBOX dflt rpi: : "
11301 						"status:x%x rpi:x%x",
11302 						(uint32_t)pmbox->mbxStatus,
11303 						pmbox->un.varWords[0], 0);
11304 
11305 					if (!pmbox->mbxStatus) {
11306 						mp = (struct lpfc_dmabuf *)
11307 							(pmb->context1);
11308 						ndlp = (struct lpfc_nodelist *)
11309 							pmb->context2;
11310 
11311 						/* Reg_LOGIN of dflt RPI was
11312 						 * successful. new lets get
11313 						 * rid of the RPI using the
11314 						 * same mbox buffer.
11315 						 */
11316 						lpfc_unreg_login(phba,
11317 							vport->vpi,
11318 							pmbox->un.varWords[0],
11319 							pmb);
11320 						pmb->mbox_cmpl =
11321 							lpfc_mbx_cmpl_dflt_rpi;
11322 						pmb->context1 = mp;
11323 						pmb->context2 = ndlp;
11324 						pmb->vport = vport;
11325 						rc = lpfc_sli_issue_mbox(phba,
11326 								pmb,
11327 								MBX_NOWAIT);
11328 						if (rc != MBX_BUSY)
11329 							lpfc_printf_log(phba,
11330 							KERN_ERR,
11331 							LOG_MBOX | LOG_SLI,
11332 							"0350 rc should have"
11333 							"been MBX_BUSY\n");
11334 						if (rc != MBX_NOT_FINISHED)
11335 							goto send_current_mbox;
11336 					}
11337 				}
11338 				spin_lock_irqsave(
11339 						&phba->pport->work_port_lock,
11340 						iflag);
11341 				phba->pport->work_port_events &=
11342 					~WORKER_MBOX_TMO;
11343 				spin_unlock_irqrestore(
11344 						&phba->pport->work_port_lock,
11345 						iflag);
11346 				lpfc_mbox_cmpl_put(phba, pmb);
11347 			}
11348 		} else
11349 			spin_unlock_irqrestore(&phba->hbalock, iflag);
11350 
11351 		if ((work_ha_copy & HA_MBATT) &&
11352 		    (phba->sli.mbox_active == NULL)) {
11353 send_current_mbox:
11354 			/* Process next mailbox command if there is one */
11355 			do {
11356 				rc = lpfc_sli_issue_mbox(phba, NULL,
11357 							 MBX_NOWAIT);
11358 			} while (rc == MBX_NOT_FINISHED);
11359 			if (rc != MBX_SUCCESS)
11360 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
11361 						LOG_SLI, "0349 rc should be "
11362 						"MBX_SUCCESS\n");
11363 		}
11364 
11365 		spin_lock_irqsave(&phba->hbalock, iflag);
11366 		phba->work_ha |= work_ha_copy;
11367 		spin_unlock_irqrestore(&phba->hbalock, iflag);
11368 		lpfc_worker_wake_up(phba);
11369 	}
11370 	return IRQ_HANDLED;
11371 unplug_error:
11372 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11373 	return IRQ_HANDLED;
11374 
11375 } /* lpfc_sli_sp_intr_handler */
11376 
11377 /**
11378  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
11379  * @irq: Interrupt number.
11380  * @dev_id: The device context pointer.
11381  *
11382  * This function is directly called from the PCI layer as an interrupt
11383  * service routine when device with SLI-3 interface spec is enabled with
11384  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
11385  * ring event in the HBA. However, when the device is enabled with either
11386  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
11387  * device-level interrupt handler. When the PCI slot is in error recovery
11388  * or the HBA is undergoing initialization, the interrupt handler will not
11389  * process the interrupt. The SCSI FCP fast-path ring event are handled in
11390  * the intrrupt context. This function is called without any lock held.
11391  * It gets the hbalock to access and update SLI data structures.
11392  *
11393  * This function returns IRQ_HANDLED when interrupt is handled else it
11394  * returns IRQ_NONE.
11395  **/
11396 irqreturn_t
11397 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
11398 {
11399 	struct lpfc_hba  *phba;
11400 	uint32_t ha_copy;
11401 	unsigned long status;
11402 	unsigned long iflag;
11403 
11404 	/* Get the driver's phba structure from the dev_id and
11405 	 * assume the HBA is not interrupting.
11406 	 */
11407 	phba = (struct lpfc_hba *) dev_id;
11408 
11409 	if (unlikely(!phba))
11410 		return IRQ_NONE;
11411 
11412 	/*
11413 	 * Stuff needs to be attented to when this function is invoked as an
11414 	 * individual interrupt handler in MSI-X multi-message interrupt mode
11415 	 */
11416 	if (phba->intr_type == MSIX) {
11417 		/* Check device state for handling interrupt */
11418 		if (lpfc_intr_state_check(phba))
11419 			return IRQ_NONE;
11420 		/* Need to read HA REG for FCP ring and other ring events */
11421 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
11422 			return IRQ_HANDLED;
11423 		/* Clear up only attention source related to fast-path */
11424 		spin_lock_irqsave(&phba->hbalock, iflag);
11425 		/*
11426 		 * If there is deferred error attention, do not check for
11427 		 * any interrupt.
11428 		 */
11429 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11430 			spin_unlock_irqrestore(&phba->hbalock, iflag);
11431 			return IRQ_NONE;
11432 		}
11433 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
11434 			phba->HAregaddr);
11435 		readl(phba->HAregaddr); /* flush */
11436 		spin_unlock_irqrestore(&phba->hbalock, iflag);
11437 	} else
11438 		ha_copy = phba->ha_copy;
11439 
11440 	/*
11441 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
11442 	 */
11443 	ha_copy &= ~(phba->work_ha_mask);
11444 
11445 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
11446 	status >>= (4*LPFC_FCP_RING);
11447 	if (status & HA_RXMASK)
11448 		lpfc_sli_handle_fast_ring_event(phba,
11449 						&phba->sli.ring[LPFC_FCP_RING],
11450 						status);
11451 
11452 	if (phba->cfg_multi_ring_support == 2) {
11453 		/*
11454 		 * Process all events on extra ring. Take the optimized path
11455 		 * for extra ring IO.
11456 		 */
11457 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
11458 		status >>= (4*LPFC_EXTRA_RING);
11459 		if (status & HA_RXMASK) {
11460 			lpfc_sli_handle_fast_ring_event(phba,
11461 					&phba->sli.ring[LPFC_EXTRA_RING],
11462 					status);
11463 		}
11464 	}
11465 	return IRQ_HANDLED;
11466 }  /* lpfc_sli_fp_intr_handler */
11467 
11468 /**
11469  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
11470  * @irq: Interrupt number.
11471  * @dev_id: The device context pointer.
11472  *
11473  * This function is the HBA device-level interrupt handler to device with
11474  * SLI-3 interface spec, called from the PCI layer when either MSI or
11475  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
11476  * requires driver attention. This function invokes the slow-path interrupt
11477  * attention handling function and fast-path interrupt attention handling
11478  * function in turn to process the relevant HBA attention events. This
11479  * function is called without any lock held. It gets the hbalock to access
11480  * and update SLI data structures.
11481  *
11482  * This function returns IRQ_HANDLED when interrupt is handled, else it
11483  * returns IRQ_NONE.
11484  **/
11485 irqreturn_t
11486 lpfc_sli_intr_handler(int irq, void *dev_id)
11487 {
11488 	struct lpfc_hba  *phba;
11489 	irqreturn_t sp_irq_rc, fp_irq_rc;
11490 	unsigned long status1, status2;
11491 	uint32_t hc_copy;
11492 
11493 	/*
11494 	 * Get the driver's phba structure from the dev_id and
11495 	 * assume the HBA is not interrupting.
11496 	 */
11497 	phba = (struct lpfc_hba *) dev_id;
11498 
11499 	if (unlikely(!phba))
11500 		return IRQ_NONE;
11501 
11502 	/* Check device state for handling interrupt */
11503 	if (lpfc_intr_state_check(phba))
11504 		return IRQ_NONE;
11505 
11506 	spin_lock(&phba->hbalock);
11507 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
11508 		spin_unlock(&phba->hbalock);
11509 		return IRQ_HANDLED;
11510 	}
11511 
11512 	if (unlikely(!phba->ha_copy)) {
11513 		spin_unlock(&phba->hbalock);
11514 		return IRQ_NONE;
11515 	} else if (phba->ha_copy & HA_ERATT) {
11516 		if (phba->hba_flag & HBA_ERATT_HANDLED)
11517 			/* ERATT polling has handled ERATT */
11518 			phba->ha_copy &= ~HA_ERATT;
11519 		else
11520 			/* Indicate interrupt handler handles ERATT */
11521 			phba->hba_flag |= HBA_ERATT_HANDLED;
11522 	}
11523 
11524 	/*
11525 	 * If there is deferred error attention, do not check for any interrupt.
11526 	 */
11527 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11528 		spin_unlock(&phba->hbalock);
11529 		return IRQ_NONE;
11530 	}
11531 
11532 	/* Clear attention sources except link and error attentions */
11533 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
11534 		spin_unlock(&phba->hbalock);
11535 		return IRQ_HANDLED;
11536 	}
11537 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
11538 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
11539 		phba->HCregaddr);
11540 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
11541 	writel(hc_copy, phba->HCregaddr);
11542 	readl(phba->HAregaddr); /* flush */
11543 	spin_unlock(&phba->hbalock);
11544 
11545 	/*
11546 	 * Invokes slow-path host attention interrupt handling as appropriate.
11547 	 */
11548 
11549 	/* status of events with mailbox and link attention */
11550 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
11551 
11552 	/* status of events with ELS ring */
11553 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
11554 	status2 >>= (4*LPFC_ELS_RING);
11555 
11556 	if (status1 || (status2 & HA_RXMASK))
11557 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
11558 	else
11559 		sp_irq_rc = IRQ_NONE;
11560 
11561 	/*
11562 	 * Invoke fast-path host attention interrupt handling as appropriate.
11563 	 */
11564 
11565 	/* status of events with FCP ring */
11566 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
11567 	status1 >>= (4*LPFC_FCP_RING);
11568 
11569 	/* status of events with extra ring */
11570 	if (phba->cfg_multi_ring_support == 2) {
11571 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
11572 		status2 >>= (4*LPFC_EXTRA_RING);
11573 	} else
11574 		status2 = 0;
11575 
11576 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
11577 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
11578 	else
11579 		fp_irq_rc = IRQ_NONE;
11580 
11581 	/* Return device-level interrupt handling status */
11582 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
11583 }  /* lpfc_sli_intr_handler */
11584 
11585 /**
11586  * lpfc_sli4_fcp_xri_abort_event_proc - Process fcp xri abort event
11587  * @phba: pointer to lpfc hba data structure.
11588  *
11589  * This routine is invoked by the worker thread to process all the pending
11590  * SLI4 FCP abort XRI events.
11591  **/
11592 void lpfc_sli4_fcp_xri_abort_event_proc(struct lpfc_hba *phba)
11593 {
11594 	struct lpfc_cq_event *cq_event;
11595 
11596 	/* First, declare the fcp xri abort event has been handled */
11597 	spin_lock_irq(&phba->hbalock);
11598 	phba->hba_flag &= ~FCP_XRI_ABORT_EVENT;
11599 	spin_unlock_irq(&phba->hbalock);
11600 	/* Now, handle all the fcp xri abort events */
11601 	while (!list_empty(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue)) {
11602 		/* Get the first event from the head of the event queue */
11603 		spin_lock_irq(&phba->hbalock);
11604 		list_remove_head(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue,
11605 				 cq_event, struct lpfc_cq_event, list);
11606 		spin_unlock_irq(&phba->hbalock);
11607 		/* Notify aborted XRI for FCP work queue */
11608 		lpfc_sli4_fcp_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
11609 		/* Free the event processed back to the free pool */
11610 		lpfc_sli4_cq_event_release(phba, cq_event);
11611 	}
11612 }
11613 
11614 /**
11615  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
11616  * @phba: pointer to lpfc hba data structure.
11617  *
11618  * This routine is invoked by the worker thread to process all the pending
11619  * SLI4 els abort xri events.
11620  **/
11621 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
11622 {
11623 	struct lpfc_cq_event *cq_event;
11624 
11625 	/* First, declare the els xri abort event has been handled */
11626 	spin_lock_irq(&phba->hbalock);
11627 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
11628 	spin_unlock_irq(&phba->hbalock);
11629 	/* Now, handle all the els xri abort events */
11630 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
11631 		/* Get the first event from the head of the event queue */
11632 		spin_lock_irq(&phba->hbalock);
11633 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
11634 				 cq_event, struct lpfc_cq_event, list);
11635 		spin_unlock_irq(&phba->hbalock);
11636 		/* Notify aborted XRI for ELS work queue */
11637 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
11638 		/* Free the event processed back to the free pool */
11639 		lpfc_sli4_cq_event_release(phba, cq_event);
11640 	}
11641 }
11642 
11643 /**
11644  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
11645  * @phba: pointer to lpfc hba data structure
11646  * @pIocbIn: pointer to the rspiocbq
11647  * @pIocbOut: pointer to the cmdiocbq
11648  * @wcqe: pointer to the complete wcqe
11649  *
11650  * This routine transfers the fields of a command iocbq to a response iocbq
11651  * by copying all the IOCB fields from command iocbq and transferring the
11652  * completion status information from the complete wcqe.
11653  **/
11654 static void
11655 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
11656 			      struct lpfc_iocbq *pIocbIn,
11657 			      struct lpfc_iocbq *pIocbOut,
11658 			      struct lpfc_wcqe_complete *wcqe)
11659 {
11660 	int numBdes, i;
11661 	unsigned long iflags;
11662 	uint32_t status, max_response;
11663 	struct lpfc_dmabuf *dmabuf;
11664 	struct ulp_bde64 *bpl, bde;
11665 	size_t offset = offsetof(struct lpfc_iocbq, iocb);
11666 
11667 	memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
11668 	       sizeof(struct lpfc_iocbq) - offset);
11669 	/* Map WCQE parameters into irspiocb parameters */
11670 	status = bf_get(lpfc_wcqe_c_status, wcqe);
11671 	pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
11672 	if (pIocbOut->iocb_flag & LPFC_IO_FCP)
11673 		if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
11674 			pIocbIn->iocb.un.fcpi.fcpi_parm =
11675 					pIocbOut->iocb.un.fcpi.fcpi_parm -
11676 					wcqe->total_data_placed;
11677 		else
11678 			pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
11679 	else {
11680 		pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
11681 		switch (pIocbOut->iocb.ulpCommand) {
11682 		case CMD_ELS_REQUEST64_CR:
11683 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
11684 			bpl  = (struct ulp_bde64 *)dmabuf->virt;
11685 			bde.tus.w = le32_to_cpu(bpl[1].tus.w);
11686 			max_response = bde.tus.f.bdeSize;
11687 			break;
11688 		case CMD_GEN_REQUEST64_CR:
11689 			max_response = 0;
11690 			if (!pIocbOut->context3)
11691 				break;
11692 			numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
11693 					sizeof(struct ulp_bde64);
11694 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
11695 			bpl = (struct ulp_bde64 *)dmabuf->virt;
11696 			for (i = 0; i < numBdes; i++) {
11697 				bde.tus.w = le32_to_cpu(bpl[i].tus.w);
11698 				if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
11699 					max_response += bde.tus.f.bdeSize;
11700 			}
11701 			break;
11702 		default:
11703 			max_response = wcqe->total_data_placed;
11704 			break;
11705 		}
11706 		if (max_response < wcqe->total_data_placed)
11707 			pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
11708 		else
11709 			pIocbIn->iocb.un.genreq64.bdl.bdeSize =
11710 				wcqe->total_data_placed;
11711 	}
11712 
11713 	/* Convert BG errors for completion status */
11714 	if (status == CQE_STATUS_DI_ERROR) {
11715 		pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
11716 
11717 		if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
11718 			pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
11719 		else
11720 			pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
11721 
11722 		pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
11723 		if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
11724 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11725 				BGS_GUARD_ERR_MASK;
11726 		if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
11727 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11728 				BGS_APPTAG_ERR_MASK;
11729 		if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
11730 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11731 				BGS_REFTAG_ERR_MASK;
11732 
11733 		/* Check to see if there was any good data before the error */
11734 		if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
11735 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11736 				BGS_HI_WATER_MARK_PRESENT_MASK;
11737 			pIocbIn->iocb.unsli3.sli3_bg.bghm =
11738 				wcqe->total_data_placed;
11739 		}
11740 
11741 		/*
11742 		* Set ALL the error bits to indicate we don't know what
11743 		* type of error it is.
11744 		*/
11745 		if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
11746 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11747 				(BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
11748 				BGS_GUARD_ERR_MASK);
11749 	}
11750 
11751 	/* Pick up HBA exchange busy condition */
11752 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
11753 		spin_lock_irqsave(&phba->hbalock, iflags);
11754 		pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
11755 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11756 	}
11757 }
11758 
11759 /**
11760  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
11761  * @phba: Pointer to HBA context object.
11762  * @wcqe: Pointer to work-queue completion queue entry.
11763  *
11764  * This routine handles an ELS work-queue completion event and construct
11765  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
11766  * discovery engine to handle.
11767  *
11768  * Return: Pointer to the receive IOCBQ, NULL otherwise.
11769  **/
11770 static struct lpfc_iocbq *
11771 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
11772 			       struct lpfc_iocbq *irspiocbq)
11773 {
11774 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
11775 	struct lpfc_iocbq *cmdiocbq;
11776 	struct lpfc_wcqe_complete *wcqe;
11777 	unsigned long iflags;
11778 
11779 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
11780 	spin_lock_irqsave(&pring->ring_lock, iflags);
11781 	pring->stats.iocb_event++;
11782 	/* Look up the ELS command IOCB and create pseudo response IOCB */
11783 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
11784 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
11785 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
11786 
11787 	if (unlikely(!cmdiocbq)) {
11788 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11789 				"0386 ELS complete with no corresponding "
11790 				"cmdiocb: iotag (%d)\n",
11791 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
11792 		lpfc_sli_release_iocbq(phba, irspiocbq);
11793 		return NULL;
11794 	}
11795 
11796 	/* Fake the irspiocbq and copy necessary response information */
11797 	lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
11798 
11799 	return irspiocbq;
11800 }
11801 
11802 /**
11803  * lpfc_sli4_sp_handle_async_event - Handle an asynchroous event
11804  * @phba: Pointer to HBA context object.
11805  * @cqe: Pointer to mailbox completion queue entry.
11806  *
11807  * This routine process a mailbox completion queue entry with asynchrous
11808  * event.
11809  *
11810  * Return: true if work posted to worker thread, otherwise false.
11811  **/
11812 static bool
11813 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
11814 {
11815 	struct lpfc_cq_event *cq_event;
11816 	unsigned long iflags;
11817 
11818 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11819 			"0392 Async Event: word0:x%x, word1:x%x, "
11820 			"word2:x%x, word3:x%x\n", mcqe->word0,
11821 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
11822 
11823 	/* Allocate a new internal CQ_EVENT entry */
11824 	cq_event = lpfc_sli4_cq_event_alloc(phba);
11825 	if (!cq_event) {
11826 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11827 				"0394 Failed to allocate CQ_EVENT entry\n");
11828 		return false;
11829 	}
11830 
11831 	/* Move the CQE into an asynchronous event entry */
11832 	memcpy(&cq_event->cqe, mcqe, sizeof(struct lpfc_mcqe));
11833 	spin_lock_irqsave(&phba->hbalock, iflags);
11834 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
11835 	/* Set the async event flag */
11836 	phba->hba_flag |= ASYNC_EVENT;
11837 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11838 
11839 	return true;
11840 }
11841 
11842 /**
11843  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
11844  * @phba: Pointer to HBA context object.
11845  * @cqe: Pointer to mailbox completion queue entry.
11846  *
11847  * This routine process a mailbox completion queue entry with mailbox
11848  * completion event.
11849  *
11850  * Return: true if work posted to worker thread, otherwise false.
11851  **/
11852 static bool
11853 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
11854 {
11855 	uint32_t mcqe_status;
11856 	MAILBOX_t *mbox, *pmbox;
11857 	struct lpfc_mqe *mqe;
11858 	struct lpfc_vport *vport;
11859 	struct lpfc_nodelist *ndlp;
11860 	struct lpfc_dmabuf *mp;
11861 	unsigned long iflags;
11862 	LPFC_MBOXQ_t *pmb;
11863 	bool workposted = false;
11864 	int rc;
11865 
11866 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
11867 	if (!bf_get(lpfc_trailer_completed, mcqe))
11868 		goto out_no_mqe_complete;
11869 
11870 	/* Get the reference to the active mbox command */
11871 	spin_lock_irqsave(&phba->hbalock, iflags);
11872 	pmb = phba->sli.mbox_active;
11873 	if (unlikely(!pmb)) {
11874 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
11875 				"1832 No pending MBOX command to handle\n");
11876 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11877 		goto out_no_mqe_complete;
11878 	}
11879 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11880 	mqe = &pmb->u.mqe;
11881 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
11882 	mbox = phba->mbox;
11883 	vport = pmb->vport;
11884 
11885 	/* Reset heartbeat timer */
11886 	phba->last_completion_time = jiffies;
11887 	del_timer(&phba->sli.mbox_tmo);
11888 
11889 	/* Move mbox data to caller's mailbox region, do endian swapping */
11890 	if (pmb->mbox_cmpl && mbox)
11891 		lpfc_sli_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
11892 
11893 	/*
11894 	 * For mcqe errors, conditionally move a modified error code to
11895 	 * the mbox so that the error will not be missed.
11896 	 */
11897 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
11898 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
11899 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
11900 			bf_set(lpfc_mqe_status, mqe,
11901 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
11902 	}
11903 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
11904 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
11905 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
11906 				      "MBOX dflt rpi: status:x%x rpi:x%x",
11907 				      mcqe_status,
11908 				      pmbox->un.varWords[0], 0);
11909 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
11910 			mp = (struct lpfc_dmabuf *)(pmb->context1);
11911 			ndlp = (struct lpfc_nodelist *)pmb->context2;
11912 			/* Reg_LOGIN of dflt RPI was successful. Now lets get
11913 			 * RID of the PPI using the same mbox buffer.
11914 			 */
11915 			lpfc_unreg_login(phba, vport->vpi,
11916 					 pmbox->un.varWords[0], pmb);
11917 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
11918 			pmb->context1 = mp;
11919 			pmb->context2 = ndlp;
11920 			pmb->vport = vport;
11921 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
11922 			if (rc != MBX_BUSY)
11923 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
11924 						LOG_SLI, "0385 rc should "
11925 						"have been MBX_BUSY\n");
11926 			if (rc != MBX_NOT_FINISHED)
11927 				goto send_current_mbox;
11928 		}
11929 	}
11930 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
11931 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
11932 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
11933 
11934 	/* There is mailbox completion work to do */
11935 	spin_lock_irqsave(&phba->hbalock, iflags);
11936 	__lpfc_mbox_cmpl_put(phba, pmb);
11937 	phba->work_ha |= HA_MBATT;
11938 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11939 	workposted = true;
11940 
11941 send_current_mbox:
11942 	spin_lock_irqsave(&phba->hbalock, iflags);
11943 	/* Release the mailbox command posting token */
11944 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11945 	/* Setting active mailbox pointer need to be in sync to flag clear */
11946 	phba->sli.mbox_active = NULL;
11947 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11948 	/* Wake up worker thread to post the next pending mailbox command */
11949 	lpfc_worker_wake_up(phba);
11950 out_no_mqe_complete:
11951 	if (bf_get(lpfc_trailer_consumed, mcqe))
11952 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
11953 	return workposted;
11954 }
11955 
11956 /**
11957  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
11958  * @phba: Pointer to HBA context object.
11959  * @cqe: Pointer to mailbox completion queue entry.
11960  *
11961  * This routine process a mailbox completion queue entry, it invokes the
11962  * proper mailbox complete handling or asynchrous event handling routine
11963  * according to the MCQE's async bit.
11964  *
11965  * Return: true if work posted to worker thread, otherwise false.
11966  **/
11967 static bool
11968 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_cqe *cqe)
11969 {
11970 	struct lpfc_mcqe mcqe;
11971 	bool workposted;
11972 
11973 	/* Copy the mailbox MCQE and convert endian order as needed */
11974 	lpfc_sli_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
11975 
11976 	/* Invoke the proper event handling routine */
11977 	if (!bf_get(lpfc_trailer_async, &mcqe))
11978 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
11979 	else
11980 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
11981 	return workposted;
11982 }
11983 
11984 /**
11985  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
11986  * @phba: Pointer to HBA context object.
11987  * @cq: Pointer to associated CQ
11988  * @wcqe: Pointer to work-queue completion queue entry.
11989  *
11990  * This routine handles an ELS work-queue completion event.
11991  *
11992  * Return: true if work posted to worker thread, otherwise false.
11993  **/
11994 static bool
11995 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
11996 			     struct lpfc_wcqe_complete *wcqe)
11997 {
11998 	struct lpfc_iocbq *irspiocbq;
11999 	unsigned long iflags;
12000 	struct lpfc_sli_ring *pring = cq->pring;
12001 	int txq_cnt = 0;
12002 	int txcmplq_cnt = 0;
12003 	int fcp_txcmplq_cnt = 0;
12004 
12005 	/* Get an irspiocbq for later ELS response processing use */
12006 	irspiocbq = lpfc_sli_get_iocbq(phba);
12007 	if (!irspiocbq) {
12008 		if (!list_empty(&pring->txq))
12009 			txq_cnt++;
12010 		if (!list_empty(&pring->txcmplq))
12011 			txcmplq_cnt++;
12012 		if (!list_empty(&phba->sli.ring[LPFC_FCP_RING].txcmplq))
12013 			fcp_txcmplq_cnt++;
12014 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12015 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
12016 			"fcp_txcmplq_cnt=%d, els_txcmplq_cnt=%d\n",
12017 			txq_cnt, phba->iocb_cnt,
12018 			fcp_txcmplq_cnt,
12019 			txcmplq_cnt);
12020 		return false;
12021 	}
12022 
12023 	/* Save off the slow-path queue event for work thread to process */
12024 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
12025 	spin_lock_irqsave(&phba->hbalock, iflags);
12026 	list_add_tail(&irspiocbq->cq_event.list,
12027 		      &phba->sli4_hba.sp_queue_event);
12028 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
12029 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12030 
12031 	return true;
12032 }
12033 
12034 /**
12035  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
12036  * @phba: Pointer to HBA context object.
12037  * @wcqe: Pointer to work-queue completion queue entry.
12038  *
12039  * This routine handles slow-path WQ entry comsumed event by invoking the
12040  * proper WQ release routine to the slow-path WQ.
12041  **/
12042 static void
12043 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
12044 			     struct lpfc_wcqe_release *wcqe)
12045 {
12046 	/* sanity check on queue memory */
12047 	if (unlikely(!phba->sli4_hba.els_wq))
12048 		return;
12049 	/* Check for the slow-path ELS work queue */
12050 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
12051 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
12052 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
12053 	else
12054 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12055 				"2579 Slow-path wqe consume event carries "
12056 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
12057 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
12058 				phba->sli4_hba.els_wq->queue_id);
12059 }
12060 
12061 /**
12062  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
12063  * @phba: Pointer to HBA context object.
12064  * @cq: Pointer to a WQ completion queue.
12065  * @wcqe: Pointer to work-queue completion queue entry.
12066  *
12067  * This routine handles an XRI abort event.
12068  *
12069  * Return: true if work posted to worker thread, otherwise false.
12070  **/
12071 static bool
12072 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
12073 				   struct lpfc_queue *cq,
12074 				   struct sli4_wcqe_xri_aborted *wcqe)
12075 {
12076 	bool workposted = false;
12077 	struct lpfc_cq_event *cq_event;
12078 	unsigned long iflags;
12079 
12080 	/* Allocate a new internal CQ_EVENT entry */
12081 	cq_event = lpfc_sli4_cq_event_alloc(phba);
12082 	if (!cq_event) {
12083 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12084 				"0602 Failed to allocate CQ_EVENT entry\n");
12085 		return false;
12086 	}
12087 
12088 	/* Move the CQE into the proper xri abort event list */
12089 	memcpy(&cq_event->cqe, wcqe, sizeof(struct sli4_wcqe_xri_aborted));
12090 	switch (cq->subtype) {
12091 	case LPFC_FCP:
12092 		spin_lock_irqsave(&phba->hbalock, iflags);
12093 		list_add_tail(&cq_event->list,
12094 			      &phba->sli4_hba.sp_fcp_xri_aborted_work_queue);
12095 		/* Set the fcp xri abort event flag */
12096 		phba->hba_flag |= FCP_XRI_ABORT_EVENT;
12097 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12098 		workposted = true;
12099 		break;
12100 	case LPFC_ELS:
12101 		spin_lock_irqsave(&phba->hbalock, iflags);
12102 		list_add_tail(&cq_event->list,
12103 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
12104 		/* Set the els xri abort event flag */
12105 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
12106 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12107 		workposted = true;
12108 		break;
12109 	default:
12110 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12111 				"0603 Invalid work queue CQE subtype (x%x)\n",
12112 				cq->subtype);
12113 		workposted = false;
12114 		break;
12115 	}
12116 	return workposted;
12117 }
12118 
12119 /**
12120  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
12121  * @phba: Pointer to HBA context object.
12122  * @rcqe: Pointer to receive-queue completion queue entry.
12123  *
12124  * This routine process a receive-queue completion queue entry.
12125  *
12126  * Return: true if work posted to worker thread, otherwise false.
12127  **/
12128 static bool
12129 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
12130 {
12131 	bool workposted = false;
12132 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
12133 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
12134 	struct hbq_dmabuf *dma_buf;
12135 	uint32_t status, rq_id;
12136 	unsigned long iflags;
12137 
12138 	/* sanity check on queue memory */
12139 	if (unlikely(!hrq) || unlikely(!drq))
12140 		return workposted;
12141 
12142 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
12143 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
12144 	else
12145 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
12146 	if (rq_id != hrq->queue_id)
12147 		goto out;
12148 
12149 	status = bf_get(lpfc_rcqe_status, rcqe);
12150 	switch (status) {
12151 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
12152 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12153 				"2537 Receive Frame Truncated!!\n");
12154 		hrq->RQ_buf_trunc++;
12155 	case FC_STATUS_RQ_SUCCESS:
12156 		lpfc_sli4_rq_release(hrq, drq);
12157 		spin_lock_irqsave(&phba->hbalock, iflags);
12158 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
12159 		if (!dma_buf) {
12160 			hrq->RQ_no_buf_found++;
12161 			spin_unlock_irqrestore(&phba->hbalock, iflags);
12162 			goto out;
12163 		}
12164 		hrq->RQ_rcv_buf++;
12165 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
12166 		/* save off the frame for the word thread to process */
12167 		list_add_tail(&dma_buf->cq_event.list,
12168 			      &phba->sli4_hba.sp_queue_event);
12169 		/* Frame received */
12170 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
12171 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12172 		workposted = true;
12173 		break;
12174 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
12175 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
12176 		hrq->RQ_no_posted_buf++;
12177 		/* Post more buffers if possible */
12178 		spin_lock_irqsave(&phba->hbalock, iflags);
12179 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
12180 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12181 		workposted = true;
12182 		break;
12183 	}
12184 out:
12185 	return workposted;
12186 }
12187 
12188 /**
12189  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
12190  * @phba: Pointer to HBA context object.
12191  * @cq: Pointer to the completion queue.
12192  * @wcqe: Pointer to a completion queue entry.
12193  *
12194  * This routine process a slow-path work-queue or receive queue completion queue
12195  * entry.
12196  *
12197  * Return: true if work posted to worker thread, otherwise false.
12198  **/
12199 static bool
12200 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12201 			 struct lpfc_cqe *cqe)
12202 {
12203 	struct lpfc_cqe cqevt;
12204 	bool workposted = false;
12205 
12206 	/* Copy the work queue CQE and convert endian order if needed */
12207 	lpfc_sli_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
12208 
12209 	/* Check and process for different type of WCQE and dispatch */
12210 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
12211 	case CQE_CODE_COMPL_WQE:
12212 		/* Process the WQ/RQ complete event */
12213 		phba->last_completion_time = jiffies;
12214 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
12215 				(struct lpfc_wcqe_complete *)&cqevt);
12216 		break;
12217 	case CQE_CODE_RELEASE_WQE:
12218 		/* Process the WQ release event */
12219 		lpfc_sli4_sp_handle_rel_wcqe(phba,
12220 				(struct lpfc_wcqe_release *)&cqevt);
12221 		break;
12222 	case CQE_CODE_XRI_ABORTED:
12223 		/* Process the WQ XRI abort event */
12224 		phba->last_completion_time = jiffies;
12225 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
12226 				(struct sli4_wcqe_xri_aborted *)&cqevt);
12227 		break;
12228 	case CQE_CODE_RECEIVE:
12229 	case CQE_CODE_RECEIVE_V1:
12230 		/* Process the RQ event */
12231 		phba->last_completion_time = jiffies;
12232 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
12233 				(struct lpfc_rcqe *)&cqevt);
12234 		break;
12235 	default:
12236 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12237 				"0388 Not a valid WCQE code: x%x\n",
12238 				bf_get(lpfc_cqe_code, &cqevt));
12239 		break;
12240 	}
12241 	return workposted;
12242 }
12243 
12244 /**
12245  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
12246  * @phba: Pointer to HBA context object.
12247  * @eqe: Pointer to fast-path event queue entry.
12248  *
12249  * This routine process a event queue entry from the slow-path event queue.
12250  * It will check the MajorCode and MinorCode to determine this is for a
12251  * completion event on a completion queue, if not, an error shall be logged
12252  * and just return. Otherwise, it will get to the corresponding completion
12253  * queue and process all the entries on that completion queue, rearm the
12254  * completion queue, and then return.
12255  *
12256  **/
12257 static void
12258 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
12259 	struct lpfc_queue *speq)
12260 {
12261 	struct lpfc_queue *cq = NULL, *childq;
12262 	struct lpfc_cqe *cqe;
12263 	bool workposted = false;
12264 	int ecount = 0;
12265 	uint16_t cqid;
12266 
12267 	/* Get the reference to the corresponding CQ */
12268 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
12269 
12270 	list_for_each_entry(childq, &speq->child_list, list) {
12271 		if (childq->queue_id == cqid) {
12272 			cq = childq;
12273 			break;
12274 		}
12275 	}
12276 	if (unlikely(!cq)) {
12277 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
12278 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12279 					"0365 Slow-path CQ identifier "
12280 					"(%d) does not exist\n", cqid);
12281 		return;
12282 	}
12283 
12284 	/* Process all the entries to the CQ */
12285 	switch (cq->type) {
12286 	case LPFC_MCQ:
12287 		while ((cqe = lpfc_sli4_cq_get(cq))) {
12288 			workposted |= lpfc_sli4_sp_handle_mcqe(phba, cqe);
12289 			if (!(++ecount % cq->entry_repost))
12290 				lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12291 			cq->CQ_mbox++;
12292 		}
12293 		break;
12294 	case LPFC_WCQ:
12295 		while ((cqe = lpfc_sli4_cq_get(cq))) {
12296 			if (cq->subtype == LPFC_FCP)
12297 				workposted |= lpfc_sli4_fp_handle_wcqe(phba, cq,
12298 								       cqe);
12299 			else
12300 				workposted |= lpfc_sli4_sp_handle_cqe(phba, cq,
12301 								      cqe);
12302 			if (!(++ecount % cq->entry_repost))
12303 				lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12304 		}
12305 
12306 		/* Track the max number of CQEs processed in 1 EQ */
12307 		if (ecount > cq->CQ_max_cqe)
12308 			cq->CQ_max_cqe = ecount;
12309 		break;
12310 	default:
12311 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12312 				"0370 Invalid completion queue type (%d)\n",
12313 				cq->type);
12314 		return;
12315 	}
12316 
12317 	/* Catch the no cq entry condition, log an error */
12318 	if (unlikely(ecount == 0))
12319 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12320 				"0371 No entry from the CQ: identifier "
12321 				"(x%x), type (%d)\n", cq->queue_id, cq->type);
12322 
12323 	/* In any case, flash and re-arm the RCQ */
12324 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
12325 
12326 	/* wake up worker thread if there are works to be done */
12327 	if (workposted)
12328 		lpfc_worker_wake_up(phba);
12329 }
12330 
12331 /**
12332  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
12333  * @phba: Pointer to HBA context object.
12334  * @cq: Pointer to associated CQ
12335  * @wcqe: Pointer to work-queue completion queue entry.
12336  *
12337  * This routine process a fast-path work queue completion entry from fast-path
12338  * event queue for FCP command response completion.
12339  **/
12340 static void
12341 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12342 			     struct lpfc_wcqe_complete *wcqe)
12343 {
12344 	struct lpfc_sli_ring *pring = cq->pring;
12345 	struct lpfc_iocbq *cmdiocbq;
12346 	struct lpfc_iocbq irspiocbq;
12347 	unsigned long iflags;
12348 
12349 	/* Check for response status */
12350 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
12351 		/* If resource errors reported from HBA, reduce queue
12352 		 * depth of the SCSI device.
12353 		 */
12354 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
12355 		     IOSTAT_LOCAL_REJECT)) &&
12356 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
12357 		     IOERR_NO_RESOURCES))
12358 			phba->lpfc_rampdown_queue_depth(phba);
12359 
12360 		/* Log the error status */
12361 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12362 				"0373 FCP complete error: status=x%x, "
12363 				"hw_status=x%x, total_data_specified=%d, "
12364 				"parameter=x%x, word3=x%x\n",
12365 				bf_get(lpfc_wcqe_c_status, wcqe),
12366 				bf_get(lpfc_wcqe_c_hw_status, wcqe),
12367 				wcqe->total_data_placed, wcqe->parameter,
12368 				wcqe->word3);
12369 	}
12370 
12371 	/* Look up the FCP command IOCB and create pseudo response IOCB */
12372 	spin_lock_irqsave(&pring->ring_lock, iflags);
12373 	pring->stats.iocb_event++;
12374 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
12375 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12376 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
12377 	if (unlikely(!cmdiocbq)) {
12378 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12379 				"0374 FCP complete with no corresponding "
12380 				"cmdiocb: iotag (%d)\n",
12381 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12382 		return;
12383 	}
12384 	if (unlikely(!cmdiocbq->iocb_cmpl)) {
12385 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12386 				"0375 FCP cmdiocb not callback function "
12387 				"iotag: (%d)\n",
12388 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12389 		return;
12390 	}
12391 
12392 	/* Fake the irspiocb and copy necessary response information */
12393 	lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
12394 
12395 	if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
12396 		spin_lock_irqsave(&phba->hbalock, iflags);
12397 		cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
12398 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12399 	}
12400 
12401 	/* Pass the cmd_iocb and the rsp state to the upper layer */
12402 	(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
12403 }
12404 
12405 /**
12406  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
12407  * @phba: Pointer to HBA context object.
12408  * @cq: Pointer to completion queue.
12409  * @wcqe: Pointer to work-queue completion queue entry.
12410  *
12411  * This routine handles an fast-path WQ entry comsumed event by invoking the
12412  * proper WQ release routine to the slow-path WQ.
12413  **/
12414 static void
12415 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12416 			     struct lpfc_wcqe_release *wcqe)
12417 {
12418 	struct lpfc_queue *childwq;
12419 	bool wqid_matched = false;
12420 	uint16_t fcp_wqid;
12421 
12422 	/* Check for fast-path FCP work queue release */
12423 	fcp_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
12424 	list_for_each_entry(childwq, &cq->child_list, list) {
12425 		if (childwq->queue_id == fcp_wqid) {
12426 			lpfc_sli4_wq_release(childwq,
12427 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
12428 			wqid_matched = true;
12429 			break;
12430 		}
12431 	}
12432 	/* Report warning log message if no match found */
12433 	if (wqid_matched != true)
12434 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12435 				"2580 Fast-path wqe consume event carries "
12436 				"miss-matched qid: wcqe-qid=x%x\n", fcp_wqid);
12437 }
12438 
12439 /**
12440  * lpfc_sli4_fp_handle_wcqe - Process fast-path work queue completion entry
12441  * @cq: Pointer to the completion queue.
12442  * @eqe: Pointer to fast-path completion queue entry.
12443  *
12444  * This routine process a fast-path work queue completion entry from fast-path
12445  * event queue for FCP command response completion.
12446  **/
12447 static int
12448 lpfc_sli4_fp_handle_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12449 			 struct lpfc_cqe *cqe)
12450 {
12451 	struct lpfc_wcqe_release wcqe;
12452 	bool workposted = false;
12453 
12454 	/* Copy the work queue CQE and convert endian order if needed */
12455 	lpfc_sli_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
12456 
12457 	/* Check and process for different type of WCQE and dispatch */
12458 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
12459 	case CQE_CODE_COMPL_WQE:
12460 		cq->CQ_wq++;
12461 		/* Process the WQ complete event */
12462 		phba->last_completion_time = jiffies;
12463 		lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
12464 				(struct lpfc_wcqe_complete *)&wcqe);
12465 		break;
12466 	case CQE_CODE_RELEASE_WQE:
12467 		cq->CQ_release_wqe++;
12468 		/* Process the WQ release event */
12469 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
12470 				(struct lpfc_wcqe_release *)&wcqe);
12471 		break;
12472 	case CQE_CODE_XRI_ABORTED:
12473 		cq->CQ_xri_aborted++;
12474 		/* Process the WQ XRI abort event */
12475 		phba->last_completion_time = jiffies;
12476 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
12477 				(struct sli4_wcqe_xri_aborted *)&wcqe);
12478 		break;
12479 	default:
12480 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12481 				"0144 Not a valid WCQE code: x%x\n",
12482 				bf_get(lpfc_wcqe_c_code, &wcqe));
12483 		break;
12484 	}
12485 	return workposted;
12486 }
12487 
12488 /**
12489  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
12490  * @phba: Pointer to HBA context object.
12491  * @eqe: Pointer to fast-path event queue entry.
12492  *
12493  * This routine process a event queue entry from the fast-path event queue.
12494  * It will check the MajorCode and MinorCode to determine this is for a
12495  * completion event on a completion queue, if not, an error shall be logged
12496  * and just return. Otherwise, it will get to the corresponding completion
12497  * queue and process all the entries on the completion queue, rearm the
12498  * completion queue, and then return.
12499  **/
12500 static void
12501 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
12502 			uint32_t qidx)
12503 {
12504 	struct lpfc_queue *cq;
12505 	struct lpfc_cqe *cqe;
12506 	bool workposted = false;
12507 	uint16_t cqid;
12508 	int ecount = 0;
12509 
12510 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
12511 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12512 				"0366 Not a valid completion "
12513 				"event: majorcode=x%x, minorcode=x%x\n",
12514 				bf_get_le32(lpfc_eqe_major_code, eqe),
12515 				bf_get_le32(lpfc_eqe_minor_code, eqe));
12516 		return;
12517 	}
12518 
12519 	/* Get the reference to the corresponding CQ */
12520 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
12521 
12522 	/* Check if this is a Slow path event */
12523 	if (unlikely(cqid != phba->sli4_hba.fcp_cq_map[qidx])) {
12524 		lpfc_sli4_sp_handle_eqe(phba, eqe,
12525 			phba->sli4_hba.hba_eq[qidx]);
12526 		return;
12527 	}
12528 
12529 	if (unlikely(!phba->sli4_hba.fcp_cq)) {
12530 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12531 				"3146 Fast-path completion queues "
12532 				"does not exist\n");
12533 		return;
12534 	}
12535 	cq = phba->sli4_hba.fcp_cq[qidx];
12536 	if (unlikely(!cq)) {
12537 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
12538 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12539 					"0367 Fast-path completion queue "
12540 					"(%d) does not exist\n", qidx);
12541 		return;
12542 	}
12543 
12544 	if (unlikely(cqid != cq->queue_id)) {
12545 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12546 				"0368 Miss-matched fast-path completion "
12547 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
12548 				cqid, cq->queue_id);
12549 		return;
12550 	}
12551 
12552 	/* Process all the entries to the CQ */
12553 	while ((cqe = lpfc_sli4_cq_get(cq))) {
12554 		workposted |= lpfc_sli4_fp_handle_wcqe(phba, cq, cqe);
12555 		if (!(++ecount % cq->entry_repost))
12556 			lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12557 	}
12558 
12559 	/* Track the max number of CQEs processed in 1 EQ */
12560 	if (ecount > cq->CQ_max_cqe)
12561 		cq->CQ_max_cqe = ecount;
12562 
12563 	/* Catch the no cq entry condition */
12564 	if (unlikely(ecount == 0))
12565 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12566 				"0369 No entry from fast-path completion "
12567 				"queue fcpcqid=%d\n", cq->queue_id);
12568 
12569 	/* In any case, flash and re-arm the CQ */
12570 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
12571 
12572 	/* wake up worker thread if there are works to be done */
12573 	if (workposted)
12574 		lpfc_worker_wake_up(phba);
12575 }
12576 
12577 static void
12578 lpfc_sli4_eq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
12579 {
12580 	struct lpfc_eqe *eqe;
12581 
12582 	/* walk all the EQ entries and drop on the floor */
12583 	while ((eqe = lpfc_sli4_eq_get(eq)))
12584 		;
12585 
12586 	/* Clear and re-arm the EQ */
12587 	lpfc_sli4_eq_release(eq, LPFC_QUEUE_REARM);
12588 }
12589 
12590 
12591 /**
12592  * lpfc_sli4_fof_handle_eqe - Process a Flash Optimized Fabric event queue
12593  *			     entry
12594  * @phba: Pointer to HBA context object.
12595  * @eqe: Pointer to fast-path event queue entry.
12596  *
12597  * This routine process a event queue entry from the Flash Optimized Fabric
12598  * event queue.  It will check the MajorCode and MinorCode to determine this
12599  * is for a completion event on a completion queue, if not, an error shall be
12600  * logged and just return. Otherwise, it will get to the corresponding
12601  * completion queue and process all the entries on the completion queue, rearm
12602  * the completion queue, and then return.
12603  **/
12604 static void
12605 lpfc_sli4_fof_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe)
12606 {
12607 	struct lpfc_queue *cq;
12608 	struct lpfc_cqe *cqe;
12609 	bool workposted = false;
12610 	uint16_t cqid;
12611 	int ecount = 0;
12612 
12613 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
12614 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12615 				"9147 Not a valid completion "
12616 				"event: majorcode=x%x, minorcode=x%x\n",
12617 				bf_get_le32(lpfc_eqe_major_code, eqe),
12618 				bf_get_le32(lpfc_eqe_minor_code, eqe));
12619 		return;
12620 	}
12621 
12622 	/* Get the reference to the corresponding CQ */
12623 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
12624 
12625 	/* Next check for OAS */
12626 	cq = phba->sli4_hba.oas_cq;
12627 	if (unlikely(!cq)) {
12628 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
12629 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12630 					"9148 OAS completion queue "
12631 					"does not exist\n");
12632 		return;
12633 	}
12634 
12635 	if (unlikely(cqid != cq->queue_id)) {
12636 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12637 				"9149 Miss-matched fast-path compl "
12638 				"queue id: eqcqid=%d, fcpcqid=%d\n",
12639 				cqid, cq->queue_id);
12640 		return;
12641 	}
12642 
12643 	/* Process all the entries to the OAS CQ */
12644 	while ((cqe = lpfc_sli4_cq_get(cq))) {
12645 		workposted |= lpfc_sli4_fp_handle_wcqe(phba, cq, cqe);
12646 		if (!(++ecount % cq->entry_repost))
12647 			lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12648 	}
12649 
12650 	/* Track the max number of CQEs processed in 1 EQ */
12651 	if (ecount > cq->CQ_max_cqe)
12652 		cq->CQ_max_cqe = ecount;
12653 
12654 	/* Catch the no cq entry condition */
12655 	if (unlikely(ecount == 0))
12656 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12657 				"9153 No entry from fast-path completion "
12658 				"queue fcpcqid=%d\n", cq->queue_id);
12659 
12660 	/* In any case, flash and re-arm the CQ */
12661 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
12662 
12663 	/* wake up worker thread if there are works to be done */
12664 	if (workposted)
12665 		lpfc_worker_wake_up(phba);
12666 }
12667 
12668 /**
12669  * lpfc_sli4_fof_intr_handler - HBA interrupt handler to SLI-4 device
12670  * @irq: Interrupt number.
12671  * @dev_id: The device context pointer.
12672  *
12673  * This function is directly called from the PCI layer as an interrupt
12674  * service routine when device with SLI-4 interface spec is enabled with
12675  * MSI-X multi-message interrupt mode and there is a Flash Optimized Fabric
12676  * IOCB ring event in the HBA. However, when the device is enabled with either
12677  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
12678  * device-level interrupt handler. When the PCI slot is in error recovery
12679  * or the HBA is undergoing initialization, the interrupt handler will not
12680  * process the interrupt. The Flash Optimized Fabric ring event are handled in
12681  * the intrrupt context. This function is called without any lock held.
12682  * It gets the hbalock to access and update SLI data structures. Note that,
12683  * the EQ to CQ are one-to-one map such that the EQ index is
12684  * equal to that of CQ index.
12685  *
12686  * This function returns IRQ_HANDLED when interrupt is handled else it
12687  * returns IRQ_NONE.
12688  **/
12689 irqreturn_t
12690 lpfc_sli4_fof_intr_handler(int irq, void *dev_id)
12691 {
12692 	struct lpfc_hba *phba;
12693 	struct lpfc_fcp_eq_hdl *fcp_eq_hdl;
12694 	struct lpfc_queue *eq;
12695 	struct lpfc_eqe *eqe;
12696 	unsigned long iflag;
12697 	int ecount = 0;
12698 
12699 	/* Get the driver's phba structure from the dev_id */
12700 	fcp_eq_hdl = (struct lpfc_fcp_eq_hdl *)dev_id;
12701 	phba = fcp_eq_hdl->phba;
12702 
12703 	if (unlikely(!phba))
12704 		return IRQ_NONE;
12705 
12706 	/* Get to the EQ struct associated with this vector */
12707 	eq = phba->sli4_hba.fof_eq;
12708 	if (unlikely(!eq))
12709 		return IRQ_NONE;
12710 
12711 	/* Check device state for handling interrupt */
12712 	if (unlikely(lpfc_intr_state_check(phba))) {
12713 		eq->EQ_badstate++;
12714 		/* Check again for link_state with lock held */
12715 		spin_lock_irqsave(&phba->hbalock, iflag);
12716 		if (phba->link_state < LPFC_LINK_DOWN)
12717 			/* Flush, clear interrupt, and rearm the EQ */
12718 			lpfc_sli4_eq_flush(phba, eq);
12719 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12720 		return IRQ_NONE;
12721 	}
12722 
12723 	/*
12724 	 * Process all the event on FCP fast-path EQ
12725 	 */
12726 	while ((eqe = lpfc_sli4_eq_get(eq))) {
12727 		lpfc_sli4_fof_handle_eqe(phba, eqe);
12728 		if (!(++ecount % eq->entry_repost))
12729 			lpfc_sli4_eq_release(eq, LPFC_QUEUE_NOARM);
12730 		eq->EQ_processed++;
12731 	}
12732 
12733 	/* Track the max number of EQEs processed in 1 intr */
12734 	if (ecount > eq->EQ_max_eqe)
12735 		eq->EQ_max_eqe = ecount;
12736 
12737 
12738 	if (unlikely(ecount == 0)) {
12739 		eq->EQ_no_entry++;
12740 
12741 		if (phba->intr_type == MSIX)
12742 			/* MSI-X treated interrupt served as no EQ share INT */
12743 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12744 					"9145 MSI-X interrupt with no EQE\n");
12745 		else {
12746 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12747 					"9146 ISR interrupt with no EQE\n");
12748 			/* Non MSI-X treated on interrupt as EQ share INT */
12749 			return IRQ_NONE;
12750 		}
12751 	}
12752 	/* Always clear and re-arm the fast-path EQ */
12753 	lpfc_sli4_eq_release(eq, LPFC_QUEUE_REARM);
12754 	return IRQ_HANDLED;
12755 }
12756 
12757 /**
12758  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
12759  * @irq: Interrupt number.
12760  * @dev_id: The device context pointer.
12761  *
12762  * This function is directly called from the PCI layer as an interrupt
12763  * service routine when device with SLI-4 interface spec is enabled with
12764  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
12765  * ring event in the HBA. However, when the device is enabled with either
12766  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
12767  * device-level interrupt handler. When the PCI slot is in error recovery
12768  * or the HBA is undergoing initialization, the interrupt handler will not
12769  * process the interrupt. The SCSI FCP fast-path ring event are handled in
12770  * the intrrupt context. This function is called without any lock held.
12771  * It gets the hbalock to access and update SLI data structures. Note that,
12772  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
12773  * equal to that of FCP CQ index.
12774  *
12775  * The link attention and ELS ring attention events are handled
12776  * by the worker thread. The interrupt handler signals the worker thread
12777  * and returns for these events. This function is called without any lock
12778  * held. It gets the hbalock to access and update SLI data structures.
12779  *
12780  * This function returns IRQ_HANDLED when interrupt is handled else it
12781  * returns IRQ_NONE.
12782  **/
12783 irqreturn_t
12784 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
12785 {
12786 	struct lpfc_hba *phba;
12787 	struct lpfc_fcp_eq_hdl *fcp_eq_hdl;
12788 	struct lpfc_queue *fpeq;
12789 	struct lpfc_eqe *eqe;
12790 	unsigned long iflag;
12791 	int ecount = 0;
12792 	int fcp_eqidx;
12793 
12794 	/* Get the driver's phba structure from the dev_id */
12795 	fcp_eq_hdl = (struct lpfc_fcp_eq_hdl *)dev_id;
12796 	phba = fcp_eq_hdl->phba;
12797 	fcp_eqidx = fcp_eq_hdl->idx;
12798 
12799 	if (unlikely(!phba))
12800 		return IRQ_NONE;
12801 	if (unlikely(!phba->sli4_hba.hba_eq))
12802 		return IRQ_NONE;
12803 
12804 	/* Get to the EQ struct associated with this vector */
12805 	fpeq = phba->sli4_hba.hba_eq[fcp_eqidx];
12806 	if (unlikely(!fpeq))
12807 		return IRQ_NONE;
12808 
12809 	if (lpfc_fcp_look_ahead) {
12810 		if (atomic_dec_and_test(&fcp_eq_hdl->fcp_eq_in_use))
12811 			lpfc_sli4_eq_clr_intr(fpeq);
12812 		else {
12813 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12814 			return IRQ_NONE;
12815 		}
12816 	}
12817 
12818 	/* Check device state for handling interrupt */
12819 	if (unlikely(lpfc_intr_state_check(phba))) {
12820 		fpeq->EQ_badstate++;
12821 		/* Check again for link_state with lock held */
12822 		spin_lock_irqsave(&phba->hbalock, iflag);
12823 		if (phba->link_state < LPFC_LINK_DOWN)
12824 			/* Flush, clear interrupt, and rearm the EQ */
12825 			lpfc_sli4_eq_flush(phba, fpeq);
12826 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12827 		if (lpfc_fcp_look_ahead)
12828 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12829 		return IRQ_NONE;
12830 	}
12831 
12832 	/*
12833 	 * Process all the event on FCP fast-path EQ
12834 	 */
12835 	while ((eqe = lpfc_sli4_eq_get(fpeq))) {
12836 		if (eqe == NULL)
12837 			break;
12838 
12839 		lpfc_sli4_hba_handle_eqe(phba, eqe, fcp_eqidx);
12840 		if (!(++ecount % fpeq->entry_repost))
12841 			lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_NOARM);
12842 		fpeq->EQ_processed++;
12843 	}
12844 
12845 	/* Track the max number of EQEs processed in 1 intr */
12846 	if (ecount > fpeq->EQ_max_eqe)
12847 		fpeq->EQ_max_eqe = ecount;
12848 
12849 	/* Always clear and re-arm the fast-path EQ */
12850 	lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_REARM);
12851 
12852 	if (unlikely(ecount == 0)) {
12853 		fpeq->EQ_no_entry++;
12854 
12855 		if (lpfc_fcp_look_ahead) {
12856 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12857 			return IRQ_NONE;
12858 		}
12859 
12860 		if (phba->intr_type == MSIX)
12861 			/* MSI-X treated interrupt served as no EQ share INT */
12862 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12863 					"0358 MSI-X interrupt with no EQE\n");
12864 		else
12865 			/* Non MSI-X treated on interrupt as EQ share INT */
12866 			return IRQ_NONE;
12867 	}
12868 
12869 	if (lpfc_fcp_look_ahead)
12870 		atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12871 	return IRQ_HANDLED;
12872 } /* lpfc_sli4_fp_intr_handler */
12873 
12874 /**
12875  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
12876  * @irq: Interrupt number.
12877  * @dev_id: The device context pointer.
12878  *
12879  * This function is the device-level interrupt handler to device with SLI-4
12880  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
12881  * interrupt mode is enabled and there is an event in the HBA which requires
12882  * driver attention. This function invokes the slow-path interrupt attention
12883  * handling function and fast-path interrupt attention handling function in
12884  * turn to process the relevant HBA attention events. This function is called
12885  * without any lock held. It gets the hbalock to access and update SLI data
12886  * structures.
12887  *
12888  * This function returns IRQ_HANDLED when interrupt is handled, else it
12889  * returns IRQ_NONE.
12890  **/
12891 irqreturn_t
12892 lpfc_sli4_intr_handler(int irq, void *dev_id)
12893 {
12894 	struct lpfc_hba  *phba;
12895 	irqreturn_t hba_irq_rc;
12896 	bool hba_handled = false;
12897 	int fcp_eqidx;
12898 
12899 	/* Get the driver's phba structure from the dev_id */
12900 	phba = (struct lpfc_hba *)dev_id;
12901 
12902 	if (unlikely(!phba))
12903 		return IRQ_NONE;
12904 
12905 	/*
12906 	 * Invoke fast-path host attention interrupt handling as appropriate.
12907 	 */
12908 	for (fcp_eqidx = 0; fcp_eqidx < phba->cfg_fcp_io_channel; fcp_eqidx++) {
12909 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
12910 					&phba->sli4_hba.fcp_eq_hdl[fcp_eqidx]);
12911 		if (hba_irq_rc == IRQ_HANDLED)
12912 			hba_handled |= true;
12913 	}
12914 
12915 	if (phba->cfg_fof) {
12916 		hba_irq_rc = lpfc_sli4_fof_intr_handler(irq,
12917 					&phba->sli4_hba.fcp_eq_hdl[0]);
12918 		if (hba_irq_rc == IRQ_HANDLED)
12919 			hba_handled |= true;
12920 	}
12921 
12922 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
12923 } /* lpfc_sli4_intr_handler */
12924 
12925 /**
12926  * lpfc_sli4_queue_free - free a queue structure and associated memory
12927  * @queue: The queue structure to free.
12928  *
12929  * This function frees a queue structure and the DMAable memory used for
12930  * the host resident queue. This function must be called after destroying the
12931  * queue on the HBA.
12932  **/
12933 void
12934 lpfc_sli4_queue_free(struct lpfc_queue *queue)
12935 {
12936 	struct lpfc_dmabuf *dmabuf;
12937 
12938 	if (!queue)
12939 		return;
12940 
12941 	while (!list_empty(&queue->page_list)) {
12942 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
12943 				 list);
12944 		dma_free_coherent(&queue->phba->pcidev->dev, SLI4_PAGE_SIZE,
12945 				  dmabuf->virt, dmabuf->phys);
12946 		kfree(dmabuf);
12947 	}
12948 	kfree(queue);
12949 	return;
12950 }
12951 
12952 /**
12953  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
12954  * @phba: The HBA that this queue is being created on.
12955  * @entry_size: The size of each queue entry for this queue.
12956  * @entry count: The number of entries that this queue will handle.
12957  *
12958  * This function allocates a queue structure and the DMAable memory used for
12959  * the host resident queue. This function must be called before creating the
12960  * queue on the HBA.
12961  **/
12962 struct lpfc_queue *
12963 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t entry_size,
12964 		      uint32_t entry_count)
12965 {
12966 	struct lpfc_queue *queue;
12967 	struct lpfc_dmabuf *dmabuf;
12968 	int x, total_qe_count;
12969 	void *dma_pointer;
12970 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
12971 
12972 	if (!phba->sli4_hba.pc_sli4_params.supported)
12973 		hw_page_size = SLI4_PAGE_SIZE;
12974 
12975 	queue = kzalloc(sizeof(struct lpfc_queue) +
12976 			(sizeof(union sli4_qe) * entry_count), GFP_KERNEL);
12977 	if (!queue)
12978 		return NULL;
12979 	queue->page_count = (ALIGN(entry_size * entry_count,
12980 			hw_page_size))/hw_page_size;
12981 	INIT_LIST_HEAD(&queue->list);
12982 	INIT_LIST_HEAD(&queue->page_list);
12983 	INIT_LIST_HEAD(&queue->child_list);
12984 	for (x = 0, total_qe_count = 0; x < queue->page_count; x++) {
12985 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
12986 		if (!dmabuf)
12987 			goto out_fail;
12988 		dmabuf->virt = dma_zalloc_coherent(&phba->pcidev->dev,
12989 						   hw_page_size, &dmabuf->phys,
12990 						   GFP_KERNEL);
12991 		if (!dmabuf->virt) {
12992 			kfree(dmabuf);
12993 			goto out_fail;
12994 		}
12995 		dmabuf->buffer_tag = x;
12996 		list_add_tail(&dmabuf->list, &queue->page_list);
12997 		/* initialize queue's entry array */
12998 		dma_pointer = dmabuf->virt;
12999 		for (; total_qe_count < entry_count &&
13000 		     dma_pointer < (hw_page_size + dmabuf->virt);
13001 		     total_qe_count++, dma_pointer += entry_size) {
13002 			queue->qe[total_qe_count].address = dma_pointer;
13003 		}
13004 	}
13005 	queue->entry_size = entry_size;
13006 	queue->entry_count = entry_count;
13007 
13008 	/*
13009 	 * entry_repost is calculated based on the number of entries in the
13010 	 * queue. This works out except for RQs. If buffers are NOT initially
13011 	 * posted for every RQE, entry_repost should be adjusted accordingly.
13012 	 */
13013 	queue->entry_repost = (entry_count >> 3);
13014 	if (queue->entry_repost < LPFC_QUEUE_MIN_REPOST)
13015 		queue->entry_repost = LPFC_QUEUE_MIN_REPOST;
13016 	queue->phba = phba;
13017 
13018 	return queue;
13019 out_fail:
13020 	lpfc_sli4_queue_free(queue);
13021 	return NULL;
13022 }
13023 
13024 /**
13025  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
13026  * @phba: HBA structure that indicates port to create a queue on.
13027  * @pci_barset: PCI BAR set flag.
13028  *
13029  * This function shall perform iomap of the specified PCI BAR address to host
13030  * memory address if not already done so and return it. The returned host
13031  * memory address can be NULL.
13032  */
13033 static void __iomem *
13034 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
13035 {
13036 	if (!phba->pcidev)
13037 		return NULL;
13038 
13039 	switch (pci_barset) {
13040 	case WQ_PCI_BAR_0_AND_1:
13041 		return phba->pci_bar0_memmap_p;
13042 	case WQ_PCI_BAR_2_AND_3:
13043 		return phba->pci_bar2_memmap_p;
13044 	case WQ_PCI_BAR_4_AND_5:
13045 		return phba->pci_bar4_memmap_p;
13046 	default:
13047 		break;
13048 	}
13049 	return NULL;
13050 }
13051 
13052 /**
13053  * lpfc_modify_fcp_eq_delay - Modify Delay Multiplier on FCP EQs
13054  * @phba: HBA structure that indicates port to create a queue on.
13055  * @startq: The starting FCP EQ to modify
13056  *
13057  * This function sends an MODIFY_EQ_DELAY mailbox command to the HBA.
13058  *
13059  * The @phba struct is used to send mailbox command to HBA. The @startq
13060  * is used to get the starting FCP EQ to change.
13061  * This function is asynchronous and will wait for the mailbox
13062  * command to finish before continuing.
13063  *
13064  * On success this function will return a zero. If unable to allocate enough
13065  * memory this function will return -ENOMEM. If the queue create mailbox command
13066  * fails this function will return -ENXIO.
13067  **/
13068 int
13069 lpfc_modify_fcp_eq_delay(struct lpfc_hba *phba, uint32_t startq)
13070 {
13071 	struct lpfc_mbx_modify_eq_delay *eq_delay;
13072 	LPFC_MBOXQ_t *mbox;
13073 	struct lpfc_queue *eq;
13074 	int cnt, rc, length, status = 0;
13075 	uint32_t shdr_status, shdr_add_status;
13076 	uint32_t result;
13077 	int fcp_eqidx;
13078 	union lpfc_sli4_cfg_shdr *shdr;
13079 	uint16_t dmult;
13080 
13081 	if (startq >= phba->cfg_fcp_io_channel)
13082 		return 0;
13083 
13084 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13085 	if (!mbox)
13086 		return -ENOMEM;
13087 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
13088 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13089 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13090 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
13091 			 length, LPFC_SLI4_MBX_EMBED);
13092 	eq_delay = &mbox->u.mqe.un.eq_delay;
13093 
13094 	/* Calculate delay multiper from maximum interrupt per second */
13095 	result = phba->cfg_fcp_imax / phba->cfg_fcp_io_channel;
13096 	if (result > LPFC_DMULT_CONST)
13097 		dmult = 0;
13098 	else
13099 		dmult = LPFC_DMULT_CONST/result - 1;
13100 
13101 	cnt = 0;
13102 	for (fcp_eqidx = startq; fcp_eqidx < phba->cfg_fcp_io_channel;
13103 	    fcp_eqidx++) {
13104 		eq = phba->sli4_hba.hba_eq[fcp_eqidx];
13105 		if (!eq)
13106 			continue;
13107 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
13108 		eq_delay->u.request.eq[cnt].phase = 0;
13109 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
13110 		cnt++;
13111 		if (cnt >= LPFC_MAX_EQ_DELAY)
13112 			break;
13113 	}
13114 	eq_delay->u.request.num_eq = cnt;
13115 
13116 	mbox->vport = phba->pport;
13117 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13118 	mbox->context1 = NULL;
13119 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13120 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
13121 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13122 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13123 	if (shdr_status || shdr_add_status || rc) {
13124 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13125 				"2512 MODIFY_EQ_DELAY mailbox failed with "
13126 				"status x%x add_status x%x, mbx status x%x\n",
13127 				shdr_status, shdr_add_status, rc);
13128 		status = -ENXIO;
13129 	}
13130 	mempool_free(mbox, phba->mbox_mem_pool);
13131 	return status;
13132 }
13133 
13134 /**
13135  * lpfc_eq_create - Create an Event Queue on the HBA
13136  * @phba: HBA structure that indicates port to create a queue on.
13137  * @eq: The queue structure to use to create the event queue.
13138  * @imax: The maximum interrupt per second limit.
13139  *
13140  * This function creates an event queue, as detailed in @eq, on a port,
13141  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
13142  *
13143  * The @phba struct is used to send mailbox command to HBA. The @eq struct
13144  * is used to get the entry count and entry size that are necessary to
13145  * determine the number of pages to allocate and use for this queue. This
13146  * function will send the EQ_CREATE mailbox command to the HBA to setup the
13147  * event queue. This function is asynchronous and will wait for the mailbox
13148  * command to finish before continuing.
13149  *
13150  * On success this function will return a zero. If unable to allocate enough
13151  * memory this function will return -ENOMEM. If the queue create mailbox command
13152  * fails this function will return -ENXIO.
13153  **/
13154 int
13155 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
13156 {
13157 	struct lpfc_mbx_eq_create *eq_create;
13158 	LPFC_MBOXQ_t *mbox;
13159 	int rc, length, status = 0;
13160 	struct lpfc_dmabuf *dmabuf;
13161 	uint32_t shdr_status, shdr_add_status;
13162 	union lpfc_sli4_cfg_shdr *shdr;
13163 	uint16_t dmult;
13164 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13165 
13166 	/* sanity check on queue memory */
13167 	if (!eq)
13168 		return -ENODEV;
13169 	if (!phba->sli4_hba.pc_sli4_params.supported)
13170 		hw_page_size = SLI4_PAGE_SIZE;
13171 
13172 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13173 	if (!mbox)
13174 		return -ENOMEM;
13175 	length = (sizeof(struct lpfc_mbx_eq_create) -
13176 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13177 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13178 			 LPFC_MBOX_OPCODE_EQ_CREATE,
13179 			 length, LPFC_SLI4_MBX_EMBED);
13180 	eq_create = &mbox->u.mqe.un.eq_create;
13181 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
13182 	       eq->page_count);
13183 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
13184 	       LPFC_EQE_SIZE);
13185 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
13186 	/* don't setup delay multiplier using EQ_CREATE */
13187 	dmult = 0;
13188 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
13189 	       dmult);
13190 	switch (eq->entry_count) {
13191 	default:
13192 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13193 				"0360 Unsupported EQ count. (%d)\n",
13194 				eq->entry_count);
13195 		if (eq->entry_count < 256)
13196 			return -EINVAL;
13197 		/* otherwise default to smallest count (drop through) */
13198 	case 256:
13199 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13200 		       LPFC_EQ_CNT_256);
13201 		break;
13202 	case 512:
13203 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13204 		       LPFC_EQ_CNT_512);
13205 		break;
13206 	case 1024:
13207 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13208 		       LPFC_EQ_CNT_1024);
13209 		break;
13210 	case 2048:
13211 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13212 		       LPFC_EQ_CNT_2048);
13213 		break;
13214 	case 4096:
13215 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13216 		       LPFC_EQ_CNT_4096);
13217 		break;
13218 	}
13219 	list_for_each_entry(dmabuf, &eq->page_list, list) {
13220 		memset(dmabuf->virt, 0, hw_page_size);
13221 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13222 					putPaddrLow(dmabuf->phys);
13223 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13224 					putPaddrHigh(dmabuf->phys);
13225 	}
13226 	mbox->vport = phba->pport;
13227 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13228 	mbox->context1 = NULL;
13229 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13230 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
13231 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13232 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13233 	if (shdr_status || shdr_add_status || rc) {
13234 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13235 				"2500 EQ_CREATE mailbox failed with "
13236 				"status x%x add_status x%x, mbx status x%x\n",
13237 				shdr_status, shdr_add_status, rc);
13238 		status = -ENXIO;
13239 	}
13240 	eq->type = LPFC_EQ;
13241 	eq->subtype = LPFC_NONE;
13242 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
13243 	if (eq->queue_id == 0xFFFF)
13244 		status = -ENXIO;
13245 	eq->host_index = 0;
13246 	eq->hba_index = 0;
13247 
13248 	mempool_free(mbox, phba->mbox_mem_pool);
13249 	return status;
13250 }
13251 
13252 /**
13253  * lpfc_cq_create - Create a Completion Queue on the HBA
13254  * @phba: HBA structure that indicates port to create a queue on.
13255  * @cq: The queue structure to use to create the completion queue.
13256  * @eq: The event queue to bind this completion queue to.
13257  *
13258  * This function creates a completion queue, as detailed in @wq, on a port,
13259  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
13260  *
13261  * The @phba struct is used to send mailbox command to HBA. The @cq struct
13262  * is used to get the entry count and entry size that are necessary to
13263  * determine the number of pages to allocate and use for this queue. The @eq
13264  * is used to indicate which event queue to bind this completion queue to. This
13265  * function will send the CQ_CREATE mailbox command to the HBA to setup the
13266  * completion queue. This function is asynchronous and will wait for the mailbox
13267  * command to finish before continuing.
13268  *
13269  * On success this function will return a zero. If unable to allocate enough
13270  * memory this function will return -ENOMEM. If the queue create mailbox command
13271  * fails this function will return -ENXIO.
13272  **/
13273 int
13274 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
13275 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
13276 {
13277 	struct lpfc_mbx_cq_create *cq_create;
13278 	struct lpfc_dmabuf *dmabuf;
13279 	LPFC_MBOXQ_t *mbox;
13280 	int rc, length, status = 0;
13281 	uint32_t shdr_status, shdr_add_status;
13282 	union lpfc_sli4_cfg_shdr *shdr;
13283 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13284 
13285 	/* sanity check on queue memory */
13286 	if (!cq || !eq)
13287 		return -ENODEV;
13288 	if (!phba->sli4_hba.pc_sli4_params.supported)
13289 		hw_page_size = SLI4_PAGE_SIZE;
13290 
13291 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13292 	if (!mbox)
13293 		return -ENOMEM;
13294 	length = (sizeof(struct lpfc_mbx_cq_create) -
13295 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13296 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13297 			 LPFC_MBOX_OPCODE_CQ_CREATE,
13298 			 length, LPFC_SLI4_MBX_EMBED);
13299 	cq_create = &mbox->u.mqe.un.cq_create;
13300 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
13301 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
13302 		    cq->page_count);
13303 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
13304 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
13305 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13306 	       phba->sli4_hba.pc_sli4_params.cqv);
13307 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
13308 		/* FW only supports 1. Should be PAGE_SIZE/SLI4_PAGE_SIZE */
13309 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request, 1);
13310 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
13311 		       eq->queue_id);
13312 	} else {
13313 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
13314 		       eq->queue_id);
13315 	}
13316 	switch (cq->entry_count) {
13317 	default:
13318 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13319 				"0361 Unsupported CQ count. (%d)\n",
13320 				cq->entry_count);
13321 		if (cq->entry_count < 256) {
13322 			status = -EINVAL;
13323 			goto out;
13324 		}
13325 		/* otherwise default to smallest count (drop through) */
13326 	case 256:
13327 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
13328 		       LPFC_CQ_CNT_256);
13329 		break;
13330 	case 512:
13331 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
13332 		       LPFC_CQ_CNT_512);
13333 		break;
13334 	case 1024:
13335 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
13336 		       LPFC_CQ_CNT_1024);
13337 		break;
13338 	}
13339 	list_for_each_entry(dmabuf, &cq->page_list, list) {
13340 		memset(dmabuf->virt, 0, hw_page_size);
13341 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13342 					putPaddrLow(dmabuf->phys);
13343 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13344 					putPaddrHigh(dmabuf->phys);
13345 	}
13346 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13347 
13348 	/* The IOCTL status is embedded in the mailbox subheader. */
13349 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13350 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13351 	if (shdr_status || shdr_add_status || rc) {
13352 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13353 				"2501 CQ_CREATE mailbox failed with "
13354 				"status x%x add_status x%x, mbx status x%x\n",
13355 				shdr_status, shdr_add_status, rc);
13356 		status = -ENXIO;
13357 		goto out;
13358 	}
13359 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
13360 	if (cq->queue_id == 0xFFFF) {
13361 		status = -ENXIO;
13362 		goto out;
13363 	}
13364 	/* link the cq onto the parent eq child list */
13365 	list_add_tail(&cq->list, &eq->child_list);
13366 	/* Set up completion queue's type and subtype */
13367 	cq->type = type;
13368 	cq->subtype = subtype;
13369 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
13370 	cq->assoc_qid = eq->queue_id;
13371 	cq->host_index = 0;
13372 	cq->hba_index = 0;
13373 
13374 out:
13375 	mempool_free(mbox, phba->mbox_mem_pool);
13376 	return status;
13377 }
13378 
13379 /**
13380  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
13381  * @phba: HBA structure that indicates port to create a queue on.
13382  * @mq: The queue structure to use to create the mailbox queue.
13383  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
13384  * @cq: The completion queue to associate with this cq.
13385  *
13386  * This function provides failback (fb) functionality when the
13387  * mq_create_ext fails on older FW generations.  It's purpose is identical
13388  * to mq_create_ext otherwise.
13389  *
13390  * This routine cannot fail as all attributes were previously accessed and
13391  * initialized in mq_create_ext.
13392  **/
13393 static void
13394 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
13395 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
13396 {
13397 	struct lpfc_mbx_mq_create *mq_create;
13398 	struct lpfc_dmabuf *dmabuf;
13399 	int length;
13400 
13401 	length = (sizeof(struct lpfc_mbx_mq_create) -
13402 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13403 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13404 			 LPFC_MBOX_OPCODE_MQ_CREATE,
13405 			 length, LPFC_SLI4_MBX_EMBED);
13406 	mq_create = &mbox->u.mqe.un.mq_create;
13407 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
13408 	       mq->page_count);
13409 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
13410 	       cq->queue_id);
13411 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
13412 	switch (mq->entry_count) {
13413 	case 16:
13414 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13415 		       LPFC_MQ_RING_SIZE_16);
13416 		break;
13417 	case 32:
13418 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13419 		       LPFC_MQ_RING_SIZE_32);
13420 		break;
13421 	case 64:
13422 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13423 		       LPFC_MQ_RING_SIZE_64);
13424 		break;
13425 	case 128:
13426 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13427 		       LPFC_MQ_RING_SIZE_128);
13428 		break;
13429 	}
13430 	list_for_each_entry(dmabuf, &mq->page_list, list) {
13431 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13432 			putPaddrLow(dmabuf->phys);
13433 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13434 			putPaddrHigh(dmabuf->phys);
13435 	}
13436 }
13437 
13438 /**
13439  * lpfc_mq_create - Create a mailbox Queue on the HBA
13440  * @phba: HBA structure that indicates port to create a queue on.
13441  * @mq: The queue structure to use to create the mailbox queue.
13442  * @cq: The completion queue to associate with this cq.
13443  * @subtype: The queue's subtype.
13444  *
13445  * This function creates a mailbox queue, as detailed in @mq, on a port,
13446  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
13447  *
13448  * The @phba struct is used to send mailbox command to HBA. The @cq struct
13449  * is used to get the entry count and entry size that are necessary to
13450  * determine the number of pages to allocate and use for this queue. This
13451  * function will send the MQ_CREATE mailbox command to the HBA to setup the
13452  * mailbox queue. This function is asynchronous and will wait for the mailbox
13453  * command to finish before continuing.
13454  *
13455  * On success this function will return a zero. If unable to allocate enough
13456  * memory this function will return -ENOMEM. If the queue create mailbox command
13457  * fails this function will return -ENXIO.
13458  **/
13459 int32_t
13460 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
13461 	       struct lpfc_queue *cq, uint32_t subtype)
13462 {
13463 	struct lpfc_mbx_mq_create *mq_create;
13464 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
13465 	struct lpfc_dmabuf *dmabuf;
13466 	LPFC_MBOXQ_t *mbox;
13467 	int rc, length, status = 0;
13468 	uint32_t shdr_status, shdr_add_status;
13469 	union lpfc_sli4_cfg_shdr *shdr;
13470 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13471 
13472 	/* sanity check on queue memory */
13473 	if (!mq || !cq)
13474 		return -ENODEV;
13475 	if (!phba->sli4_hba.pc_sli4_params.supported)
13476 		hw_page_size = SLI4_PAGE_SIZE;
13477 
13478 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13479 	if (!mbox)
13480 		return -ENOMEM;
13481 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
13482 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13483 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13484 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
13485 			 length, LPFC_SLI4_MBX_EMBED);
13486 
13487 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
13488 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
13489 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
13490 	       &mq_create_ext->u.request, mq->page_count);
13491 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
13492 	       &mq_create_ext->u.request, 1);
13493 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
13494 	       &mq_create_ext->u.request, 1);
13495 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
13496 	       &mq_create_ext->u.request, 1);
13497 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
13498 	       &mq_create_ext->u.request, 1);
13499 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
13500 	       &mq_create_ext->u.request, 1);
13501 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
13502 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13503 	       phba->sli4_hba.pc_sli4_params.mqv);
13504 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
13505 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
13506 		       cq->queue_id);
13507 	else
13508 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
13509 		       cq->queue_id);
13510 	switch (mq->entry_count) {
13511 	default:
13512 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13513 				"0362 Unsupported MQ count. (%d)\n",
13514 				mq->entry_count);
13515 		if (mq->entry_count < 16) {
13516 			status = -EINVAL;
13517 			goto out;
13518 		}
13519 		/* otherwise default to smallest count (drop through) */
13520 	case 16:
13521 		bf_set(lpfc_mq_context_ring_size,
13522 		       &mq_create_ext->u.request.context,
13523 		       LPFC_MQ_RING_SIZE_16);
13524 		break;
13525 	case 32:
13526 		bf_set(lpfc_mq_context_ring_size,
13527 		       &mq_create_ext->u.request.context,
13528 		       LPFC_MQ_RING_SIZE_32);
13529 		break;
13530 	case 64:
13531 		bf_set(lpfc_mq_context_ring_size,
13532 		       &mq_create_ext->u.request.context,
13533 		       LPFC_MQ_RING_SIZE_64);
13534 		break;
13535 	case 128:
13536 		bf_set(lpfc_mq_context_ring_size,
13537 		       &mq_create_ext->u.request.context,
13538 		       LPFC_MQ_RING_SIZE_128);
13539 		break;
13540 	}
13541 	list_for_each_entry(dmabuf, &mq->page_list, list) {
13542 		memset(dmabuf->virt, 0, hw_page_size);
13543 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
13544 					putPaddrLow(dmabuf->phys);
13545 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
13546 					putPaddrHigh(dmabuf->phys);
13547 	}
13548 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13549 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
13550 			      &mq_create_ext->u.response);
13551 	if (rc != MBX_SUCCESS) {
13552 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13553 				"2795 MQ_CREATE_EXT failed with "
13554 				"status x%x. Failback to MQ_CREATE.\n",
13555 				rc);
13556 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
13557 		mq_create = &mbox->u.mqe.un.mq_create;
13558 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13559 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
13560 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
13561 				      &mq_create->u.response);
13562 	}
13563 
13564 	/* The IOCTL status is embedded in the mailbox subheader. */
13565 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13566 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13567 	if (shdr_status || shdr_add_status || rc) {
13568 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13569 				"2502 MQ_CREATE mailbox failed with "
13570 				"status x%x add_status x%x, mbx status x%x\n",
13571 				shdr_status, shdr_add_status, rc);
13572 		status = -ENXIO;
13573 		goto out;
13574 	}
13575 	if (mq->queue_id == 0xFFFF) {
13576 		status = -ENXIO;
13577 		goto out;
13578 	}
13579 	mq->type = LPFC_MQ;
13580 	mq->assoc_qid = cq->queue_id;
13581 	mq->subtype = subtype;
13582 	mq->host_index = 0;
13583 	mq->hba_index = 0;
13584 
13585 	/* link the mq onto the parent cq child list */
13586 	list_add_tail(&mq->list, &cq->child_list);
13587 out:
13588 	mempool_free(mbox, phba->mbox_mem_pool);
13589 	return status;
13590 }
13591 
13592 /**
13593  * lpfc_wq_create - Create a Work Queue on the HBA
13594  * @phba: HBA structure that indicates port to create a queue on.
13595  * @wq: The queue structure to use to create the work queue.
13596  * @cq: The completion queue to bind this work queue to.
13597  * @subtype: The subtype of the work queue indicating its functionality.
13598  *
13599  * This function creates a work queue, as detailed in @wq, on a port, described
13600  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
13601  *
13602  * The @phba struct is used to send mailbox command to HBA. The @wq struct
13603  * is used to get the entry count and entry size that are necessary to
13604  * determine the number of pages to allocate and use for this queue. The @cq
13605  * is used to indicate which completion queue to bind this work queue to. This
13606  * function will send the WQ_CREATE mailbox command to the HBA to setup the
13607  * work queue. This function is asynchronous and will wait for the mailbox
13608  * command to finish before continuing.
13609  *
13610  * On success this function will return a zero. If unable to allocate enough
13611  * memory this function will return -ENOMEM. If the queue create mailbox command
13612  * fails this function will return -ENXIO.
13613  **/
13614 int
13615 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
13616 	       struct lpfc_queue *cq, uint32_t subtype)
13617 {
13618 	struct lpfc_mbx_wq_create *wq_create;
13619 	struct lpfc_dmabuf *dmabuf;
13620 	LPFC_MBOXQ_t *mbox;
13621 	int rc, length, status = 0;
13622 	uint32_t shdr_status, shdr_add_status;
13623 	union lpfc_sli4_cfg_shdr *shdr;
13624 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13625 	struct dma_address *page;
13626 	void __iomem *bar_memmap_p;
13627 	uint32_t db_offset;
13628 	uint16_t pci_barset;
13629 
13630 	/* sanity check on queue memory */
13631 	if (!wq || !cq)
13632 		return -ENODEV;
13633 	if (!phba->sli4_hba.pc_sli4_params.supported)
13634 		hw_page_size = SLI4_PAGE_SIZE;
13635 
13636 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13637 	if (!mbox)
13638 		return -ENOMEM;
13639 	length = (sizeof(struct lpfc_mbx_wq_create) -
13640 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13641 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
13642 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
13643 			 length, LPFC_SLI4_MBX_EMBED);
13644 	wq_create = &mbox->u.mqe.un.wq_create;
13645 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
13646 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
13647 		    wq->page_count);
13648 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
13649 		    cq->queue_id);
13650 
13651 	/* wqv is the earliest version supported, NOT the latest */
13652 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13653 	       phba->sli4_hba.pc_sli4_params.wqv);
13654 
13655 	switch (phba->sli4_hba.pc_sli4_params.wqv) {
13656 	case LPFC_Q_CREATE_VERSION_0:
13657 		switch (wq->entry_size) {
13658 		default:
13659 		case 64:
13660 			/* Nothing to do, version 0 ONLY supports 64 byte */
13661 			page = wq_create->u.request.page;
13662 			break;
13663 		case 128:
13664 			if (!(phba->sli4_hba.pc_sli4_params.wqsize &
13665 			    LPFC_WQ_SZ128_SUPPORT)) {
13666 				status = -ERANGE;
13667 				goto out;
13668 			}
13669 			/* If we get here the HBA MUST also support V1 and
13670 			 * we MUST use it
13671 			 */
13672 			bf_set(lpfc_mbox_hdr_version, &shdr->request,
13673 			       LPFC_Q_CREATE_VERSION_1);
13674 
13675 			bf_set(lpfc_mbx_wq_create_wqe_count,
13676 			       &wq_create->u.request_1, wq->entry_count);
13677 			bf_set(lpfc_mbx_wq_create_wqe_size,
13678 			       &wq_create->u.request_1,
13679 			       LPFC_WQ_WQE_SIZE_128);
13680 			bf_set(lpfc_mbx_wq_create_page_size,
13681 			       &wq_create->u.request_1,
13682 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
13683 			page = wq_create->u.request_1.page;
13684 			break;
13685 		}
13686 		break;
13687 	case LPFC_Q_CREATE_VERSION_1:
13688 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
13689 		       wq->entry_count);
13690 		switch (wq->entry_size) {
13691 		default:
13692 		case 64:
13693 			bf_set(lpfc_mbx_wq_create_wqe_size,
13694 			       &wq_create->u.request_1,
13695 			       LPFC_WQ_WQE_SIZE_64);
13696 			break;
13697 		case 128:
13698 			if (!(phba->sli4_hba.pc_sli4_params.wqsize &
13699 				LPFC_WQ_SZ128_SUPPORT)) {
13700 				status = -ERANGE;
13701 				goto out;
13702 			}
13703 			bf_set(lpfc_mbx_wq_create_wqe_size,
13704 			       &wq_create->u.request_1,
13705 			       LPFC_WQ_WQE_SIZE_128);
13706 			break;
13707 		}
13708 		bf_set(lpfc_mbx_wq_create_page_size, &wq_create->u.request_1,
13709 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
13710 		page = wq_create->u.request_1.page;
13711 		break;
13712 	default:
13713 		status = -ERANGE;
13714 		goto out;
13715 	}
13716 
13717 	list_for_each_entry(dmabuf, &wq->page_list, list) {
13718 		memset(dmabuf->virt, 0, hw_page_size);
13719 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
13720 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
13721 	}
13722 
13723 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
13724 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
13725 
13726 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13727 	/* The IOCTL status is embedded in the mailbox subheader. */
13728 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13729 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13730 	if (shdr_status || shdr_add_status || rc) {
13731 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13732 				"2503 WQ_CREATE mailbox failed with "
13733 				"status x%x add_status x%x, mbx status x%x\n",
13734 				shdr_status, shdr_add_status, rc);
13735 		status = -ENXIO;
13736 		goto out;
13737 	}
13738 	wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id, &wq_create->u.response);
13739 	if (wq->queue_id == 0xFFFF) {
13740 		status = -ENXIO;
13741 		goto out;
13742 	}
13743 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
13744 		wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
13745 				       &wq_create->u.response);
13746 		if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
13747 		    (wq->db_format != LPFC_DB_RING_FORMAT)) {
13748 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13749 					"3265 WQ[%d] doorbell format not "
13750 					"supported: x%x\n", wq->queue_id,
13751 					wq->db_format);
13752 			status = -EINVAL;
13753 			goto out;
13754 		}
13755 		pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
13756 				    &wq_create->u.response);
13757 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
13758 		if (!bar_memmap_p) {
13759 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13760 					"3263 WQ[%d] failed to memmap pci "
13761 					"barset:x%x\n", wq->queue_id,
13762 					pci_barset);
13763 			status = -ENOMEM;
13764 			goto out;
13765 		}
13766 		db_offset = wq_create->u.response.doorbell_offset;
13767 		if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
13768 		    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
13769 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13770 					"3252 WQ[%d] doorbell offset not "
13771 					"supported: x%x\n", wq->queue_id,
13772 					db_offset);
13773 			status = -EINVAL;
13774 			goto out;
13775 		}
13776 		wq->db_regaddr = bar_memmap_p + db_offset;
13777 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13778 				"3264 WQ[%d]: barset:x%x, offset:x%x, "
13779 				"format:x%x\n", wq->queue_id, pci_barset,
13780 				db_offset, wq->db_format);
13781 	} else {
13782 		wq->db_format = LPFC_DB_LIST_FORMAT;
13783 		wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
13784 	}
13785 	wq->type = LPFC_WQ;
13786 	wq->assoc_qid = cq->queue_id;
13787 	wq->subtype = subtype;
13788 	wq->host_index = 0;
13789 	wq->hba_index = 0;
13790 	wq->entry_repost = LPFC_RELEASE_NOTIFICATION_INTERVAL;
13791 
13792 	/* link the wq onto the parent cq child list */
13793 	list_add_tail(&wq->list, &cq->child_list);
13794 out:
13795 	mempool_free(mbox, phba->mbox_mem_pool);
13796 	return status;
13797 }
13798 
13799 /**
13800  * lpfc_rq_adjust_repost - Adjust entry_repost for an RQ
13801  * @phba: HBA structure that indicates port to create a queue on.
13802  * @rq:   The queue structure to use for the receive queue.
13803  * @qno:  The associated HBQ number
13804  *
13805  *
13806  * For SLI4 we need to adjust the RQ repost value based on
13807  * the number of buffers that are initially posted to the RQ.
13808  */
13809 void
13810 lpfc_rq_adjust_repost(struct lpfc_hba *phba, struct lpfc_queue *rq, int qno)
13811 {
13812 	uint32_t cnt;
13813 
13814 	/* sanity check on queue memory */
13815 	if (!rq)
13816 		return;
13817 	cnt = lpfc_hbq_defs[qno]->entry_count;
13818 
13819 	/* Recalc repost for RQs based on buffers initially posted */
13820 	cnt = (cnt >> 3);
13821 	if (cnt < LPFC_QUEUE_MIN_REPOST)
13822 		cnt = LPFC_QUEUE_MIN_REPOST;
13823 
13824 	rq->entry_repost = cnt;
13825 }
13826 
13827 /**
13828  * lpfc_rq_create - Create a Receive Queue on the HBA
13829  * @phba: HBA structure that indicates port to create a queue on.
13830  * @hrq: The queue structure to use to create the header receive queue.
13831  * @drq: The queue structure to use to create the data receive queue.
13832  * @cq: The completion queue to bind this work queue to.
13833  *
13834  * This function creates a receive buffer queue pair , as detailed in @hrq and
13835  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
13836  * to the HBA.
13837  *
13838  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
13839  * struct is used to get the entry count that is necessary to determine the
13840  * number of pages to use for this queue. The @cq is used to indicate which
13841  * completion queue to bind received buffers that are posted to these queues to.
13842  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
13843  * receive queue pair. This function is asynchronous and will wait for the
13844  * mailbox command to finish before continuing.
13845  *
13846  * On success this function will return a zero. If unable to allocate enough
13847  * memory this function will return -ENOMEM. If the queue create mailbox command
13848  * fails this function will return -ENXIO.
13849  **/
13850 int
13851 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
13852 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
13853 {
13854 	struct lpfc_mbx_rq_create *rq_create;
13855 	struct lpfc_dmabuf *dmabuf;
13856 	LPFC_MBOXQ_t *mbox;
13857 	int rc, length, status = 0;
13858 	uint32_t shdr_status, shdr_add_status;
13859 	union lpfc_sli4_cfg_shdr *shdr;
13860 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13861 	void __iomem *bar_memmap_p;
13862 	uint32_t db_offset;
13863 	uint16_t pci_barset;
13864 
13865 	/* sanity check on queue memory */
13866 	if (!hrq || !drq || !cq)
13867 		return -ENODEV;
13868 	if (!phba->sli4_hba.pc_sli4_params.supported)
13869 		hw_page_size = SLI4_PAGE_SIZE;
13870 
13871 	if (hrq->entry_count != drq->entry_count)
13872 		return -EINVAL;
13873 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13874 	if (!mbox)
13875 		return -ENOMEM;
13876 	length = (sizeof(struct lpfc_mbx_rq_create) -
13877 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13878 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
13879 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
13880 			 length, LPFC_SLI4_MBX_EMBED);
13881 	rq_create = &mbox->u.mqe.un.rq_create;
13882 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
13883 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13884 	       phba->sli4_hba.pc_sli4_params.rqv);
13885 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
13886 		bf_set(lpfc_rq_context_rqe_count_1,
13887 		       &rq_create->u.request.context,
13888 		       hrq->entry_count);
13889 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
13890 		bf_set(lpfc_rq_context_rqe_size,
13891 		       &rq_create->u.request.context,
13892 		       LPFC_RQE_SIZE_8);
13893 		bf_set(lpfc_rq_context_page_size,
13894 		       &rq_create->u.request.context,
13895 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
13896 	} else {
13897 		switch (hrq->entry_count) {
13898 		default:
13899 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13900 					"2535 Unsupported RQ count. (%d)\n",
13901 					hrq->entry_count);
13902 			if (hrq->entry_count < 512) {
13903 				status = -EINVAL;
13904 				goto out;
13905 			}
13906 			/* otherwise default to smallest count (drop through) */
13907 		case 512:
13908 			bf_set(lpfc_rq_context_rqe_count,
13909 			       &rq_create->u.request.context,
13910 			       LPFC_RQ_RING_SIZE_512);
13911 			break;
13912 		case 1024:
13913 			bf_set(lpfc_rq_context_rqe_count,
13914 			       &rq_create->u.request.context,
13915 			       LPFC_RQ_RING_SIZE_1024);
13916 			break;
13917 		case 2048:
13918 			bf_set(lpfc_rq_context_rqe_count,
13919 			       &rq_create->u.request.context,
13920 			       LPFC_RQ_RING_SIZE_2048);
13921 			break;
13922 		case 4096:
13923 			bf_set(lpfc_rq_context_rqe_count,
13924 			       &rq_create->u.request.context,
13925 			       LPFC_RQ_RING_SIZE_4096);
13926 			break;
13927 		}
13928 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
13929 		       LPFC_HDR_BUF_SIZE);
13930 	}
13931 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
13932 	       cq->queue_id);
13933 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
13934 	       hrq->page_count);
13935 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
13936 		memset(dmabuf->virt, 0, hw_page_size);
13937 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13938 					putPaddrLow(dmabuf->phys);
13939 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13940 					putPaddrHigh(dmabuf->phys);
13941 	}
13942 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
13943 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
13944 
13945 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13946 	/* The IOCTL status is embedded in the mailbox subheader. */
13947 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13948 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13949 	if (shdr_status || shdr_add_status || rc) {
13950 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13951 				"2504 RQ_CREATE mailbox failed with "
13952 				"status x%x add_status x%x, mbx status x%x\n",
13953 				shdr_status, shdr_add_status, rc);
13954 		status = -ENXIO;
13955 		goto out;
13956 	}
13957 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
13958 	if (hrq->queue_id == 0xFFFF) {
13959 		status = -ENXIO;
13960 		goto out;
13961 	}
13962 
13963 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
13964 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
13965 					&rq_create->u.response);
13966 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
13967 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
13968 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13969 					"3262 RQ [%d] doorbell format not "
13970 					"supported: x%x\n", hrq->queue_id,
13971 					hrq->db_format);
13972 			status = -EINVAL;
13973 			goto out;
13974 		}
13975 
13976 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
13977 				    &rq_create->u.response);
13978 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
13979 		if (!bar_memmap_p) {
13980 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13981 					"3269 RQ[%d] failed to memmap pci "
13982 					"barset:x%x\n", hrq->queue_id,
13983 					pci_barset);
13984 			status = -ENOMEM;
13985 			goto out;
13986 		}
13987 
13988 		db_offset = rq_create->u.response.doorbell_offset;
13989 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
13990 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
13991 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13992 					"3270 RQ[%d] doorbell offset not "
13993 					"supported: x%x\n", hrq->queue_id,
13994 					db_offset);
13995 			status = -EINVAL;
13996 			goto out;
13997 		}
13998 		hrq->db_regaddr = bar_memmap_p + db_offset;
13999 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14000 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
14001 				"format:x%x\n", hrq->queue_id, pci_barset,
14002 				db_offset, hrq->db_format);
14003 	} else {
14004 		hrq->db_format = LPFC_DB_RING_FORMAT;
14005 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
14006 	}
14007 	hrq->type = LPFC_HRQ;
14008 	hrq->assoc_qid = cq->queue_id;
14009 	hrq->subtype = subtype;
14010 	hrq->host_index = 0;
14011 	hrq->hba_index = 0;
14012 
14013 	/* now create the data queue */
14014 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14015 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
14016 			 length, LPFC_SLI4_MBX_EMBED);
14017 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
14018 	       phba->sli4_hba.pc_sli4_params.rqv);
14019 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
14020 		bf_set(lpfc_rq_context_rqe_count_1,
14021 		       &rq_create->u.request.context, hrq->entry_count);
14022 		rq_create->u.request.context.buffer_size = LPFC_DATA_BUF_SIZE;
14023 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
14024 		       LPFC_RQE_SIZE_8);
14025 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
14026 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
14027 	} else {
14028 		switch (drq->entry_count) {
14029 		default:
14030 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14031 					"2536 Unsupported RQ count. (%d)\n",
14032 					drq->entry_count);
14033 			if (drq->entry_count < 512) {
14034 				status = -EINVAL;
14035 				goto out;
14036 			}
14037 			/* otherwise default to smallest count (drop through) */
14038 		case 512:
14039 			bf_set(lpfc_rq_context_rqe_count,
14040 			       &rq_create->u.request.context,
14041 			       LPFC_RQ_RING_SIZE_512);
14042 			break;
14043 		case 1024:
14044 			bf_set(lpfc_rq_context_rqe_count,
14045 			       &rq_create->u.request.context,
14046 			       LPFC_RQ_RING_SIZE_1024);
14047 			break;
14048 		case 2048:
14049 			bf_set(lpfc_rq_context_rqe_count,
14050 			       &rq_create->u.request.context,
14051 			       LPFC_RQ_RING_SIZE_2048);
14052 			break;
14053 		case 4096:
14054 			bf_set(lpfc_rq_context_rqe_count,
14055 			       &rq_create->u.request.context,
14056 			       LPFC_RQ_RING_SIZE_4096);
14057 			break;
14058 		}
14059 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
14060 		       LPFC_DATA_BUF_SIZE);
14061 	}
14062 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
14063 	       cq->queue_id);
14064 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
14065 	       drq->page_count);
14066 	list_for_each_entry(dmabuf, &drq->page_list, list) {
14067 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
14068 					putPaddrLow(dmabuf->phys);
14069 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
14070 					putPaddrHigh(dmabuf->phys);
14071 	}
14072 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
14073 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
14074 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14075 	/* The IOCTL status is embedded in the mailbox subheader. */
14076 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
14077 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14078 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14079 	if (shdr_status || shdr_add_status || rc) {
14080 		status = -ENXIO;
14081 		goto out;
14082 	}
14083 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
14084 	if (drq->queue_id == 0xFFFF) {
14085 		status = -ENXIO;
14086 		goto out;
14087 	}
14088 	drq->type = LPFC_DRQ;
14089 	drq->assoc_qid = cq->queue_id;
14090 	drq->subtype = subtype;
14091 	drq->host_index = 0;
14092 	drq->hba_index = 0;
14093 
14094 	/* link the header and data RQs onto the parent cq child list */
14095 	list_add_tail(&hrq->list, &cq->child_list);
14096 	list_add_tail(&drq->list, &cq->child_list);
14097 
14098 out:
14099 	mempool_free(mbox, phba->mbox_mem_pool);
14100 	return status;
14101 }
14102 
14103 /**
14104  * lpfc_eq_destroy - Destroy an event Queue on the HBA
14105  * @eq: The queue structure associated with the queue to destroy.
14106  *
14107  * This function destroys a queue, as detailed in @eq by sending an mailbox
14108  * command, specific to the type of queue, to the HBA.
14109  *
14110  * The @eq struct is used to get the queue ID of the queue to destroy.
14111  *
14112  * On success this function will return a zero. If the queue destroy mailbox
14113  * command fails this function will return -ENXIO.
14114  **/
14115 int
14116 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
14117 {
14118 	LPFC_MBOXQ_t *mbox;
14119 	int rc, length, status = 0;
14120 	uint32_t shdr_status, shdr_add_status;
14121 	union lpfc_sli4_cfg_shdr *shdr;
14122 
14123 	/* sanity check on queue memory */
14124 	if (!eq)
14125 		return -ENODEV;
14126 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
14127 	if (!mbox)
14128 		return -ENOMEM;
14129 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
14130 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14131 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14132 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
14133 			 length, LPFC_SLI4_MBX_EMBED);
14134 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
14135 	       eq->queue_id);
14136 	mbox->vport = eq->phba->pport;
14137 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14138 
14139 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
14140 	/* The IOCTL status is embedded in the mailbox subheader. */
14141 	shdr = (union lpfc_sli4_cfg_shdr *)
14142 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
14143 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14144 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14145 	if (shdr_status || shdr_add_status || rc) {
14146 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14147 				"2505 EQ_DESTROY mailbox failed with "
14148 				"status x%x add_status x%x, mbx status x%x\n",
14149 				shdr_status, shdr_add_status, rc);
14150 		status = -ENXIO;
14151 	}
14152 
14153 	/* Remove eq from any list */
14154 	list_del_init(&eq->list);
14155 	mempool_free(mbox, eq->phba->mbox_mem_pool);
14156 	return status;
14157 }
14158 
14159 /**
14160  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
14161  * @cq: The queue structure associated with the queue to destroy.
14162  *
14163  * This function destroys a queue, as detailed in @cq by sending an mailbox
14164  * command, specific to the type of queue, to the HBA.
14165  *
14166  * The @cq struct is used to get the queue ID of the queue to destroy.
14167  *
14168  * On success this function will return a zero. If the queue destroy mailbox
14169  * command fails this function will return -ENXIO.
14170  **/
14171 int
14172 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
14173 {
14174 	LPFC_MBOXQ_t *mbox;
14175 	int rc, length, status = 0;
14176 	uint32_t shdr_status, shdr_add_status;
14177 	union lpfc_sli4_cfg_shdr *shdr;
14178 
14179 	/* sanity check on queue memory */
14180 	if (!cq)
14181 		return -ENODEV;
14182 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
14183 	if (!mbox)
14184 		return -ENOMEM;
14185 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
14186 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14187 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14188 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
14189 			 length, LPFC_SLI4_MBX_EMBED);
14190 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
14191 	       cq->queue_id);
14192 	mbox->vport = cq->phba->pport;
14193 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14194 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
14195 	/* The IOCTL status is embedded in the mailbox subheader. */
14196 	shdr = (union lpfc_sli4_cfg_shdr *)
14197 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
14198 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14199 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14200 	if (shdr_status || shdr_add_status || rc) {
14201 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14202 				"2506 CQ_DESTROY mailbox failed with "
14203 				"status x%x add_status x%x, mbx status x%x\n",
14204 				shdr_status, shdr_add_status, rc);
14205 		status = -ENXIO;
14206 	}
14207 	/* Remove cq from any list */
14208 	list_del_init(&cq->list);
14209 	mempool_free(mbox, cq->phba->mbox_mem_pool);
14210 	return status;
14211 }
14212 
14213 /**
14214  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
14215  * @qm: The queue structure associated with the queue to destroy.
14216  *
14217  * This function destroys a queue, as detailed in @mq by sending an mailbox
14218  * command, specific to the type of queue, to the HBA.
14219  *
14220  * The @mq struct is used to get the queue ID of the queue to destroy.
14221  *
14222  * On success this function will return a zero. If the queue destroy mailbox
14223  * command fails this function will return -ENXIO.
14224  **/
14225 int
14226 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
14227 {
14228 	LPFC_MBOXQ_t *mbox;
14229 	int rc, length, status = 0;
14230 	uint32_t shdr_status, shdr_add_status;
14231 	union lpfc_sli4_cfg_shdr *shdr;
14232 
14233 	/* sanity check on queue memory */
14234 	if (!mq)
14235 		return -ENODEV;
14236 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
14237 	if (!mbox)
14238 		return -ENOMEM;
14239 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
14240 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14241 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14242 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
14243 			 length, LPFC_SLI4_MBX_EMBED);
14244 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
14245 	       mq->queue_id);
14246 	mbox->vport = mq->phba->pport;
14247 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14248 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
14249 	/* The IOCTL status is embedded in the mailbox subheader. */
14250 	shdr = (union lpfc_sli4_cfg_shdr *)
14251 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
14252 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14253 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14254 	if (shdr_status || shdr_add_status || rc) {
14255 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14256 				"2507 MQ_DESTROY mailbox failed with "
14257 				"status x%x add_status x%x, mbx status x%x\n",
14258 				shdr_status, shdr_add_status, rc);
14259 		status = -ENXIO;
14260 	}
14261 	/* Remove mq from any list */
14262 	list_del_init(&mq->list);
14263 	mempool_free(mbox, mq->phba->mbox_mem_pool);
14264 	return status;
14265 }
14266 
14267 /**
14268  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
14269  * @wq: The queue structure associated with the queue to destroy.
14270  *
14271  * This function destroys a queue, as detailed in @wq by sending an mailbox
14272  * command, specific to the type of queue, to the HBA.
14273  *
14274  * The @wq struct is used to get the queue ID of the queue to destroy.
14275  *
14276  * On success this function will return a zero. If the queue destroy mailbox
14277  * command fails this function will return -ENXIO.
14278  **/
14279 int
14280 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
14281 {
14282 	LPFC_MBOXQ_t *mbox;
14283 	int rc, length, status = 0;
14284 	uint32_t shdr_status, shdr_add_status;
14285 	union lpfc_sli4_cfg_shdr *shdr;
14286 
14287 	/* sanity check on queue memory */
14288 	if (!wq)
14289 		return -ENODEV;
14290 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
14291 	if (!mbox)
14292 		return -ENOMEM;
14293 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
14294 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14295 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14296 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
14297 			 length, LPFC_SLI4_MBX_EMBED);
14298 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
14299 	       wq->queue_id);
14300 	mbox->vport = wq->phba->pport;
14301 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14302 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
14303 	shdr = (union lpfc_sli4_cfg_shdr *)
14304 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
14305 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14306 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14307 	if (shdr_status || shdr_add_status || rc) {
14308 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14309 				"2508 WQ_DESTROY mailbox failed with "
14310 				"status x%x add_status x%x, mbx status x%x\n",
14311 				shdr_status, shdr_add_status, rc);
14312 		status = -ENXIO;
14313 	}
14314 	/* Remove wq from any list */
14315 	list_del_init(&wq->list);
14316 	mempool_free(mbox, wq->phba->mbox_mem_pool);
14317 	return status;
14318 }
14319 
14320 /**
14321  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
14322  * @rq: The queue structure associated with the queue to destroy.
14323  *
14324  * This function destroys a queue, as detailed in @rq by sending an mailbox
14325  * command, specific to the type of queue, to the HBA.
14326  *
14327  * The @rq struct is used to get the queue ID of the queue to destroy.
14328  *
14329  * On success this function will return a zero. If the queue destroy mailbox
14330  * command fails this function will return -ENXIO.
14331  **/
14332 int
14333 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
14334 		struct lpfc_queue *drq)
14335 {
14336 	LPFC_MBOXQ_t *mbox;
14337 	int rc, length, status = 0;
14338 	uint32_t shdr_status, shdr_add_status;
14339 	union lpfc_sli4_cfg_shdr *shdr;
14340 
14341 	/* sanity check on queue memory */
14342 	if (!hrq || !drq)
14343 		return -ENODEV;
14344 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
14345 	if (!mbox)
14346 		return -ENOMEM;
14347 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
14348 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14349 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14350 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
14351 			 length, LPFC_SLI4_MBX_EMBED);
14352 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
14353 	       hrq->queue_id);
14354 	mbox->vport = hrq->phba->pport;
14355 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14356 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
14357 	/* The IOCTL status is embedded in the mailbox subheader. */
14358 	shdr = (union lpfc_sli4_cfg_shdr *)
14359 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
14360 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14361 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14362 	if (shdr_status || shdr_add_status || rc) {
14363 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14364 				"2509 RQ_DESTROY mailbox failed with "
14365 				"status x%x add_status x%x, mbx status x%x\n",
14366 				shdr_status, shdr_add_status, rc);
14367 		if (rc != MBX_TIMEOUT)
14368 			mempool_free(mbox, hrq->phba->mbox_mem_pool);
14369 		return -ENXIO;
14370 	}
14371 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
14372 	       drq->queue_id);
14373 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
14374 	shdr = (union lpfc_sli4_cfg_shdr *)
14375 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
14376 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14377 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14378 	if (shdr_status || shdr_add_status || rc) {
14379 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14380 				"2510 RQ_DESTROY mailbox failed with "
14381 				"status x%x add_status x%x, mbx status x%x\n",
14382 				shdr_status, shdr_add_status, rc);
14383 		status = -ENXIO;
14384 	}
14385 	list_del_init(&hrq->list);
14386 	list_del_init(&drq->list);
14387 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
14388 	return status;
14389 }
14390 
14391 /**
14392  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
14393  * @phba: The virtual port for which this call being executed.
14394  * @pdma_phys_addr0: Physical address of the 1st SGL page.
14395  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
14396  * @xritag: the xritag that ties this io to the SGL pages.
14397  *
14398  * This routine will post the sgl pages for the IO that has the xritag
14399  * that is in the iocbq structure. The xritag is assigned during iocbq
14400  * creation and persists for as long as the driver is loaded.
14401  * if the caller has fewer than 256 scatter gather segments to map then
14402  * pdma_phys_addr1 should be 0.
14403  * If the caller needs to map more than 256 scatter gather segment then
14404  * pdma_phys_addr1 should be a valid physical address.
14405  * physical address for SGLs must be 64 byte aligned.
14406  * If you are going to map 2 SGL's then the first one must have 256 entries
14407  * the second sgl can have between 1 and 256 entries.
14408  *
14409  * Return codes:
14410  * 	0 - Success
14411  * 	-ENXIO, -ENOMEM - Failure
14412  **/
14413 int
14414 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
14415 		dma_addr_t pdma_phys_addr0,
14416 		dma_addr_t pdma_phys_addr1,
14417 		uint16_t xritag)
14418 {
14419 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
14420 	LPFC_MBOXQ_t *mbox;
14421 	int rc;
14422 	uint32_t shdr_status, shdr_add_status;
14423 	uint32_t mbox_tmo;
14424 	union lpfc_sli4_cfg_shdr *shdr;
14425 
14426 	if (xritag == NO_XRI) {
14427 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14428 				"0364 Invalid param:\n");
14429 		return -EINVAL;
14430 	}
14431 
14432 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14433 	if (!mbox)
14434 		return -ENOMEM;
14435 
14436 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14437 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
14438 			sizeof(struct lpfc_mbx_post_sgl_pages) -
14439 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
14440 
14441 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
14442 				&mbox->u.mqe.un.post_sgl_pages;
14443 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
14444 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
14445 
14446 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
14447 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
14448 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
14449 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
14450 
14451 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
14452 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
14453 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
14454 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
14455 	if (!phba->sli4_hba.intr_enable)
14456 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14457 	else {
14458 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
14459 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
14460 	}
14461 	/* The IOCTL status is embedded in the mailbox subheader. */
14462 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
14463 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14464 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14465 	if (rc != MBX_TIMEOUT)
14466 		mempool_free(mbox, phba->mbox_mem_pool);
14467 	if (shdr_status || shdr_add_status || rc) {
14468 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14469 				"2511 POST_SGL mailbox failed with "
14470 				"status x%x add_status x%x, mbx status x%x\n",
14471 				shdr_status, shdr_add_status, rc);
14472 	}
14473 	return 0;
14474 }
14475 
14476 /**
14477  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
14478  * @phba: pointer to lpfc hba data structure.
14479  *
14480  * This routine is invoked to post rpi header templates to the
14481  * HBA consistent with the SLI-4 interface spec.  This routine
14482  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
14483  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
14484  *
14485  * Returns
14486  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
14487  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
14488  **/
14489 static uint16_t
14490 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
14491 {
14492 	unsigned long xri;
14493 
14494 	/*
14495 	 * Fetch the next logical xri.  Because this index is logical,
14496 	 * the driver starts at 0 each time.
14497 	 */
14498 	spin_lock_irq(&phba->hbalock);
14499 	xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
14500 				 phba->sli4_hba.max_cfg_param.max_xri, 0);
14501 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
14502 		spin_unlock_irq(&phba->hbalock);
14503 		return NO_XRI;
14504 	} else {
14505 		set_bit(xri, phba->sli4_hba.xri_bmask);
14506 		phba->sli4_hba.max_cfg_param.xri_used++;
14507 	}
14508 	spin_unlock_irq(&phba->hbalock);
14509 	return xri;
14510 }
14511 
14512 /**
14513  * lpfc_sli4_free_xri - Release an xri for reuse.
14514  * @phba: pointer to lpfc hba data structure.
14515  *
14516  * This routine is invoked to release an xri to the pool of
14517  * available rpis maintained by the driver.
14518  **/
14519 static void
14520 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
14521 {
14522 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
14523 		phba->sli4_hba.max_cfg_param.xri_used--;
14524 	}
14525 }
14526 
14527 /**
14528  * lpfc_sli4_free_xri - Release an xri for reuse.
14529  * @phba: pointer to lpfc hba data structure.
14530  *
14531  * This routine is invoked to release an xri to the pool of
14532  * available rpis maintained by the driver.
14533  **/
14534 void
14535 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
14536 {
14537 	spin_lock_irq(&phba->hbalock);
14538 	__lpfc_sli4_free_xri(phba, xri);
14539 	spin_unlock_irq(&phba->hbalock);
14540 }
14541 
14542 /**
14543  * lpfc_sli4_next_xritag - Get an xritag for the io
14544  * @phba: Pointer to HBA context object.
14545  *
14546  * This function gets an xritag for the iocb. If there is no unused xritag
14547  * it will return 0xffff.
14548  * The function returns the allocated xritag if successful, else returns zero.
14549  * Zero is not a valid xritag.
14550  * The caller is not required to hold any lock.
14551  **/
14552 uint16_t
14553 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
14554 {
14555 	uint16_t xri_index;
14556 
14557 	xri_index = lpfc_sli4_alloc_xri(phba);
14558 	if (xri_index == NO_XRI)
14559 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14560 				"2004 Failed to allocate XRI.last XRITAG is %d"
14561 				" Max XRI is %d, Used XRI is %d\n",
14562 				xri_index,
14563 				phba->sli4_hba.max_cfg_param.max_xri,
14564 				phba->sli4_hba.max_cfg_param.xri_used);
14565 	return xri_index;
14566 }
14567 
14568 /**
14569  * lpfc_sli4_post_els_sgl_list - post a block of ELS sgls to the port.
14570  * @phba: pointer to lpfc hba data structure.
14571  * @post_sgl_list: pointer to els sgl entry list.
14572  * @count: number of els sgl entries on the list.
14573  *
14574  * This routine is invoked to post a block of driver's sgl pages to the
14575  * HBA using non-embedded mailbox command. No Lock is held. This routine
14576  * is only called when the driver is loading and after all IO has been
14577  * stopped.
14578  **/
14579 static int
14580 lpfc_sli4_post_els_sgl_list(struct lpfc_hba *phba,
14581 			    struct list_head *post_sgl_list,
14582 			    int post_cnt)
14583 {
14584 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
14585 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
14586 	struct sgl_page_pairs *sgl_pg_pairs;
14587 	void *viraddr;
14588 	LPFC_MBOXQ_t *mbox;
14589 	uint32_t reqlen, alloclen, pg_pairs;
14590 	uint32_t mbox_tmo;
14591 	uint16_t xritag_start = 0;
14592 	int rc = 0;
14593 	uint32_t shdr_status, shdr_add_status;
14594 	union lpfc_sli4_cfg_shdr *shdr;
14595 
14596 	reqlen = phba->sli4_hba.els_xri_cnt * sizeof(struct sgl_page_pairs) +
14597 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
14598 	if (reqlen > SLI4_PAGE_SIZE) {
14599 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
14600 				"2559 Block sgl registration required DMA "
14601 				"size (%d) great than a page\n", reqlen);
14602 		return -ENOMEM;
14603 	}
14604 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14605 	if (!mbox)
14606 		return -ENOMEM;
14607 
14608 	/* Allocate DMA memory and set up the non-embedded mailbox command */
14609 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14610 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
14611 			 LPFC_SLI4_MBX_NEMBED);
14612 
14613 	if (alloclen < reqlen) {
14614 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14615 				"0285 Allocated DMA memory size (%d) is "
14616 				"less than the requested DMA memory "
14617 				"size (%d)\n", alloclen, reqlen);
14618 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14619 		return -ENOMEM;
14620 	}
14621 	/* Set up the SGL pages in the non-embedded DMA pages */
14622 	viraddr = mbox->sge_array->addr[0];
14623 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
14624 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
14625 
14626 	pg_pairs = 0;
14627 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
14628 		/* Set up the sge entry */
14629 		sgl_pg_pairs->sgl_pg0_addr_lo =
14630 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
14631 		sgl_pg_pairs->sgl_pg0_addr_hi =
14632 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
14633 		sgl_pg_pairs->sgl_pg1_addr_lo =
14634 				cpu_to_le32(putPaddrLow(0));
14635 		sgl_pg_pairs->sgl_pg1_addr_hi =
14636 				cpu_to_le32(putPaddrHigh(0));
14637 
14638 		/* Keep the first xritag on the list */
14639 		if (pg_pairs == 0)
14640 			xritag_start = sglq_entry->sli4_xritag;
14641 		sgl_pg_pairs++;
14642 		pg_pairs++;
14643 	}
14644 
14645 	/* Complete initialization and perform endian conversion. */
14646 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
14647 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, phba->sli4_hba.els_xri_cnt);
14648 	sgl->word0 = cpu_to_le32(sgl->word0);
14649 	if (!phba->sli4_hba.intr_enable)
14650 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14651 	else {
14652 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
14653 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
14654 	}
14655 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
14656 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14657 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14658 	if (rc != MBX_TIMEOUT)
14659 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14660 	if (shdr_status || shdr_add_status || rc) {
14661 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14662 				"2513 POST_SGL_BLOCK mailbox command failed "
14663 				"status x%x add_status x%x mbx status x%x\n",
14664 				shdr_status, shdr_add_status, rc);
14665 		rc = -ENXIO;
14666 	}
14667 	return rc;
14668 }
14669 
14670 /**
14671  * lpfc_sli4_post_scsi_sgl_block - post a block of scsi sgl list to firmware
14672  * @phba: pointer to lpfc hba data structure.
14673  * @sblist: pointer to scsi buffer list.
14674  * @count: number of scsi buffers on the list.
14675  *
14676  * This routine is invoked to post a block of @count scsi sgl pages from a
14677  * SCSI buffer list @sblist to the HBA using non-embedded mailbox command.
14678  * No Lock is held.
14679  *
14680  **/
14681 int
14682 lpfc_sli4_post_scsi_sgl_block(struct lpfc_hba *phba,
14683 			      struct list_head *sblist,
14684 			      int count)
14685 {
14686 	struct lpfc_scsi_buf *psb;
14687 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
14688 	struct sgl_page_pairs *sgl_pg_pairs;
14689 	void *viraddr;
14690 	LPFC_MBOXQ_t *mbox;
14691 	uint32_t reqlen, alloclen, pg_pairs;
14692 	uint32_t mbox_tmo;
14693 	uint16_t xritag_start = 0;
14694 	int rc = 0;
14695 	uint32_t shdr_status, shdr_add_status;
14696 	dma_addr_t pdma_phys_bpl1;
14697 	union lpfc_sli4_cfg_shdr *shdr;
14698 
14699 	/* Calculate the requested length of the dma memory */
14700 	reqlen = count * sizeof(struct sgl_page_pairs) +
14701 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
14702 	if (reqlen > SLI4_PAGE_SIZE) {
14703 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
14704 				"0217 Block sgl registration required DMA "
14705 				"size (%d) great than a page\n", reqlen);
14706 		return -ENOMEM;
14707 	}
14708 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14709 	if (!mbox) {
14710 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14711 				"0283 Failed to allocate mbox cmd memory\n");
14712 		return -ENOMEM;
14713 	}
14714 
14715 	/* Allocate DMA memory and set up the non-embedded mailbox command */
14716 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14717 				LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
14718 				LPFC_SLI4_MBX_NEMBED);
14719 
14720 	if (alloclen < reqlen) {
14721 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14722 				"2561 Allocated DMA memory size (%d) is "
14723 				"less than the requested DMA memory "
14724 				"size (%d)\n", alloclen, reqlen);
14725 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14726 		return -ENOMEM;
14727 	}
14728 
14729 	/* Get the first SGE entry from the non-embedded DMA memory */
14730 	viraddr = mbox->sge_array->addr[0];
14731 
14732 	/* Set up the SGL pages in the non-embedded DMA pages */
14733 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
14734 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
14735 
14736 	pg_pairs = 0;
14737 	list_for_each_entry(psb, sblist, list) {
14738 		/* Set up the sge entry */
14739 		sgl_pg_pairs->sgl_pg0_addr_lo =
14740 			cpu_to_le32(putPaddrLow(psb->dma_phys_bpl));
14741 		sgl_pg_pairs->sgl_pg0_addr_hi =
14742 			cpu_to_le32(putPaddrHigh(psb->dma_phys_bpl));
14743 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
14744 			pdma_phys_bpl1 = psb->dma_phys_bpl + SGL_PAGE_SIZE;
14745 		else
14746 			pdma_phys_bpl1 = 0;
14747 		sgl_pg_pairs->sgl_pg1_addr_lo =
14748 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
14749 		sgl_pg_pairs->sgl_pg1_addr_hi =
14750 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
14751 		/* Keep the first xritag on the list */
14752 		if (pg_pairs == 0)
14753 			xritag_start = psb->cur_iocbq.sli4_xritag;
14754 		sgl_pg_pairs++;
14755 		pg_pairs++;
14756 	}
14757 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
14758 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
14759 	/* Perform endian conversion if necessary */
14760 	sgl->word0 = cpu_to_le32(sgl->word0);
14761 
14762 	if (!phba->sli4_hba.intr_enable)
14763 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14764 	else {
14765 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
14766 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
14767 	}
14768 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
14769 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14770 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14771 	if (rc != MBX_TIMEOUT)
14772 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14773 	if (shdr_status || shdr_add_status || rc) {
14774 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14775 				"2564 POST_SGL_BLOCK mailbox command failed "
14776 				"status x%x add_status x%x mbx status x%x\n",
14777 				shdr_status, shdr_add_status, rc);
14778 		rc = -ENXIO;
14779 	}
14780 	return rc;
14781 }
14782 
14783 /**
14784  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
14785  * @phba: pointer to lpfc_hba struct that the frame was received on
14786  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
14787  *
14788  * This function checks the fields in the @fc_hdr to see if the FC frame is a
14789  * valid type of frame that the LPFC driver will handle. This function will
14790  * return a zero if the frame is a valid frame or a non zero value when the
14791  * frame does not pass the check.
14792  **/
14793 static int
14794 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
14795 {
14796 	/*  make rctl_names static to save stack space */
14797 	static char *rctl_names[] = FC_RCTL_NAMES_INIT;
14798 	char *type_names[] = FC_TYPE_NAMES_INIT;
14799 	struct fc_vft_header *fc_vft_hdr;
14800 	uint32_t *header = (uint32_t *) fc_hdr;
14801 
14802 	switch (fc_hdr->fh_r_ctl) {
14803 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
14804 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
14805 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
14806 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
14807 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
14808 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
14809 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
14810 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
14811 	case FC_RCTL_ELS_REQ:	/* extended link services request */
14812 	case FC_RCTL_ELS_REP:	/* extended link services reply */
14813 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
14814 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
14815 	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
14816 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
14817 	case FC_RCTL_BA_RMC: 	/* remove connection */
14818 	case FC_RCTL_BA_ACC:	/* basic accept */
14819 	case FC_RCTL_BA_RJT:	/* basic reject */
14820 	case FC_RCTL_BA_PRMT:
14821 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
14822 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
14823 	case FC_RCTL_P_RJT:	/* port reject */
14824 	case FC_RCTL_F_RJT:	/* fabric reject */
14825 	case FC_RCTL_P_BSY:	/* port busy */
14826 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
14827 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
14828 	case FC_RCTL_LCR:	/* link credit reset */
14829 	case FC_RCTL_END:	/* end */
14830 		break;
14831 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
14832 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
14833 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
14834 		return lpfc_fc_frame_check(phba, fc_hdr);
14835 	default:
14836 		goto drop;
14837 	}
14838 	switch (fc_hdr->fh_type) {
14839 	case FC_TYPE_BLS:
14840 	case FC_TYPE_ELS:
14841 	case FC_TYPE_FCP:
14842 	case FC_TYPE_CT:
14843 		break;
14844 	case FC_TYPE_IP:
14845 	case FC_TYPE_ILS:
14846 	default:
14847 		goto drop;
14848 	}
14849 
14850 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
14851 			"2538 Received frame rctl:%s (x%x), type:%s (x%x), "
14852 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
14853 			rctl_names[fc_hdr->fh_r_ctl], fc_hdr->fh_r_ctl,
14854 			type_names[fc_hdr->fh_type], fc_hdr->fh_type,
14855 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
14856 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
14857 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
14858 			be32_to_cpu(header[6]));
14859 	return 0;
14860 drop:
14861 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
14862 			"2539 Dropped frame rctl:%s type:%s\n",
14863 			rctl_names[fc_hdr->fh_r_ctl],
14864 			type_names[fc_hdr->fh_type]);
14865 	return 1;
14866 }
14867 
14868 /**
14869  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
14870  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
14871  *
14872  * This function processes the FC header to retrieve the VFI from the VF
14873  * header, if one exists. This function will return the VFI if one exists
14874  * or 0 if no VSAN Header exists.
14875  **/
14876 static uint32_t
14877 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
14878 {
14879 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
14880 
14881 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
14882 		return 0;
14883 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
14884 }
14885 
14886 /**
14887  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
14888  * @phba: Pointer to the HBA structure to search for the vport on
14889  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
14890  * @fcfi: The FC Fabric ID that the frame came from
14891  *
14892  * This function searches the @phba for a vport that matches the content of the
14893  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
14894  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
14895  * returns the matching vport pointer or NULL if unable to match frame to a
14896  * vport.
14897  **/
14898 static struct lpfc_vport *
14899 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
14900 		       uint16_t fcfi)
14901 {
14902 	struct lpfc_vport **vports;
14903 	struct lpfc_vport *vport = NULL;
14904 	int i;
14905 	uint32_t did = (fc_hdr->fh_d_id[0] << 16 |
14906 			fc_hdr->fh_d_id[1] << 8 |
14907 			fc_hdr->fh_d_id[2]);
14908 
14909 	if (did == Fabric_DID)
14910 		return phba->pport;
14911 	if ((phba->pport->fc_flag & FC_PT2PT) &&
14912 		!(phba->link_state == LPFC_HBA_READY))
14913 		return phba->pport;
14914 
14915 	vports = lpfc_create_vport_work_array(phba);
14916 	if (vports != NULL)
14917 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
14918 			if (phba->fcf.fcfi == fcfi &&
14919 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
14920 			    vports[i]->fc_myDID == did) {
14921 				vport = vports[i];
14922 				break;
14923 			}
14924 		}
14925 	lpfc_destroy_vport_work_array(phba, vports);
14926 	return vport;
14927 }
14928 
14929 /**
14930  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
14931  * @vport: The vport to work on.
14932  *
14933  * This function updates the receive sequence time stamp for this vport. The
14934  * receive sequence time stamp indicates the time that the last frame of the
14935  * the sequence that has been idle for the longest amount of time was received.
14936  * the driver uses this time stamp to indicate if any received sequences have
14937  * timed out.
14938  **/
14939 static void
14940 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
14941 {
14942 	struct lpfc_dmabuf *h_buf;
14943 	struct hbq_dmabuf *dmabuf = NULL;
14944 
14945 	/* get the oldest sequence on the rcv list */
14946 	h_buf = list_get_first(&vport->rcv_buffer_list,
14947 			       struct lpfc_dmabuf, list);
14948 	if (!h_buf)
14949 		return;
14950 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
14951 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
14952 }
14953 
14954 /**
14955  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
14956  * @vport: The vport that the received sequences were sent to.
14957  *
14958  * This function cleans up all outstanding received sequences. This is called
14959  * by the driver when a link event or user action invalidates all the received
14960  * sequences.
14961  **/
14962 void
14963 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
14964 {
14965 	struct lpfc_dmabuf *h_buf, *hnext;
14966 	struct lpfc_dmabuf *d_buf, *dnext;
14967 	struct hbq_dmabuf *dmabuf = NULL;
14968 
14969 	/* start with the oldest sequence on the rcv list */
14970 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
14971 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
14972 		list_del_init(&dmabuf->hbuf.list);
14973 		list_for_each_entry_safe(d_buf, dnext,
14974 					 &dmabuf->dbuf.list, list) {
14975 			list_del_init(&d_buf->list);
14976 			lpfc_in_buf_free(vport->phba, d_buf);
14977 		}
14978 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
14979 	}
14980 }
14981 
14982 /**
14983  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
14984  * @vport: The vport that the received sequences were sent to.
14985  *
14986  * This function determines whether any received sequences have timed out by
14987  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
14988  * indicates that there is at least one timed out sequence this routine will
14989  * go through the received sequences one at a time from most inactive to most
14990  * active to determine which ones need to be cleaned up. Once it has determined
14991  * that a sequence needs to be cleaned up it will simply free up the resources
14992  * without sending an abort.
14993  **/
14994 void
14995 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
14996 {
14997 	struct lpfc_dmabuf *h_buf, *hnext;
14998 	struct lpfc_dmabuf *d_buf, *dnext;
14999 	struct hbq_dmabuf *dmabuf = NULL;
15000 	unsigned long timeout;
15001 	int abort_count = 0;
15002 
15003 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
15004 		   vport->rcv_buffer_time_stamp);
15005 	if (list_empty(&vport->rcv_buffer_list) ||
15006 	    time_before(jiffies, timeout))
15007 		return;
15008 	/* start with the oldest sequence on the rcv list */
15009 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
15010 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
15011 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
15012 			   dmabuf->time_stamp);
15013 		if (time_before(jiffies, timeout))
15014 			break;
15015 		abort_count++;
15016 		list_del_init(&dmabuf->hbuf.list);
15017 		list_for_each_entry_safe(d_buf, dnext,
15018 					 &dmabuf->dbuf.list, list) {
15019 			list_del_init(&d_buf->list);
15020 			lpfc_in_buf_free(vport->phba, d_buf);
15021 		}
15022 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
15023 	}
15024 	if (abort_count)
15025 		lpfc_update_rcv_time_stamp(vport);
15026 }
15027 
15028 /**
15029  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
15030  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
15031  *
15032  * This function searches through the existing incomplete sequences that have
15033  * been sent to this @vport. If the frame matches one of the incomplete
15034  * sequences then the dbuf in the @dmabuf is added to the list of frames that
15035  * make up that sequence. If no sequence is found that matches this frame then
15036  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
15037  * This function returns a pointer to the first dmabuf in the sequence list that
15038  * the frame was linked to.
15039  **/
15040 static struct hbq_dmabuf *
15041 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
15042 {
15043 	struct fc_frame_header *new_hdr;
15044 	struct fc_frame_header *temp_hdr;
15045 	struct lpfc_dmabuf *d_buf;
15046 	struct lpfc_dmabuf *h_buf;
15047 	struct hbq_dmabuf *seq_dmabuf = NULL;
15048 	struct hbq_dmabuf *temp_dmabuf = NULL;
15049 	uint8_t	found = 0;
15050 
15051 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
15052 	dmabuf->time_stamp = jiffies;
15053 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
15054 
15055 	/* Use the hdr_buf to find the sequence that this frame belongs to */
15056 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
15057 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
15058 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
15059 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
15060 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
15061 			continue;
15062 		/* found a pending sequence that matches this frame */
15063 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
15064 		break;
15065 	}
15066 	if (!seq_dmabuf) {
15067 		/*
15068 		 * This indicates first frame received for this sequence.
15069 		 * Queue the buffer on the vport's rcv_buffer_list.
15070 		 */
15071 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
15072 		lpfc_update_rcv_time_stamp(vport);
15073 		return dmabuf;
15074 	}
15075 	temp_hdr = seq_dmabuf->hbuf.virt;
15076 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
15077 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
15078 		list_del_init(&seq_dmabuf->hbuf.list);
15079 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
15080 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
15081 		lpfc_update_rcv_time_stamp(vport);
15082 		return dmabuf;
15083 	}
15084 	/* move this sequence to the tail to indicate a young sequence */
15085 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
15086 	seq_dmabuf->time_stamp = jiffies;
15087 	lpfc_update_rcv_time_stamp(vport);
15088 	if (list_empty(&seq_dmabuf->dbuf.list)) {
15089 		temp_hdr = dmabuf->hbuf.virt;
15090 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
15091 		return seq_dmabuf;
15092 	}
15093 	/* find the correct place in the sequence to insert this frame */
15094 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
15095 	while (!found) {
15096 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15097 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
15098 		/*
15099 		 * If the frame's sequence count is greater than the frame on
15100 		 * the list then insert the frame right after this frame
15101 		 */
15102 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
15103 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
15104 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
15105 			found = 1;
15106 			break;
15107 		}
15108 
15109 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
15110 			break;
15111 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
15112 	}
15113 
15114 	if (found)
15115 		return seq_dmabuf;
15116 	return NULL;
15117 }
15118 
15119 /**
15120  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
15121  * @vport: pointer to a vitural port
15122  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15123  *
15124  * This function tries to abort from the partially assembed sequence, described
15125  * by the information from basic abbort @dmabuf. It checks to see whether such
15126  * partially assembled sequence held by the driver. If so, it shall free up all
15127  * the frames from the partially assembled sequence.
15128  *
15129  * Return
15130  * true  -- if there is matching partially assembled sequence present and all
15131  *          the frames freed with the sequence;
15132  * false -- if there is no matching partially assembled sequence present so
15133  *          nothing got aborted in the lower layer driver
15134  **/
15135 static bool
15136 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
15137 			    struct hbq_dmabuf *dmabuf)
15138 {
15139 	struct fc_frame_header *new_hdr;
15140 	struct fc_frame_header *temp_hdr;
15141 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
15142 	struct hbq_dmabuf *seq_dmabuf = NULL;
15143 
15144 	/* Use the hdr_buf to find the sequence that matches this frame */
15145 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
15146 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
15147 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
15148 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
15149 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
15150 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
15151 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
15152 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
15153 			continue;
15154 		/* found a pending sequence that matches this frame */
15155 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
15156 		break;
15157 	}
15158 
15159 	/* Free up all the frames from the partially assembled sequence */
15160 	if (seq_dmabuf) {
15161 		list_for_each_entry_safe(d_buf, n_buf,
15162 					 &seq_dmabuf->dbuf.list, list) {
15163 			list_del_init(&d_buf->list);
15164 			lpfc_in_buf_free(vport->phba, d_buf);
15165 		}
15166 		return true;
15167 	}
15168 	return false;
15169 }
15170 
15171 /**
15172  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
15173  * @vport: pointer to a vitural port
15174  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15175  *
15176  * This function tries to abort from the assembed sequence from upper level
15177  * protocol, described by the information from basic abbort @dmabuf. It
15178  * checks to see whether such pending context exists at upper level protocol.
15179  * If so, it shall clean up the pending context.
15180  *
15181  * Return
15182  * true  -- if there is matching pending context of the sequence cleaned
15183  *          at ulp;
15184  * false -- if there is no matching pending context of the sequence present
15185  *          at ulp.
15186  **/
15187 static bool
15188 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
15189 {
15190 	struct lpfc_hba *phba = vport->phba;
15191 	int handled;
15192 
15193 	/* Accepting abort at ulp with SLI4 only */
15194 	if (phba->sli_rev < LPFC_SLI_REV4)
15195 		return false;
15196 
15197 	/* Register all caring upper level protocols to attend abort */
15198 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
15199 	if (handled)
15200 		return true;
15201 
15202 	return false;
15203 }
15204 
15205 /**
15206  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
15207  * @phba: Pointer to HBA context object.
15208  * @cmd_iocbq: pointer to the command iocbq structure.
15209  * @rsp_iocbq: pointer to the response iocbq structure.
15210  *
15211  * This function handles the sequence abort response iocb command complete
15212  * event. It properly releases the memory allocated to the sequence abort
15213  * accept iocb.
15214  **/
15215 static void
15216 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
15217 			     struct lpfc_iocbq *cmd_iocbq,
15218 			     struct lpfc_iocbq *rsp_iocbq)
15219 {
15220 	struct lpfc_nodelist *ndlp;
15221 
15222 	if (cmd_iocbq) {
15223 		ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
15224 		lpfc_nlp_put(ndlp);
15225 		lpfc_nlp_not_used(ndlp);
15226 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
15227 	}
15228 
15229 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
15230 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
15231 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15232 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
15233 			rsp_iocbq->iocb.ulpStatus,
15234 			rsp_iocbq->iocb.un.ulpWord[4]);
15235 }
15236 
15237 /**
15238  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
15239  * @phba: Pointer to HBA context object.
15240  * @xri: xri id in transaction.
15241  *
15242  * This function validates the xri maps to the known range of XRIs allocated an
15243  * used by the driver.
15244  **/
15245 uint16_t
15246 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
15247 		      uint16_t xri)
15248 {
15249 	uint16_t i;
15250 
15251 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
15252 		if (xri == phba->sli4_hba.xri_ids[i])
15253 			return i;
15254 	}
15255 	return NO_XRI;
15256 }
15257 
15258 /**
15259  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
15260  * @phba: Pointer to HBA context object.
15261  * @fc_hdr: pointer to a FC frame header.
15262  *
15263  * This function sends a basic response to a previous unsol sequence abort
15264  * event after aborting the sequence handling.
15265  **/
15266 static void
15267 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
15268 			struct fc_frame_header *fc_hdr, bool aborted)
15269 {
15270 	struct lpfc_hba *phba = vport->phba;
15271 	struct lpfc_iocbq *ctiocb = NULL;
15272 	struct lpfc_nodelist *ndlp;
15273 	uint16_t oxid, rxid, xri, lxri;
15274 	uint32_t sid, fctl;
15275 	IOCB_t *icmd;
15276 	int rc;
15277 
15278 	if (!lpfc_is_link_up(phba))
15279 		return;
15280 
15281 	sid = sli4_sid_from_fc_hdr(fc_hdr);
15282 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
15283 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
15284 
15285 	ndlp = lpfc_findnode_did(vport, sid);
15286 	if (!ndlp) {
15287 		ndlp = mempool_alloc(phba->nlp_mem_pool, GFP_KERNEL);
15288 		if (!ndlp) {
15289 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
15290 					 "1268 Failed to allocate ndlp for "
15291 					 "oxid:x%x SID:x%x\n", oxid, sid);
15292 			return;
15293 		}
15294 		lpfc_nlp_init(vport, ndlp, sid);
15295 		/* Put ndlp onto pport node list */
15296 		lpfc_enqueue_node(vport, ndlp);
15297 	} else if (!NLP_CHK_NODE_ACT(ndlp)) {
15298 		/* re-setup ndlp without removing from node list */
15299 		ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_UNUSED_NODE);
15300 		if (!ndlp) {
15301 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
15302 					 "3275 Failed to active ndlp found "
15303 					 "for oxid:x%x SID:x%x\n", oxid, sid);
15304 			return;
15305 		}
15306 	}
15307 
15308 	/* Allocate buffer for rsp iocb */
15309 	ctiocb = lpfc_sli_get_iocbq(phba);
15310 	if (!ctiocb)
15311 		return;
15312 
15313 	/* Extract the F_CTL field from FC_HDR */
15314 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
15315 
15316 	icmd = &ctiocb->iocb;
15317 	icmd->un.xseq64.bdl.bdeSize = 0;
15318 	icmd->un.xseq64.bdl.ulpIoTag32 = 0;
15319 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
15320 	icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
15321 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
15322 
15323 	/* Fill in the rest of iocb fields */
15324 	icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
15325 	icmd->ulpBdeCount = 0;
15326 	icmd->ulpLe = 1;
15327 	icmd->ulpClass = CLASS3;
15328 	icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
15329 	ctiocb->context1 = lpfc_nlp_get(ndlp);
15330 
15331 	ctiocb->iocb_cmpl = NULL;
15332 	ctiocb->vport = phba->pport;
15333 	ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
15334 	ctiocb->sli4_lxritag = NO_XRI;
15335 	ctiocb->sli4_xritag = NO_XRI;
15336 
15337 	if (fctl & FC_FC_EX_CTX)
15338 		/* Exchange responder sent the abort so we
15339 		 * own the oxid.
15340 		 */
15341 		xri = oxid;
15342 	else
15343 		xri = rxid;
15344 	lxri = lpfc_sli4_xri_inrange(phba, xri);
15345 	if (lxri != NO_XRI)
15346 		lpfc_set_rrq_active(phba, ndlp, lxri,
15347 			(xri == oxid) ? rxid : oxid, 0);
15348 	/* For BA_ABTS from exchange responder, if the logical xri with
15349 	 * the oxid maps to the FCP XRI range, the port no longer has
15350 	 * that exchange context, send a BLS_RJT. Override the IOCB for
15351 	 * a BA_RJT.
15352 	 */
15353 	if ((fctl & FC_FC_EX_CTX) &&
15354 	    (lxri > lpfc_sli4_get_els_iocb_cnt(phba))) {
15355 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
15356 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
15357 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
15358 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
15359 	}
15360 
15361 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
15362 	 * the driver no longer has that exchange, send a BLS_RJT. Override
15363 	 * the IOCB for a BA_RJT.
15364 	 */
15365 	if (aborted == false) {
15366 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
15367 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
15368 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
15369 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
15370 	}
15371 
15372 	if (fctl & FC_FC_EX_CTX) {
15373 		/* ABTS sent by responder to CT exchange, construction
15374 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
15375 		 * field and RX_ID from ABTS for RX_ID field.
15376 		 */
15377 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
15378 	} else {
15379 		/* ABTS sent by initiator to CT exchange, construction
15380 		 * of BA_ACC will need to allocate a new XRI as for the
15381 		 * XRI_TAG field.
15382 		 */
15383 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
15384 	}
15385 	bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
15386 	bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
15387 
15388 	/* Xmit CT abts response on exchange <xid> */
15389 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
15390 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
15391 			 icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
15392 
15393 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
15394 	if (rc == IOCB_ERROR) {
15395 		lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
15396 				 "2925 Failed to issue CT ABTS RSP x%x on "
15397 				 "xri x%x, Data x%x\n",
15398 				 icmd->un.xseq64.w5.hcsw.Rctl, oxid,
15399 				 phba->link_state);
15400 		lpfc_nlp_put(ndlp);
15401 		ctiocb->context1 = NULL;
15402 		lpfc_sli_release_iocbq(phba, ctiocb);
15403 	}
15404 }
15405 
15406 /**
15407  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
15408  * @vport: Pointer to the vport on which this sequence was received
15409  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15410  *
15411  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
15412  * receive sequence is only partially assembed by the driver, it shall abort
15413  * the partially assembled frames for the sequence. Otherwise, if the
15414  * unsolicited receive sequence has been completely assembled and passed to
15415  * the Upper Layer Protocol (UPL), it then mark the per oxid status for the
15416  * unsolicited sequence has been aborted. After that, it will issue a basic
15417  * accept to accept the abort.
15418  **/
15419 static void
15420 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
15421 			     struct hbq_dmabuf *dmabuf)
15422 {
15423 	struct lpfc_hba *phba = vport->phba;
15424 	struct fc_frame_header fc_hdr;
15425 	uint32_t fctl;
15426 	bool aborted;
15427 
15428 	/* Make a copy of fc_hdr before the dmabuf being released */
15429 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
15430 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
15431 
15432 	if (fctl & FC_FC_EX_CTX) {
15433 		/* ABTS by responder to exchange, no cleanup needed */
15434 		aborted = true;
15435 	} else {
15436 		/* ABTS by initiator to exchange, need to do cleanup */
15437 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
15438 		if (aborted == false)
15439 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
15440 	}
15441 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
15442 
15443 	/* Respond with BA_ACC or BA_RJT accordingly */
15444 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
15445 }
15446 
15447 /**
15448  * lpfc_seq_complete - Indicates if a sequence is complete
15449  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15450  *
15451  * This function checks the sequence, starting with the frame described by
15452  * @dmabuf, to see if all the frames associated with this sequence are present.
15453  * the frames associated with this sequence are linked to the @dmabuf using the
15454  * dbuf list. This function looks for two major things. 1) That the first frame
15455  * has a sequence count of zero. 2) There is a frame with last frame of sequence
15456  * set. 3) That there are no holes in the sequence count. The function will
15457  * return 1 when the sequence is complete, otherwise it will return 0.
15458  **/
15459 static int
15460 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
15461 {
15462 	struct fc_frame_header *hdr;
15463 	struct lpfc_dmabuf *d_buf;
15464 	struct hbq_dmabuf *seq_dmabuf;
15465 	uint32_t fctl;
15466 	int seq_count = 0;
15467 
15468 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
15469 	/* make sure first fame of sequence has a sequence count of zero */
15470 	if (hdr->fh_seq_cnt != seq_count)
15471 		return 0;
15472 	fctl = (hdr->fh_f_ctl[0] << 16 |
15473 		hdr->fh_f_ctl[1] << 8 |
15474 		hdr->fh_f_ctl[2]);
15475 	/* If last frame of sequence we can return success. */
15476 	if (fctl & FC_FC_END_SEQ)
15477 		return 1;
15478 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
15479 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15480 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
15481 		/* If there is a hole in the sequence count then fail. */
15482 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
15483 			return 0;
15484 		fctl = (hdr->fh_f_ctl[0] << 16 |
15485 			hdr->fh_f_ctl[1] << 8 |
15486 			hdr->fh_f_ctl[2]);
15487 		/* If last frame of sequence we can return success. */
15488 		if (fctl & FC_FC_END_SEQ)
15489 			return 1;
15490 	}
15491 	return 0;
15492 }
15493 
15494 /**
15495  * lpfc_prep_seq - Prep sequence for ULP processing
15496  * @vport: Pointer to the vport on which this sequence was received
15497  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15498  *
15499  * This function takes a sequence, described by a list of frames, and creates
15500  * a list of iocbq structures to describe the sequence. This iocbq list will be
15501  * used to issue to the generic unsolicited sequence handler. This routine
15502  * returns a pointer to the first iocbq in the list. If the function is unable
15503  * to allocate an iocbq then it throw out the received frames that were not
15504  * able to be described and return a pointer to the first iocbq. If unable to
15505  * allocate any iocbqs (including the first) this function will return NULL.
15506  **/
15507 static struct lpfc_iocbq *
15508 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
15509 {
15510 	struct hbq_dmabuf *hbq_buf;
15511 	struct lpfc_dmabuf *d_buf, *n_buf;
15512 	struct lpfc_iocbq *first_iocbq, *iocbq;
15513 	struct fc_frame_header *fc_hdr;
15514 	uint32_t sid;
15515 	uint32_t len, tot_len;
15516 	struct ulp_bde64 *pbde;
15517 
15518 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
15519 	/* remove from receive buffer list */
15520 	list_del_init(&seq_dmabuf->hbuf.list);
15521 	lpfc_update_rcv_time_stamp(vport);
15522 	/* get the Remote Port's SID */
15523 	sid = sli4_sid_from_fc_hdr(fc_hdr);
15524 	tot_len = 0;
15525 	/* Get an iocbq struct to fill in. */
15526 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
15527 	if (first_iocbq) {
15528 		/* Initialize the first IOCB. */
15529 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
15530 		first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
15531 
15532 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
15533 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
15534 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
15535 			first_iocbq->iocb.un.rcvels.parmRo =
15536 				sli4_did_from_fc_hdr(fc_hdr);
15537 			first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
15538 		} else
15539 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
15540 		first_iocbq->iocb.ulpContext = NO_XRI;
15541 		first_iocbq->iocb.unsli3.rcvsli3.ox_id =
15542 			be16_to_cpu(fc_hdr->fh_ox_id);
15543 		/* iocbq is prepped for internal consumption.  Physical vpi. */
15544 		first_iocbq->iocb.unsli3.rcvsli3.vpi =
15545 			vport->phba->vpi_ids[vport->vpi];
15546 		/* put the first buffer into the first IOCBq */
15547 		tot_len = bf_get(lpfc_rcqe_length,
15548 				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
15549 
15550 		first_iocbq->context2 = &seq_dmabuf->dbuf;
15551 		first_iocbq->context3 = NULL;
15552 		first_iocbq->iocb.ulpBdeCount = 1;
15553 		if (tot_len > LPFC_DATA_BUF_SIZE)
15554 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
15555 							LPFC_DATA_BUF_SIZE;
15556 		else
15557 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
15558 
15559 		first_iocbq->iocb.un.rcvels.remoteID = sid;
15560 
15561 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
15562 	}
15563 	iocbq = first_iocbq;
15564 	/*
15565 	 * Each IOCBq can have two Buffers assigned, so go through the list
15566 	 * of buffers for this sequence and save two buffers in each IOCBq
15567 	 */
15568 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
15569 		if (!iocbq) {
15570 			lpfc_in_buf_free(vport->phba, d_buf);
15571 			continue;
15572 		}
15573 		if (!iocbq->context3) {
15574 			iocbq->context3 = d_buf;
15575 			iocbq->iocb.ulpBdeCount++;
15576 			/* We need to get the size out of the right CQE */
15577 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15578 			len = bf_get(lpfc_rcqe_length,
15579 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
15580 			pbde = (struct ulp_bde64 *)
15581 					&iocbq->iocb.unsli3.sli3Words[4];
15582 			if (len > LPFC_DATA_BUF_SIZE)
15583 				pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
15584 			else
15585 				pbde->tus.f.bdeSize = len;
15586 
15587 			iocbq->iocb.unsli3.rcvsli3.acc_len += len;
15588 			tot_len += len;
15589 		} else {
15590 			iocbq = lpfc_sli_get_iocbq(vport->phba);
15591 			if (!iocbq) {
15592 				if (first_iocbq) {
15593 					first_iocbq->iocb.ulpStatus =
15594 							IOSTAT_FCP_RSP_ERROR;
15595 					first_iocbq->iocb.un.ulpWord[4] =
15596 							IOERR_NO_RESOURCES;
15597 				}
15598 				lpfc_in_buf_free(vport->phba, d_buf);
15599 				continue;
15600 			}
15601 			/* We need to get the size out of the right CQE */
15602 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15603 			len = bf_get(lpfc_rcqe_length,
15604 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
15605 			iocbq->context2 = d_buf;
15606 			iocbq->context3 = NULL;
15607 			iocbq->iocb.ulpBdeCount = 1;
15608 			if (len > LPFC_DATA_BUF_SIZE)
15609 				iocbq->iocb.un.cont64[0].tus.f.bdeSize =
15610 							LPFC_DATA_BUF_SIZE;
15611 			else
15612 				iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
15613 
15614 			tot_len += len;
15615 			iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
15616 
15617 			iocbq->iocb.un.rcvels.remoteID = sid;
15618 			list_add_tail(&iocbq->list, &first_iocbq->list);
15619 		}
15620 	}
15621 	return first_iocbq;
15622 }
15623 
15624 static void
15625 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
15626 			  struct hbq_dmabuf *seq_dmabuf)
15627 {
15628 	struct fc_frame_header *fc_hdr;
15629 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
15630 	struct lpfc_hba *phba = vport->phba;
15631 
15632 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
15633 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
15634 	if (!iocbq) {
15635 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15636 				"2707 Ring %d handler: Failed to allocate "
15637 				"iocb Rctl x%x Type x%x received\n",
15638 				LPFC_ELS_RING,
15639 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
15640 		return;
15641 	}
15642 	if (!lpfc_complete_unsol_iocb(phba,
15643 				      &phba->sli.ring[LPFC_ELS_RING],
15644 				      iocbq, fc_hdr->fh_r_ctl,
15645 				      fc_hdr->fh_type))
15646 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15647 				"2540 Ring %d handler: unexpected Rctl "
15648 				"x%x Type x%x received\n",
15649 				LPFC_ELS_RING,
15650 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
15651 
15652 	/* Free iocb created in lpfc_prep_seq */
15653 	list_for_each_entry_safe(curr_iocb, next_iocb,
15654 		&iocbq->list, list) {
15655 		list_del_init(&curr_iocb->list);
15656 		lpfc_sli_release_iocbq(phba, curr_iocb);
15657 	}
15658 	lpfc_sli_release_iocbq(phba, iocbq);
15659 }
15660 
15661 /**
15662  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
15663  * @phba: Pointer to HBA context object.
15664  *
15665  * This function is called with no lock held. This function processes all
15666  * the received buffers and gives it to upper layers when a received buffer
15667  * indicates that it is the final frame in the sequence. The interrupt
15668  * service routine processes received buffers at interrupt contexts and adds
15669  * received dma buffers to the rb_pend_list queue and signals the worker thread.
15670  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
15671  * appropriate receive function when the final frame in a sequence is received.
15672  **/
15673 void
15674 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
15675 				 struct hbq_dmabuf *dmabuf)
15676 {
15677 	struct hbq_dmabuf *seq_dmabuf;
15678 	struct fc_frame_header *fc_hdr;
15679 	struct lpfc_vport *vport;
15680 	uint32_t fcfi;
15681 	uint32_t did;
15682 
15683 	/* Process each received buffer */
15684 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
15685 	/* check to see if this a valid type of frame */
15686 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
15687 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
15688 		return;
15689 	}
15690 	if ((bf_get(lpfc_cqe_code,
15691 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
15692 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
15693 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
15694 	else
15695 		fcfi = bf_get(lpfc_rcqe_fcf_id,
15696 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
15697 
15698 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi);
15699 	if (!vport) {
15700 		/* throw out the frame */
15701 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
15702 		return;
15703 	}
15704 
15705 	/* d_id this frame is directed to */
15706 	did = sli4_did_from_fc_hdr(fc_hdr);
15707 
15708 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
15709 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
15710 		(did != Fabric_DID)) {
15711 		/*
15712 		 * Throw out the frame if we are not pt2pt.
15713 		 * The pt2pt protocol allows for discovery frames
15714 		 * to be received without a registered VPI.
15715 		 */
15716 		if (!(vport->fc_flag & FC_PT2PT) ||
15717 			(phba->link_state == LPFC_HBA_READY)) {
15718 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
15719 			return;
15720 		}
15721 	}
15722 
15723 	/* Handle the basic abort sequence (BA_ABTS) event */
15724 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
15725 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
15726 		return;
15727 	}
15728 
15729 	/* Link this frame */
15730 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
15731 	if (!seq_dmabuf) {
15732 		/* unable to add frame to vport - throw it out */
15733 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
15734 		return;
15735 	}
15736 	/* If not last frame in sequence continue processing frames. */
15737 	if (!lpfc_seq_complete(seq_dmabuf))
15738 		return;
15739 
15740 	/* Send the complete sequence to the upper layer protocol */
15741 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
15742 }
15743 
15744 /**
15745  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
15746  * @phba: pointer to lpfc hba data structure.
15747  *
15748  * This routine is invoked to post rpi header templates to the
15749  * HBA consistent with the SLI-4 interface spec.  This routine
15750  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
15751  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
15752  *
15753  * This routine does not require any locks.  It's usage is expected
15754  * to be driver load or reset recovery when the driver is
15755  * sequential.
15756  *
15757  * Return codes
15758  * 	0 - successful
15759  *      -EIO - The mailbox failed to complete successfully.
15760  * 	When this error occurs, the driver is not guaranteed
15761  *	to have any rpi regions posted to the device and
15762  *	must either attempt to repost the regions or take a
15763  *	fatal error.
15764  **/
15765 int
15766 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
15767 {
15768 	struct lpfc_rpi_hdr *rpi_page;
15769 	uint32_t rc = 0;
15770 	uint16_t lrpi = 0;
15771 
15772 	/* SLI4 ports that support extents do not require RPI headers. */
15773 	if (!phba->sli4_hba.rpi_hdrs_in_use)
15774 		goto exit;
15775 	if (phba->sli4_hba.extents_in_use)
15776 		return -EIO;
15777 
15778 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
15779 		/*
15780 		 * Assign the rpi headers a physical rpi only if the driver
15781 		 * has not initialized those resources.  A port reset only
15782 		 * needs the headers posted.
15783 		 */
15784 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
15785 		    LPFC_RPI_RSRC_RDY)
15786 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
15787 
15788 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
15789 		if (rc != MBX_SUCCESS) {
15790 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15791 					"2008 Error %d posting all rpi "
15792 					"headers\n", rc);
15793 			rc = -EIO;
15794 			break;
15795 		}
15796 	}
15797 
15798  exit:
15799 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
15800 	       LPFC_RPI_RSRC_RDY);
15801 	return rc;
15802 }
15803 
15804 /**
15805  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
15806  * @phba: pointer to lpfc hba data structure.
15807  * @rpi_page:  pointer to the rpi memory region.
15808  *
15809  * This routine is invoked to post a single rpi header to the
15810  * HBA consistent with the SLI-4 interface spec.  This memory region
15811  * maps up to 64 rpi context regions.
15812  *
15813  * Return codes
15814  * 	0 - successful
15815  * 	-ENOMEM - No available memory
15816  *      -EIO - The mailbox failed to complete successfully.
15817  **/
15818 int
15819 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
15820 {
15821 	LPFC_MBOXQ_t *mboxq;
15822 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
15823 	uint32_t rc = 0;
15824 	uint32_t shdr_status, shdr_add_status;
15825 	union lpfc_sli4_cfg_shdr *shdr;
15826 
15827 	/* SLI4 ports that support extents do not require RPI headers. */
15828 	if (!phba->sli4_hba.rpi_hdrs_in_use)
15829 		return rc;
15830 	if (phba->sli4_hba.extents_in_use)
15831 		return -EIO;
15832 
15833 	/* The port is notified of the header region via a mailbox command. */
15834 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15835 	if (!mboxq) {
15836 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15837 				"2001 Unable to allocate memory for issuing "
15838 				"SLI_CONFIG_SPECIAL mailbox command\n");
15839 		return -ENOMEM;
15840 	}
15841 
15842 	/* Post all rpi memory regions to the port. */
15843 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
15844 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
15845 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
15846 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
15847 			 sizeof(struct lpfc_sli4_cfg_mhdr),
15848 			 LPFC_SLI4_MBX_EMBED);
15849 
15850 
15851 	/* Post the physical rpi to the port for this rpi header. */
15852 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
15853 	       rpi_page->start_rpi);
15854 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
15855 	       hdr_tmpl, rpi_page->page_count);
15856 
15857 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
15858 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
15859 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
15860 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
15861 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15862 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15863 	if (rc != MBX_TIMEOUT)
15864 		mempool_free(mboxq, phba->mbox_mem_pool);
15865 	if (shdr_status || shdr_add_status || rc) {
15866 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15867 				"2514 POST_RPI_HDR mailbox failed with "
15868 				"status x%x add_status x%x, mbx status x%x\n",
15869 				shdr_status, shdr_add_status, rc);
15870 		rc = -ENXIO;
15871 	}
15872 	return rc;
15873 }
15874 
15875 /**
15876  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
15877  * @phba: pointer to lpfc hba data structure.
15878  *
15879  * This routine is invoked to post rpi header templates to the
15880  * HBA consistent with the SLI-4 interface spec.  This routine
15881  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
15882  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
15883  *
15884  * Returns
15885  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
15886  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
15887  **/
15888 int
15889 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
15890 {
15891 	unsigned long rpi;
15892 	uint16_t max_rpi, rpi_limit;
15893 	uint16_t rpi_remaining, lrpi = 0;
15894 	struct lpfc_rpi_hdr *rpi_hdr;
15895 	unsigned long iflag;
15896 
15897 	/*
15898 	 * Fetch the next logical rpi.  Because this index is logical,
15899 	 * the  driver starts at 0 each time.
15900 	 */
15901 	spin_lock_irqsave(&phba->hbalock, iflag);
15902 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
15903 	rpi_limit = phba->sli4_hba.next_rpi;
15904 
15905 	rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
15906 	if (rpi >= rpi_limit)
15907 		rpi = LPFC_RPI_ALLOC_ERROR;
15908 	else {
15909 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
15910 		phba->sli4_hba.max_cfg_param.rpi_used++;
15911 		phba->sli4_hba.rpi_count++;
15912 	}
15913 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
15914 			"0001 rpi:%x max:%x lim:%x\n",
15915 			(int) rpi, max_rpi, rpi_limit);
15916 
15917 	/*
15918 	 * Don't try to allocate more rpi header regions if the device limit
15919 	 * has been exhausted.
15920 	 */
15921 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
15922 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
15923 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15924 		return rpi;
15925 	}
15926 
15927 	/*
15928 	 * RPI header postings are not required for SLI4 ports capable of
15929 	 * extents.
15930 	 */
15931 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
15932 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15933 		return rpi;
15934 	}
15935 
15936 	/*
15937 	 * If the driver is running low on rpi resources, allocate another
15938 	 * page now.  Note that the next_rpi value is used because
15939 	 * it represents how many are actually in use whereas max_rpi notes
15940 	 * how many are supported max by the device.
15941 	 */
15942 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
15943 	spin_unlock_irqrestore(&phba->hbalock, iflag);
15944 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
15945 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
15946 		if (!rpi_hdr) {
15947 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15948 					"2002 Error Could not grow rpi "
15949 					"count\n");
15950 		} else {
15951 			lrpi = rpi_hdr->start_rpi;
15952 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
15953 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
15954 		}
15955 	}
15956 
15957 	return rpi;
15958 }
15959 
15960 /**
15961  * lpfc_sli4_free_rpi - Release an rpi for reuse.
15962  * @phba: pointer to lpfc hba data structure.
15963  *
15964  * This routine is invoked to release an rpi to the pool of
15965  * available rpis maintained by the driver.
15966  **/
15967 static void
15968 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
15969 {
15970 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
15971 		phba->sli4_hba.rpi_count--;
15972 		phba->sli4_hba.max_cfg_param.rpi_used--;
15973 	}
15974 }
15975 
15976 /**
15977  * lpfc_sli4_free_rpi - Release an rpi for reuse.
15978  * @phba: pointer to lpfc hba data structure.
15979  *
15980  * This routine is invoked to release an rpi to the pool of
15981  * available rpis maintained by the driver.
15982  **/
15983 void
15984 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
15985 {
15986 	spin_lock_irq(&phba->hbalock);
15987 	__lpfc_sli4_free_rpi(phba, rpi);
15988 	spin_unlock_irq(&phba->hbalock);
15989 }
15990 
15991 /**
15992  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
15993  * @phba: pointer to lpfc hba data structure.
15994  *
15995  * This routine is invoked to remove the memory region that
15996  * provided rpi via a bitmask.
15997  **/
15998 void
15999 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
16000 {
16001 	kfree(phba->sli4_hba.rpi_bmask);
16002 	kfree(phba->sli4_hba.rpi_ids);
16003 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
16004 }
16005 
16006 /**
16007  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
16008  * @phba: pointer to lpfc hba data structure.
16009  *
16010  * This routine is invoked to remove the memory region that
16011  * provided rpi via a bitmask.
16012  **/
16013 int
16014 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
16015 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
16016 {
16017 	LPFC_MBOXQ_t *mboxq;
16018 	struct lpfc_hba *phba = ndlp->phba;
16019 	int rc;
16020 
16021 	/* The port is notified of the header region via a mailbox command. */
16022 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16023 	if (!mboxq)
16024 		return -ENOMEM;
16025 
16026 	/* Post all rpi memory regions to the port. */
16027 	lpfc_resume_rpi(mboxq, ndlp);
16028 	if (cmpl) {
16029 		mboxq->mbox_cmpl = cmpl;
16030 		mboxq->context1 = arg;
16031 		mboxq->context2 = ndlp;
16032 	} else
16033 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16034 	mboxq->vport = ndlp->vport;
16035 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16036 	if (rc == MBX_NOT_FINISHED) {
16037 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16038 				"2010 Resume RPI Mailbox failed "
16039 				"status %d, mbxStatus x%x\n", rc,
16040 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
16041 		mempool_free(mboxq, phba->mbox_mem_pool);
16042 		return -EIO;
16043 	}
16044 	return 0;
16045 }
16046 
16047 /**
16048  * lpfc_sli4_init_vpi - Initialize a vpi with the port
16049  * @vport: Pointer to the vport for which the vpi is being initialized
16050  *
16051  * This routine is invoked to activate a vpi with the port.
16052  *
16053  * Returns:
16054  *    0 success
16055  *    -Evalue otherwise
16056  **/
16057 int
16058 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
16059 {
16060 	LPFC_MBOXQ_t *mboxq;
16061 	int rc = 0;
16062 	int retval = MBX_SUCCESS;
16063 	uint32_t mbox_tmo;
16064 	struct lpfc_hba *phba = vport->phba;
16065 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16066 	if (!mboxq)
16067 		return -ENOMEM;
16068 	lpfc_init_vpi(phba, mboxq, vport->vpi);
16069 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
16070 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
16071 	if (rc != MBX_SUCCESS) {
16072 		lpfc_printf_vlog(vport, KERN_ERR, LOG_SLI,
16073 				"2022 INIT VPI Mailbox failed "
16074 				"status %d, mbxStatus x%x\n", rc,
16075 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
16076 		retval = -EIO;
16077 	}
16078 	if (rc != MBX_TIMEOUT)
16079 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
16080 
16081 	return retval;
16082 }
16083 
16084 /**
16085  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
16086  * @phba: pointer to lpfc hba data structure.
16087  * @mboxq: Pointer to mailbox object.
16088  *
16089  * This routine is invoked to manually add a single FCF record. The caller
16090  * must pass a completely initialized FCF_Record.  This routine takes
16091  * care of the nonembedded mailbox operations.
16092  **/
16093 static void
16094 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
16095 {
16096 	void *virt_addr;
16097 	union lpfc_sli4_cfg_shdr *shdr;
16098 	uint32_t shdr_status, shdr_add_status;
16099 
16100 	virt_addr = mboxq->sge_array->addr[0];
16101 	/* The IOCTL status is embedded in the mailbox subheader. */
16102 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
16103 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16104 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16105 
16106 	if ((shdr_status || shdr_add_status) &&
16107 		(shdr_status != STATUS_FCF_IN_USE))
16108 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16109 			"2558 ADD_FCF_RECORD mailbox failed with "
16110 			"status x%x add_status x%x\n",
16111 			shdr_status, shdr_add_status);
16112 
16113 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
16114 }
16115 
16116 /**
16117  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
16118  * @phba: pointer to lpfc hba data structure.
16119  * @fcf_record:  pointer to the initialized fcf record to add.
16120  *
16121  * This routine is invoked to manually add a single FCF record. The caller
16122  * must pass a completely initialized FCF_Record.  This routine takes
16123  * care of the nonembedded mailbox operations.
16124  **/
16125 int
16126 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
16127 {
16128 	int rc = 0;
16129 	LPFC_MBOXQ_t *mboxq;
16130 	uint8_t *bytep;
16131 	void *virt_addr;
16132 	struct lpfc_mbx_sge sge;
16133 	uint32_t alloc_len, req_len;
16134 	uint32_t fcfindex;
16135 
16136 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16137 	if (!mboxq) {
16138 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16139 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
16140 		return -ENOMEM;
16141 	}
16142 
16143 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
16144 		  sizeof(uint32_t);
16145 
16146 	/* Allocate DMA memory and set up the non-embedded mailbox command */
16147 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
16148 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
16149 				     req_len, LPFC_SLI4_MBX_NEMBED);
16150 	if (alloc_len < req_len) {
16151 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16152 			"2523 Allocated DMA memory size (x%x) is "
16153 			"less than the requested DMA memory "
16154 			"size (x%x)\n", alloc_len, req_len);
16155 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
16156 		return -ENOMEM;
16157 	}
16158 
16159 	/*
16160 	 * Get the first SGE entry from the non-embedded DMA memory.  This
16161 	 * routine only uses a single SGE.
16162 	 */
16163 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
16164 	virt_addr = mboxq->sge_array->addr[0];
16165 	/*
16166 	 * Configure the FCF record for FCFI 0.  This is the driver's
16167 	 * hardcoded default and gets used in nonFIP mode.
16168 	 */
16169 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
16170 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
16171 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
16172 
16173 	/*
16174 	 * Copy the fcf_index and the FCF Record Data. The data starts after
16175 	 * the FCoE header plus word10. The data copy needs to be endian
16176 	 * correct.
16177 	 */
16178 	bytep += sizeof(uint32_t);
16179 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
16180 	mboxq->vport = phba->pport;
16181 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
16182 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16183 	if (rc == MBX_NOT_FINISHED) {
16184 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16185 			"2515 ADD_FCF_RECORD mailbox failed with "
16186 			"status 0x%x\n", rc);
16187 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
16188 		rc = -EIO;
16189 	} else
16190 		rc = 0;
16191 
16192 	return rc;
16193 }
16194 
16195 /**
16196  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
16197  * @phba: pointer to lpfc hba data structure.
16198  * @fcf_record:  pointer to the fcf record to write the default data.
16199  * @fcf_index: FCF table entry index.
16200  *
16201  * This routine is invoked to build the driver's default FCF record.  The
16202  * values used are hardcoded.  This routine handles memory initialization.
16203  *
16204  **/
16205 void
16206 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
16207 				struct fcf_record *fcf_record,
16208 				uint16_t fcf_index)
16209 {
16210 	memset(fcf_record, 0, sizeof(struct fcf_record));
16211 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
16212 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
16213 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
16214 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
16215 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
16216 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
16217 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
16218 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
16219 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
16220 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
16221 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
16222 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
16223 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
16224 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
16225 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
16226 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
16227 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
16228 	/* Set the VLAN bit map */
16229 	if (phba->valid_vlan) {
16230 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
16231 			= 1 << (phba->vlan_id % 8);
16232 	}
16233 }
16234 
16235 /**
16236  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
16237  * @phba: pointer to lpfc hba data structure.
16238  * @fcf_index: FCF table entry offset.
16239  *
16240  * This routine is invoked to scan the entire FCF table by reading FCF
16241  * record and processing it one at a time starting from the @fcf_index
16242  * for initial FCF discovery or fast FCF failover rediscovery.
16243  *
16244  * Return 0 if the mailbox command is submitted successfully, none 0
16245  * otherwise.
16246  **/
16247 int
16248 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
16249 {
16250 	int rc = 0, error;
16251 	LPFC_MBOXQ_t *mboxq;
16252 
16253 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
16254 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
16255 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16256 	if (!mboxq) {
16257 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16258 				"2000 Failed to allocate mbox for "
16259 				"READ_FCF cmd\n");
16260 		error = -ENOMEM;
16261 		goto fail_fcf_scan;
16262 	}
16263 	/* Construct the read FCF record mailbox command */
16264 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
16265 	if (rc) {
16266 		error = -EINVAL;
16267 		goto fail_fcf_scan;
16268 	}
16269 	/* Issue the mailbox command asynchronously */
16270 	mboxq->vport = phba->pport;
16271 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
16272 
16273 	spin_lock_irq(&phba->hbalock);
16274 	phba->hba_flag |= FCF_TS_INPROG;
16275 	spin_unlock_irq(&phba->hbalock);
16276 
16277 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16278 	if (rc == MBX_NOT_FINISHED)
16279 		error = -EIO;
16280 	else {
16281 		/* Reset eligible FCF count for new scan */
16282 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
16283 			phba->fcf.eligible_fcf_cnt = 0;
16284 		error = 0;
16285 	}
16286 fail_fcf_scan:
16287 	if (error) {
16288 		if (mboxq)
16289 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
16290 		/* FCF scan failed, clear FCF_TS_INPROG flag */
16291 		spin_lock_irq(&phba->hbalock);
16292 		phba->hba_flag &= ~FCF_TS_INPROG;
16293 		spin_unlock_irq(&phba->hbalock);
16294 	}
16295 	return error;
16296 }
16297 
16298 /**
16299  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
16300  * @phba: pointer to lpfc hba data structure.
16301  * @fcf_index: FCF table entry offset.
16302  *
16303  * This routine is invoked to read an FCF record indicated by @fcf_index
16304  * and to use it for FLOGI roundrobin FCF failover.
16305  *
16306  * Return 0 if the mailbox command is submitted successfully, none 0
16307  * otherwise.
16308  **/
16309 int
16310 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
16311 {
16312 	int rc = 0, error;
16313 	LPFC_MBOXQ_t *mboxq;
16314 
16315 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16316 	if (!mboxq) {
16317 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
16318 				"2763 Failed to allocate mbox for "
16319 				"READ_FCF cmd\n");
16320 		error = -ENOMEM;
16321 		goto fail_fcf_read;
16322 	}
16323 	/* Construct the read FCF record mailbox command */
16324 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
16325 	if (rc) {
16326 		error = -EINVAL;
16327 		goto fail_fcf_read;
16328 	}
16329 	/* Issue the mailbox command asynchronously */
16330 	mboxq->vport = phba->pport;
16331 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
16332 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16333 	if (rc == MBX_NOT_FINISHED)
16334 		error = -EIO;
16335 	else
16336 		error = 0;
16337 
16338 fail_fcf_read:
16339 	if (error && mboxq)
16340 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
16341 	return error;
16342 }
16343 
16344 /**
16345  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
16346  * @phba: pointer to lpfc hba data structure.
16347  * @fcf_index: FCF table entry offset.
16348  *
16349  * This routine is invoked to read an FCF record indicated by @fcf_index to
16350  * determine whether it's eligible for FLOGI roundrobin failover list.
16351  *
16352  * Return 0 if the mailbox command is submitted successfully, none 0
16353  * otherwise.
16354  **/
16355 int
16356 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
16357 {
16358 	int rc = 0, error;
16359 	LPFC_MBOXQ_t *mboxq;
16360 
16361 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16362 	if (!mboxq) {
16363 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
16364 				"2758 Failed to allocate mbox for "
16365 				"READ_FCF cmd\n");
16366 				error = -ENOMEM;
16367 				goto fail_fcf_read;
16368 	}
16369 	/* Construct the read FCF record mailbox command */
16370 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
16371 	if (rc) {
16372 		error = -EINVAL;
16373 		goto fail_fcf_read;
16374 	}
16375 	/* Issue the mailbox command asynchronously */
16376 	mboxq->vport = phba->pport;
16377 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
16378 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16379 	if (rc == MBX_NOT_FINISHED)
16380 		error = -EIO;
16381 	else
16382 		error = 0;
16383 
16384 fail_fcf_read:
16385 	if (error && mboxq)
16386 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
16387 	return error;
16388 }
16389 
16390 /**
16391  * lpfc_check_next_fcf_pri_level
16392  * phba pointer to the lpfc_hba struct for this port.
16393  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
16394  * routine when the rr_bmask is empty. The FCF indecies are put into the
16395  * rr_bmask based on their priority level. Starting from the highest priority
16396  * to the lowest. The most likely FCF candidate will be in the highest
16397  * priority group. When this routine is called it searches the fcf_pri list for
16398  * next lowest priority group and repopulates the rr_bmask with only those
16399  * fcf_indexes.
16400  * returns:
16401  * 1=success 0=failure
16402  **/
16403 static int
16404 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
16405 {
16406 	uint16_t next_fcf_pri;
16407 	uint16_t last_index;
16408 	struct lpfc_fcf_pri *fcf_pri;
16409 	int rc;
16410 	int ret = 0;
16411 
16412 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
16413 			LPFC_SLI4_FCF_TBL_INDX_MAX);
16414 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16415 			"3060 Last IDX %d\n", last_index);
16416 
16417 	/* Verify the priority list has 2 or more entries */
16418 	spin_lock_irq(&phba->hbalock);
16419 	if (list_empty(&phba->fcf.fcf_pri_list) ||
16420 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
16421 		spin_unlock_irq(&phba->hbalock);
16422 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16423 			"3061 Last IDX %d\n", last_index);
16424 		return 0; /* Empty rr list */
16425 	}
16426 	spin_unlock_irq(&phba->hbalock);
16427 
16428 	next_fcf_pri = 0;
16429 	/*
16430 	 * Clear the rr_bmask and set all of the bits that are at this
16431 	 * priority.
16432 	 */
16433 	memset(phba->fcf.fcf_rr_bmask, 0,
16434 			sizeof(*phba->fcf.fcf_rr_bmask));
16435 	spin_lock_irq(&phba->hbalock);
16436 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
16437 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
16438 			continue;
16439 		/*
16440 		 * the 1st priority that has not FLOGI failed
16441 		 * will be the highest.
16442 		 */
16443 		if (!next_fcf_pri)
16444 			next_fcf_pri = fcf_pri->fcf_rec.priority;
16445 		spin_unlock_irq(&phba->hbalock);
16446 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
16447 			rc = lpfc_sli4_fcf_rr_index_set(phba,
16448 						fcf_pri->fcf_rec.fcf_index);
16449 			if (rc)
16450 				return 0;
16451 		}
16452 		spin_lock_irq(&phba->hbalock);
16453 	}
16454 	/*
16455 	 * if next_fcf_pri was not set above and the list is not empty then
16456 	 * we have failed flogis on all of them. So reset flogi failed
16457 	 * and start at the beginning.
16458 	 */
16459 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
16460 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
16461 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
16462 			/*
16463 			 * the 1st priority that has not FLOGI failed
16464 			 * will be the highest.
16465 			 */
16466 			if (!next_fcf_pri)
16467 				next_fcf_pri = fcf_pri->fcf_rec.priority;
16468 			spin_unlock_irq(&phba->hbalock);
16469 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
16470 				rc = lpfc_sli4_fcf_rr_index_set(phba,
16471 						fcf_pri->fcf_rec.fcf_index);
16472 				if (rc)
16473 					return 0;
16474 			}
16475 			spin_lock_irq(&phba->hbalock);
16476 		}
16477 	} else
16478 		ret = 1;
16479 	spin_unlock_irq(&phba->hbalock);
16480 
16481 	return ret;
16482 }
16483 /**
16484  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
16485  * @phba: pointer to lpfc hba data structure.
16486  *
16487  * This routine is to get the next eligible FCF record index in a round
16488  * robin fashion. If the next eligible FCF record index equals to the
16489  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
16490  * shall be returned, otherwise, the next eligible FCF record's index
16491  * shall be returned.
16492  **/
16493 uint16_t
16494 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
16495 {
16496 	uint16_t next_fcf_index;
16497 
16498 initial_priority:
16499 	/* Search start from next bit of currently registered FCF index */
16500 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
16501 
16502 next_priority:
16503 	/* Determine the next fcf index to check */
16504 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
16505 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
16506 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
16507 				       next_fcf_index);
16508 
16509 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
16510 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
16511 		/*
16512 		 * If we have wrapped then we need to clear the bits that
16513 		 * have been tested so that we can detect when we should
16514 		 * change the priority level.
16515 		 */
16516 		next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
16517 					       LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
16518 	}
16519 
16520 
16521 	/* Check roundrobin failover list empty condition */
16522 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
16523 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
16524 		/*
16525 		 * If next fcf index is not found check if there are lower
16526 		 * Priority level fcf's in the fcf_priority list.
16527 		 * Set up the rr_bmask with all of the avaiable fcf bits
16528 		 * at that level and continue the selection process.
16529 		 */
16530 		if (lpfc_check_next_fcf_pri_level(phba))
16531 			goto initial_priority;
16532 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
16533 				"2844 No roundrobin failover FCF available\n");
16534 		if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX)
16535 			return LPFC_FCOE_FCF_NEXT_NONE;
16536 		else {
16537 			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
16538 				"3063 Only FCF available idx %d, flag %x\n",
16539 				next_fcf_index,
16540 			phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag);
16541 			return next_fcf_index;
16542 		}
16543 	}
16544 
16545 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
16546 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
16547 		LPFC_FCF_FLOGI_FAILED) {
16548 		if (list_is_singular(&phba->fcf.fcf_pri_list))
16549 			return LPFC_FCOE_FCF_NEXT_NONE;
16550 
16551 		goto next_priority;
16552 	}
16553 
16554 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16555 			"2845 Get next roundrobin failover FCF (x%x)\n",
16556 			next_fcf_index);
16557 
16558 	return next_fcf_index;
16559 }
16560 
16561 /**
16562  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
16563  * @phba: pointer to lpfc hba data structure.
16564  *
16565  * This routine sets the FCF record index in to the eligible bmask for
16566  * roundrobin failover search. It checks to make sure that the index
16567  * does not go beyond the range of the driver allocated bmask dimension
16568  * before setting the bit.
16569  *
16570  * Returns 0 if the index bit successfully set, otherwise, it returns
16571  * -EINVAL.
16572  **/
16573 int
16574 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
16575 {
16576 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
16577 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16578 				"2610 FCF (x%x) reached driver's book "
16579 				"keeping dimension:x%x\n",
16580 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
16581 		return -EINVAL;
16582 	}
16583 	/* Set the eligible FCF record index bmask */
16584 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
16585 
16586 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16587 			"2790 Set FCF (x%x) to roundrobin FCF failover "
16588 			"bmask\n", fcf_index);
16589 
16590 	return 0;
16591 }
16592 
16593 /**
16594  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
16595  * @phba: pointer to lpfc hba data structure.
16596  *
16597  * This routine clears the FCF record index from the eligible bmask for
16598  * roundrobin failover search. It checks to make sure that the index
16599  * does not go beyond the range of the driver allocated bmask dimension
16600  * before clearing the bit.
16601  **/
16602 void
16603 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
16604 {
16605 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
16606 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
16607 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16608 				"2762 FCF (x%x) reached driver's book "
16609 				"keeping dimension:x%x\n",
16610 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
16611 		return;
16612 	}
16613 	/* Clear the eligible FCF record index bmask */
16614 	spin_lock_irq(&phba->hbalock);
16615 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
16616 				 list) {
16617 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
16618 			list_del_init(&fcf_pri->list);
16619 			break;
16620 		}
16621 	}
16622 	spin_unlock_irq(&phba->hbalock);
16623 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
16624 
16625 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16626 			"2791 Clear FCF (x%x) from roundrobin failover "
16627 			"bmask\n", fcf_index);
16628 }
16629 
16630 /**
16631  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
16632  * @phba: pointer to lpfc hba data structure.
16633  *
16634  * This routine is the completion routine for the rediscover FCF table mailbox
16635  * command. If the mailbox command returned failure, it will try to stop the
16636  * FCF rediscover wait timer.
16637  **/
16638 static void
16639 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
16640 {
16641 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
16642 	uint32_t shdr_status, shdr_add_status;
16643 
16644 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
16645 
16646 	shdr_status = bf_get(lpfc_mbox_hdr_status,
16647 			     &redisc_fcf->header.cfg_shdr.response);
16648 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
16649 			     &redisc_fcf->header.cfg_shdr.response);
16650 	if (shdr_status || shdr_add_status) {
16651 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16652 				"2746 Requesting for FCF rediscovery failed "
16653 				"status x%x add_status x%x\n",
16654 				shdr_status, shdr_add_status);
16655 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
16656 			spin_lock_irq(&phba->hbalock);
16657 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
16658 			spin_unlock_irq(&phba->hbalock);
16659 			/*
16660 			 * CVL event triggered FCF rediscover request failed,
16661 			 * last resort to re-try current registered FCF entry.
16662 			 */
16663 			lpfc_retry_pport_discovery(phba);
16664 		} else {
16665 			spin_lock_irq(&phba->hbalock);
16666 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
16667 			spin_unlock_irq(&phba->hbalock);
16668 			/*
16669 			 * DEAD FCF event triggered FCF rediscover request
16670 			 * failed, last resort to fail over as a link down
16671 			 * to FCF registration.
16672 			 */
16673 			lpfc_sli4_fcf_dead_failthrough(phba);
16674 		}
16675 	} else {
16676 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16677 				"2775 Start FCF rediscover quiescent timer\n");
16678 		/*
16679 		 * Start FCF rediscovery wait timer for pending FCF
16680 		 * before rescan FCF record table.
16681 		 */
16682 		lpfc_fcf_redisc_wait_start_timer(phba);
16683 	}
16684 
16685 	mempool_free(mbox, phba->mbox_mem_pool);
16686 }
16687 
16688 /**
16689  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
16690  * @phba: pointer to lpfc hba data structure.
16691  *
16692  * This routine is invoked to request for rediscovery of the entire FCF table
16693  * by the port.
16694  **/
16695 int
16696 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
16697 {
16698 	LPFC_MBOXQ_t *mbox;
16699 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
16700 	int rc, length;
16701 
16702 	/* Cancel retry delay timers to all vports before FCF rediscover */
16703 	lpfc_cancel_all_vport_retry_delay_timer(phba);
16704 
16705 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16706 	if (!mbox) {
16707 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16708 				"2745 Failed to allocate mbox for "
16709 				"requesting FCF rediscover.\n");
16710 		return -ENOMEM;
16711 	}
16712 
16713 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
16714 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16715 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16716 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
16717 			 length, LPFC_SLI4_MBX_EMBED);
16718 
16719 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
16720 	/* Set count to 0 for invalidating the entire FCF database */
16721 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
16722 
16723 	/* Issue the mailbox command asynchronously */
16724 	mbox->vport = phba->pport;
16725 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
16726 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
16727 
16728 	if (rc == MBX_NOT_FINISHED) {
16729 		mempool_free(mbox, phba->mbox_mem_pool);
16730 		return -EIO;
16731 	}
16732 	return 0;
16733 }
16734 
16735 /**
16736  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
16737  * @phba: pointer to lpfc hba data structure.
16738  *
16739  * This function is the failover routine as a last resort to the FCF DEAD
16740  * event when driver failed to perform fast FCF failover.
16741  **/
16742 void
16743 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
16744 {
16745 	uint32_t link_state;
16746 
16747 	/*
16748 	 * Last resort as FCF DEAD event failover will treat this as
16749 	 * a link down, but save the link state because we don't want
16750 	 * it to be changed to Link Down unless it is already down.
16751 	 */
16752 	link_state = phba->link_state;
16753 	lpfc_linkdown(phba);
16754 	phba->link_state = link_state;
16755 
16756 	/* Unregister FCF if no devices connected to it */
16757 	lpfc_unregister_unused_fcf(phba);
16758 }
16759 
16760 /**
16761  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
16762  * @phba: pointer to lpfc hba data structure.
16763  * @rgn23_data: pointer to configure region 23 data.
16764  *
16765  * This function gets SLI3 port configure region 23 data through memory dump
16766  * mailbox command. When it successfully retrieves data, the size of the data
16767  * will be returned, otherwise, 0 will be returned.
16768  **/
16769 static uint32_t
16770 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
16771 {
16772 	LPFC_MBOXQ_t *pmb = NULL;
16773 	MAILBOX_t *mb;
16774 	uint32_t offset = 0;
16775 	int rc;
16776 
16777 	if (!rgn23_data)
16778 		return 0;
16779 
16780 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16781 	if (!pmb) {
16782 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16783 				"2600 failed to allocate mailbox memory\n");
16784 		return 0;
16785 	}
16786 	mb = &pmb->u.mb;
16787 
16788 	do {
16789 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
16790 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
16791 
16792 		if (rc != MBX_SUCCESS) {
16793 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16794 					"2601 failed to read config "
16795 					"region 23, rc 0x%x Status 0x%x\n",
16796 					rc, mb->mbxStatus);
16797 			mb->un.varDmp.word_cnt = 0;
16798 		}
16799 		/*
16800 		 * dump mem may return a zero when finished or we got a
16801 		 * mailbox error, either way we are done.
16802 		 */
16803 		if (mb->un.varDmp.word_cnt == 0)
16804 			break;
16805 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
16806 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
16807 
16808 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
16809 				       rgn23_data + offset,
16810 				       mb->un.varDmp.word_cnt);
16811 		offset += mb->un.varDmp.word_cnt;
16812 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
16813 
16814 	mempool_free(pmb, phba->mbox_mem_pool);
16815 	return offset;
16816 }
16817 
16818 /**
16819  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
16820  * @phba: pointer to lpfc hba data structure.
16821  * @rgn23_data: pointer to configure region 23 data.
16822  *
16823  * This function gets SLI4 port configure region 23 data through memory dump
16824  * mailbox command. When it successfully retrieves data, the size of the data
16825  * will be returned, otherwise, 0 will be returned.
16826  **/
16827 static uint32_t
16828 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
16829 {
16830 	LPFC_MBOXQ_t *mboxq = NULL;
16831 	struct lpfc_dmabuf *mp = NULL;
16832 	struct lpfc_mqe *mqe;
16833 	uint32_t data_length = 0;
16834 	int rc;
16835 
16836 	if (!rgn23_data)
16837 		return 0;
16838 
16839 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16840 	if (!mboxq) {
16841 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16842 				"3105 failed to allocate mailbox memory\n");
16843 		return 0;
16844 	}
16845 
16846 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
16847 		goto out;
16848 	mqe = &mboxq->u.mqe;
16849 	mp = (struct lpfc_dmabuf *) mboxq->context1;
16850 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
16851 	if (rc)
16852 		goto out;
16853 	data_length = mqe->un.mb_words[5];
16854 	if (data_length == 0)
16855 		goto out;
16856 	if (data_length > DMP_RGN23_SIZE) {
16857 		data_length = 0;
16858 		goto out;
16859 	}
16860 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
16861 out:
16862 	mempool_free(mboxq, phba->mbox_mem_pool);
16863 	if (mp) {
16864 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
16865 		kfree(mp);
16866 	}
16867 	return data_length;
16868 }
16869 
16870 /**
16871  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
16872  * @phba: pointer to lpfc hba data structure.
16873  *
16874  * This function read region 23 and parse TLV for port status to
16875  * decide if the user disaled the port. If the TLV indicates the
16876  * port is disabled, the hba_flag is set accordingly.
16877  **/
16878 void
16879 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
16880 {
16881 	uint8_t *rgn23_data = NULL;
16882 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
16883 	uint32_t offset = 0;
16884 
16885 	/* Get adapter Region 23 data */
16886 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
16887 	if (!rgn23_data)
16888 		goto out;
16889 
16890 	if (phba->sli_rev < LPFC_SLI_REV4)
16891 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
16892 	else {
16893 		if_type = bf_get(lpfc_sli_intf_if_type,
16894 				 &phba->sli4_hba.sli_intf);
16895 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
16896 			goto out;
16897 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
16898 	}
16899 
16900 	if (!data_size)
16901 		goto out;
16902 
16903 	/* Check the region signature first */
16904 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
16905 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16906 			"2619 Config region 23 has bad signature\n");
16907 			goto out;
16908 	}
16909 	offset += 4;
16910 
16911 	/* Check the data structure version */
16912 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
16913 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16914 			"2620 Config region 23 has bad version\n");
16915 		goto out;
16916 	}
16917 	offset += 4;
16918 
16919 	/* Parse TLV entries in the region */
16920 	while (offset < data_size) {
16921 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
16922 			break;
16923 		/*
16924 		 * If the TLV is not driver specific TLV or driver id is
16925 		 * not linux driver id, skip the record.
16926 		 */
16927 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
16928 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
16929 		    (rgn23_data[offset + 3] != 0)) {
16930 			offset += rgn23_data[offset + 1] * 4 + 4;
16931 			continue;
16932 		}
16933 
16934 		/* Driver found a driver specific TLV in the config region */
16935 		sub_tlv_len = rgn23_data[offset + 1] * 4;
16936 		offset += 4;
16937 		tlv_offset = 0;
16938 
16939 		/*
16940 		 * Search for configured port state sub-TLV.
16941 		 */
16942 		while ((offset < data_size) &&
16943 			(tlv_offset < sub_tlv_len)) {
16944 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
16945 				offset += 4;
16946 				tlv_offset += 4;
16947 				break;
16948 			}
16949 			if (rgn23_data[offset] != PORT_STE_TYPE) {
16950 				offset += rgn23_data[offset + 1] * 4 + 4;
16951 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
16952 				continue;
16953 			}
16954 
16955 			/* This HBA contains PORT_STE configured */
16956 			if (!rgn23_data[offset + 2])
16957 				phba->hba_flag |= LINK_DISABLED;
16958 
16959 			goto out;
16960 		}
16961 	}
16962 
16963 out:
16964 	kfree(rgn23_data);
16965 	return;
16966 }
16967 
16968 /**
16969  * lpfc_wr_object - write an object to the firmware
16970  * @phba: HBA structure that indicates port to create a queue on.
16971  * @dmabuf_list: list of dmabufs to write to the port.
16972  * @size: the total byte value of the objects to write to the port.
16973  * @offset: the current offset to be used to start the transfer.
16974  *
16975  * This routine will create a wr_object mailbox command to send to the port.
16976  * the mailbox command will be constructed using the dma buffers described in
16977  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
16978  * BDEs that the imbedded mailbox can support. The @offset variable will be
16979  * used to indicate the starting offset of the transfer and will also return
16980  * the offset after the write object mailbox has completed. @size is used to
16981  * determine the end of the object and whether the eof bit should be set.
16982  *
16983  * Return 0 is successful and offset will contain the the new offset to use
16984  * for the next write.
16985  * Return negative value for error cases.
16986  **/
16987 int
16988 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
16989 	       uint32_t size, uint32_t *offset)
16990 {
16991 	struct lpfc_mbx_wr_object *wr_object;
16992 	LPFC_MBOXQ_t *mbox;
16993 	int rc = 0, i = 0;
16994 	uint32_t shdr_status, shdr_add_status;
16995 	uint32_t mbox_tmo;
16996 	union lpfc_sli4_cfg_shdr *shdr;
16997 	struct lpfc_dmabuf *dmabuf;
16998 	uint32_t written = 0;
16999 
17000 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17001 	if (!mbox)
17002 		return -ENOMEM;
17003 
17004 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17005 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
17006 			sizeof(struct lpfc_mbx_wr_object) -
17007 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
17008 
17009 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
17010 	wr_object->u.request.write_offset = *offset;
17011 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
17012 	wr_object->u.request.object_name[0] =
17013 		cpu_to_le32(wr_object->u.request.object_name[0]);
17014 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
17015 	list_for_each_entry(dmabuf, dmabuf_list, list) {
17016 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
17017 			break;
17018 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
17019 		wr_object->u.request.bde[i].addrHigh =
17020 			putPaddrHigh(dmabuf->phys);
17021 		if (written + SLI4_PAGE_SIZE >= size) {
17022 			wr_object->u.request.bde[i].tus.f.bdeSize =
17023 				(size - written);
17024 			written += (size - written);
17025 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
17026 		} else {
17027 			wr_object->u.request.bde[i].tus.f.bdeSize =
17028 				SLI4_PAGE_SIZE;
17029 			written += SLI4_PAGE_SIZE;
17030 		}
17031 		i++;
17032 	}
17033 	wr_object->u.request.bde_count = i;
17034 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
17035 	if (!phba->sli4_hba.intr_enable)
17036 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17037 	else {
17038 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17039 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17040 	}
17041 	/* The IOCTL status is embedded in the mailbox subheader. */
17042 	shdr = (union lpfc_sli4_cfg_shdr *) &wr_object->header.cfg_shdr;
17043 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17044 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17045 	if (rc != MBX_TIMEOUT)
17046 		mempool_free(mbox, phba->mbox_mem_pool);
17047 	if (shdr_status || shdr_add_status || rc) {
17048 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17049 				"3025 Write Object mailbox failed with "
17050 				"status x%x add_status x%x, mbx status x%x\n",
17051 				shdr_status, shdr_add_status, rc);
17052 		rc = -ENXIO;
17053 	} else
17054 		*offset += wr_object->u.response.actual_write_length;
17055 	return rc;
17056 }
17057 
17058 /**
17059  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
17060  * @vport: pointer to vport data structure.
17061  *
17062  * This function iterate through the mailboxq and clean up all REG_LOGIN
17063  * and REG_VPI mailbox commands associated with the vport. This function
17064  * is called when driver want to restart discovery of the vport due to
17065  * a Clear Virtual Link event.
17066  **/
17067 void
17068 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
17069 {
17070 	struct lpfc_hba *phba = vport->phba;
17071 	LPFC_MBOXQ_t *mb, *nextmb;
17072 	struct lpfc_dmabuf *mp;
17073 	struct lpfc_nodelist *ndlp;
17074 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
17075 	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
17076 	LIST_HEAD(mbox_cmd_list);
17077 	uint8_t restart_loop;
17078 
17079 	/* Clean up internally queued mailbox commands with the vport */
17080 	spin_lock_irq(&phba->hbalock);
17081 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
17082 		if (mb->vport != vport)
17083 			continue;
17084 
17085 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
17086 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
17087 			continue;
17088 
17089 		list_del(&mb->list);
17090 		list_add_tail(&mb->list, &mbox_cmd_list);
17091 	}
17092 	/* Clean up active mailbox command with the vport */
17093 	mb = phba->sli.mbox_active;
17094 	if (mb && (mb->vport == vport)) {
17095 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
17096 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
17097 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17098 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
17099 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->context2;
17100 			/* Put reference count for delayed processing */
17101 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
17102 			/* Unregister the RPI when mailbox complete */
17103 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
17104 		}
17105 	}
17106 	/* Cleanup any mailbox completions which are not yet processed */
17107 	do {
17108 		restart_loop = 0;
17109 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
17110 			/*
17111 			 * If this mailox is already processed or it is
17112 			 * for another vport ignore it.
17113 			 */
17114 			if ((mb->vport != vport) ||
17115 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
17116 				continue;
17117 
17118 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
17119 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
17120 				continue;
17121 
17122 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17123 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
17124 				ndlp = (struct lpfc_nodelist *)mb->context2;
17125 				/* Unregister the RPI when mailbox complete */
17126 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
17127 				restart_loop = 1;
17128 				spin_unlock_irq(&phba->hbalock);
17129 				spin_lock(shost->host_lock);
17130 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
17131 				spin_unlock(shost->host_lock);
17132 				spin_lock_irq(&phba->hbalock);
17133 				break;
17134 			}
17135 		}
17136 	} while (restart_loop);
17137 
17138 	spin_unlock_irq(&phba->hbalock);
17139 
17140 	/* Release the cleaned-up mailbox commands */
17141 	while (!list_empty(&mbox_cmd_list)) {
17142 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
17143 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
17144 			mp = (struct lpfc_dmabuf *) (mb->context1);
17145 			if (mp) {
17146 				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
17147 				kfree(mp);
17148 			}
17149 			ndlp = (struct lpfc_nodelist *) mb->context2;
17150 			mb->context2 = NULL;
17151 			if (ndlp) {
17152 				spin_lock(shost->host_lock);
17153 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
17154 				spin_unlock(shost->host_lock);
17155 				lpfc_nlp_put(ndlp);
17156 			}
17157 		}
17158 		mempool_free(mb, phba->mbox_mem_pool);
17159 	}
17160 
17161 	/* Release the ndlp with the cleaned-up active mailbox command */
17162 	if (act_mbx_ndlp) {
17163 		spin_lock(shost->host_lock);
17164 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
17165 		spin_unlock(shost->host_lock);
17166 		lpfc_nlp_put(act_mbx_ndlp);
17167 	}
17168 }
17169 
17170 /**
17171  * lpfc_drain_txq - Drain the txq
17172  * @phba: Pointer to HBA context object.
17173  *
17174  * This function attempt to submit IOCBs on the txq
17175  * to the adapter.  For SLI4 adapters, the txq contains
17176  * ELS IOCBs that have been deferred because the there
17177  * are no SGLs.  This congestion can occur with large
17178  * vport counts during node discovery.
17179  **/
17180 
17181 uint32_t
17182 lpfc_drain_txq(struct lpfc_hba *phba)
17183 {
17184 	LIST_HEAD(completions);
17185 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
17186 	struct lpfc_iocbq *piocbq = NULL;
17187 	unsigned long iflags = 0;
17188 	char *fail_msg = NULL;
17189 	struct lpfc_sglq *sglq;
17190 	union lpfc_wqe wqe;
17191 	uint32_t txq_cnt = 0;
17192 
17193 	spin_lock_irqsave(&pring->ring_lock, iflags);
17194 	list_for_each_entry(piocbq, &pring->txq, list) {
17195 		txq_cnt++;
17196 	}
17197 
17198 	if (txq_cnt > pring->txq_max)
17199 		pring->txq_max = txq_cnt;
17200 
17201 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
17202 
17203 	while (!list_empty(&pring->txq)) {
17204 		spin_lock_irqsave(&pring->ring_lock, iflags);
17205 
17206 		piocbq = lpfc_sli_ringtx_get(phba, pring);
17207 		if (!piocbq) {
17208 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
17209 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17210 				"2823 txq empty and txq_cnt is %d\n ",
17211 				txq_cnt);
17212 			break;
17213 		}
17214 		sglq = __lpfc_sli_get_sglq(phba, piocbq);
17215 		if (!sglq) {
17216 			__lpfc_sli_ringtx_put(phba, pring, piocbq);
17217 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
17218 			break;
17219 		}
17220 		txq_cnt--;
17221 
17222 		/* The xri and iocb resources secured,
17223 		 * attempt to issue request
17224 		 */
17225 		piocbq->sli4_lxritag = sglq->sli4_lxritag;
17226 		piocbq->sli4_xritag = sglq->sli4_xritag;
17227 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
17228 			fail_msg = "to convert bpl to sgl";
17229 		else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
17230 			fail_msg = "to convert iocb to wqe";
17231 		else if (lpfc_sli4_wq_put(phba->sli4_hba.els_wq, &wqe))
17232 			fail_msg = " - Wq is full";
17233 		else
17234 			lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
17235 
17236 		if (fail_msg) {
17237 			/* Failed means we can't issue and need to cancel */
17238 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17239 					"2822 IOCB failed %s iotag 0x%x "
17240 					"xri 0x%x\n",
17241 					fail_msg,
17242 					piocbq->iotag, piocbq->sli4_xritag);
17243 			list_add_tail(&piocbq->list, &completions);
17244 		}
17245 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
17246 	}
17247 
17248 	/* Cancel all the IOCBs that cannot be issued */
17249 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
17250 				IOERR_SLI_ABORTED);
17251 
17252 	return txq_cnt;
17253 }
17254