xref: /linux/drivers/scsi/lpfc/lpfc_sli.c (revision 32786fdc9506aeba98278c1844d4bfb766863832)
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 #include "lpfc_version.h"
51 
52 /* There are only four IOCB completion types. */
53 typedef enum _lpfc_iocb_type {
54 	LPFC_UNKNOWN_IOCB,
55 	LPFC_UNSOL_IOCB,
56 	LPFC_SOL_IOCB,
57 	LPFC_ABORT_IOCB
58 } lpfc_iocb_type;
59 
60 
61 /* Provide function prototypes local to this module. */
62 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
63 				  uint32_t);
64 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
65 			      uint8_t *, uint32_t *);
66 static struct lpfc_iocbq *lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *,
67 							 struct lpfc_iocbq *);
68 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
69 				      struct hbq_dmabuf *);
70 static int lpfc_sli4_fp_handle_wcqe(struct lpfc_hba *, struct lpfc_queue *,
71 				    struct lpfc_cqe *);
72 static int lpfc_sli4_post_els_sgl_list(struct lpfc_hba *, struct list_head *,
73 				       int);
74 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *, struct lpfc_eqe *,
75 			uint32_t);
76 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
77 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
78 
79 static IOCB_t *
80 lpfc_get_iocb_from_iocbq(struct lpfc_iocbq *iocbq)
81 {
82 	return &iocbq->iocb;
83 }
84 
85 /**
86  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
87  * @q: The Work Queue to operate on.
88  * @wqe: The work Queue Entry to put on the Work queue.
89  *
90  * This routine will copy the contents of @wqe to the next available entry on
91  * the @q. This function will then ring the Work Queue Doorbell to signal the
92  * HBA to start processing the Work Queue Entry. This function returns 0 if
93  * successful. If no entries are available on @q then this function will return
94  * -ENOMEM.
95  * The caller is expected to hold the hbalock when calling this routine.
96  **/
97 static uint32_t
98 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe *wqe)
99 {
100 	union lpfc_wqe *temp_wqe;
101 	struct lpfc_register doorbell;
102 	uint32_t host_index;
103 	uint32_t idx;
104 
105 	/* sanity check on queue memory */
106 	if (unlikely(!q))
107 		return -ENOMEM;
108 	temp_wqe = q->qe[q->host_index].wqe;
109 
110 	/* If the host has not yet processed the next entry then we are done */
111 	idx = ((q->host_index + 1) % q->entry_count);
112 	if (idx == q->hba_index) {
113 		q->WQ_overflow++;
114 		return -ENOMEM;
115 	}
116 	q->WQ_posted++;
117 	/* set consumption flag every once in a while */
118 	if (!((q->host_index + 1) % q->entry_repost))
119 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
120 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
121 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
122 	lpfc_sli_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
123 
124 	/* Update the host index before invoking device */
125 	host_index = q->host_index;
126 
127 	q->host_index = idx;
128 
129 	/* Ring Doorbell */
130 	doorbell.word0 = 0;
131 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
132 		bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
133 		bf_set(lpfc_wq_db_list_fm_index, &doorbell, host_index);
134 		bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
135 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
136 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
137 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
138 	} else {
139 		return -EINVAL;
140 	}
141 	writel(doorbell.word0, q->db_regaddr);
142 
143 	return 0;
144 }
145 
146 /**
147  * lpfc_sli4_wq_release - Updates internal hba index for WQ
148  * @q: The Work Queue to operate on.
149  * @index: The index to advance the hba index to.
150  *
151  * This routine will update the HBA index of a queue to reflect consumption of
152  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
153  * an entry the host calls this function to update the queue's internal
154  * pointers. This routine returns the number of entries that were consumed by
155  * the HBA.
156  **/
157 static uint32_t
158 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
159 {
160 	uint32_t released = 0;
161 
162 	/* sanity check on queue memory */
163 	if (unlikely(!q))
164 		return 0;
165 
166 	if (q->hba_index == index)
167 		return 0;
168 	do {
169 		q->hba_index = ((q->hba_index + 1) % q->entry_count);
170 		released++;
171 	} while (q->hba_index != index);
172 	return released;
173 }
174 
175 /**
176  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
177  * @q: The Mailbox Queue to operate on.
178  * @wqe: The Mailbox Queue Entry to put on the Work queue.
179  *
180  * This routine will copy the contents of @mqe to the next available entry on
181  * the @q. This function will then ring the Work Queue Doorbell to signal the
182  * HBA to start processing the Work Queue Entry. This function returns 0 if
183  * successful. If no entries are available on @q then this function will return
184  * -ENOMEM.
185  * The caller is expected to hold the hbalock when calling this routine.
186  **/
187 static uint32_t
188 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
189 {
190 	struct lpfc_mqe *temp_mqe;
191 	struct lpfc_register doorbell;
192 
193 	/* sanity check on queue memory */
194 	if (unlikely(!q))
195 		return -ENOMEM;
196 	temp_mqe = q->qe[q->host_index].mqe;
197 
198 	/* If the host has not yet processed the next entry then we are done */
199 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
200 		return -ENOMEM;
201 	lpfc_sli_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
202 	/* Save off the mailbox pointer for completion */
203 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
204 
205 	/* Update the host index before invoking device */
206 	q->host_index = ((q->host_index + 1) % q->entry_count);
207 
208 	/* Ring Doorbell */
209 	doorbell.word0 = 0;
210 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
211 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
212 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
213 	return 0;
214 }
215 
216 /**
217  * lpfc_sli4_mq_release - Updates internal hba index for MQ
218  * @q: The Mailbox Queue to operate on.
219  *
220  * This routine will update the HBA index of a queue to reflect consumption of
221  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
222  * an entry the host calls this function to update the queue's internal
223  * pointers. This routine returns the number of entries that were consumed by
224  * the HBA.
225  **/
226 static uint32_t
227 lpfc_sli4_mq_release(struct lpfc_queue *q)
228 {
229 	/* sanity check on queue memory */
230 	if (unlikely(!q))
231 		return 0;
232 
233 	/* Clear the mailbox pointer for completion */
234 	q->phba->mbox = NULL;
235 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
236 	return 1;
237 }
238 
239 /**
240  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
241  * @q: The Event Queue to get the first valid EQE from
242  *
243  * This routine will get the first valid Event Queue Entry from @q, update
244  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
245  * the Queue (no more work to do), or the Queue is full of EQEs that have been
246  * processed, but not popped back to the HBA then this routine will return NULL.
247  **/
248 static struct lpfc_eqe *
249 lpfc_sli4_eq_get(struct lpfc_queue *q)
250 {
251 	struct lpfc_eqe *eqe;
252 	uint32_t idx;
253 
254 	/* sanity check on queue memory */
255 	if (unlikely(!q))
256 		return NULL;
257 	eqe = q->qe[q->hba_index].eqe;
258 
259 	/* If the next EQE is not valid then we are done */
260 	if (!bf_get_le32(lpfc_eqe_valid, eqe))
261 		return NULL;
262 	/* If the host has not yet processed the next entry then we are done */
263 	idx = ((q->hba_index + 1) % q->entry_count);
264 	if (idx == q->host_index)
265 		return NULL;
266 
267 	q->hba_index = idx;
268 
269 	/*
270 	 * insert barrier for instruction interlock : data from the hardware
271 	 * must have the valid bit checked before it can be copied and acted
272 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
273 	 * instructions allowing action on content before valid bit checked,
274 	 * add barrier here as well. May not be needed as "content" is a
275 	 * single 32-bit entity here (vs multi word structure for cq's).
276 	 */
277 	mb();
278 	return eqe;
279 }
280 
281 /**
282  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
283  * @q: The Event Queue to disable interrupts
284  *
285  **/
286 static inline void
287 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
288 {
289 	struct lpfc_register doorbell;
290 
291 	doorbell.word0 = 0;
292 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
293 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
294 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
295 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
296 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
297 	writel(doorbell.word0, q->phba->sli4_hba.EQCQDBregaddr);
298 }
299 
300 /**
301  * lpfc_sli4_eq_release - Indicates the host has finished processing an EQ
302  * @q: The Event Queue that the host has completed processing for.
303  * @arm: Indicates whether the host wants to arms this CQ.
304  *
305  * This routine will mark all Event Queue Entries on @q, from the last
306  * known completed entry to the last entry that was processed, as completed
307  * by clearing the valid bit for each completion queue entry. Then it will
308  * notify the HBA, by ringing the doorbell, that the EQEs have been processed.
309  * The internal host index in the @q will be updated by this routine to indicate
310  * that the host has finished processing the entries. The @arm parameter
311  * indicates that the queue should be rearmed when ringing the doorbell.
312  *
313  * This function will return the number of EQEs that were popped.
314  **/
315 uint32_t
316 lpfc_sli4_eq_release(struct lpfc_queue *q, bool arm)
317 {
318 	uint32_t released = 0;
319 	struct lpfc_eqe *temp_eqe;
320 	struct lpfc_register doorbell;
321 
322 	/* sanity check on queue memory */
323 	if (unlikely(!q))
324 		return 0;
325 
326 	/* while there are valid entries */
327 	while (q->hba_index != q->host_index) {
328 		temp_eqe = q->qe[q->host_index].eqe;
329 		bf_set_le32(lpfc_eqe_valid, temp_eqe, 0);
330 		released++;
331 		q->host_index = ((q->host_index + 1) % q->entry_count);
332 	}
333 	if (unlikely(released == 0 && !arm))
334 		return 0;
335 
336 	/* ring doorbell for number popped */
337 	doorbell.word0 = 0;
338 	if (arm) {
339 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
340 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
341 	}
342 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, released);
343 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
344 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
345 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
346 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
347 	writel(doorbell.word0, q->phba->sli4_hba.EQCQDBregaddr);
348 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
349 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
350 		readl(q->phba->sli4_hba.EQCQDBregaddr);
351 	return released;
352 }
353 
354 /**
355  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
356  * @q: The Completion Queue to get the first valid CQE from
357  *
358  * This routine will get the first valid Completion Queue Entry from @q, update
359  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
360  * the Queue (no more work to do), or the Queue is full of CQEs that have been
361  * processed, but not popped back to the HBA then this routine will return NULL.
362  **/
363 static struct lpfc_cqe *
364 lpfc_sli4_cq_get(struct lpfc_queue *q)
365 {
366 	struct lpfc_cqe *cqe;
367 	uint32_t idx;
368 
369 	/* sanity check on queue memory */
370 	if (unlikely(!q))
371 		return NULL;
372 
373 	/* If the next CQE is not valid then we are done */
374 	if (!bf_get_le32(lpfc_cqe_valid, q->qe[q->hba_index].cqe))
375 		return NULL;
376 	/* If the host has not yet processed the next entry then we are done */
377 	idx = ((q->hba_index + 1) % q->entry_count);
378 	if (idx == q->host_index)
379 		return NULL;
380 
381 	cqe = q->qe[q->hba_index].cqe;
382 	q->hba_index = idx;
383 
384 	/*
385 	 * insert barrier for instruction interlock : data from the hardware
386 	 * must have the valid bit checked before it can be copied and acted
387 	 * upon. Speculative instructions were allowing a bcopy at the start
388 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
389 	 * after our return, to copy data before the valid bit check above
390 	 * was done. As such, some of the copied data was stale. The barrier
391 	 * ensures the check is before any data is copied.
392 	 */
393 	mb();
394 	return cqe;
395 }
396 
397 /**
398  * lpfc_sli4_cq_release - Indicates the host has finished processing a CQ
399  * @q: The Completion Queue that the host has completed processing for.
400  * @arm: Indicates whether the host wants to arms this CQ.
401  *
402  * This routine will mark all Completion queue entries on @q, from the last
403  * known completed entry to the last entry that was processed, as completed
404  * by clearing the valid bit for each completion queue entry. Then it will
405  * notify the HBA, by ringing the doorbell, that the CQEs have been processed.
406  * The internal host index in the @q will be updated by this routine to indicate
407  * that the host has finished processing the entries. The @arm parameter
408  * indicates that the queue should be rearmed when ringing the doorbell.
409  *
410  * This function will return the number of CQEs that were released.
411  **/
412 uint32_t
413 lpfc_sli4_cq_release(struct lpfc_queue *q, bool arm)
414 {
415 	uint32_t released = 0;
416 	struct lpfc_cqe *temp_qe;
417 	struct lpfc_register doorbell;
418 
419 	/* sanity check on queue memory */
420 	if (unlikely(!q))
421 		return 0;
422 	/* while there are valid entries */
423 	while (q->hba_index != q->host_index) {
424 		temp_qe = q->qe[q->host_index].cqe;
425 		bf_set_le32(lpfc_cqe_valid, temp_qe, 0);
426 		released++;
427 		q->host_index = ((q->host_index + 1) % q->entry_count);
428 	}
429 	if (unlikely(released == 0 && !arm))
430 		return 0;
431 
432 	/* ring doorbell for number popped */
433 	doorbell.word0 = 0;
434 	if (arm)
435 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
436 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, released);
437 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
438 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
439 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
440 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
441 	writel(doorbell.word0, q->phba->sli4_hba.EQCQDBregaddr);
442 	return released;
443 }
444 
445 /**
446  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
447  * @q: The Header Receive Queue to operate on.
448  * @wqe: The Receive Queue Entry to put on the Receive queue.
449  *
450  * This routine will copy the contents of @wqe to the next available entry on
451  * the @q. This function will then ring the Receive Queue Doorbell to signal the
452  * HBA to start processing the Receive Queue Entry. This function returns the
453  * index that the rqe was copied to if successful. If no entries are available
454  * on @q then this function will return -ENOMEM.
455  * The caller is expected to hold the hbalock when calling this routine.
456  **/
457 static int
458 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
459 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
460 {
461 	struct lpfc_rqe *temp_hrqe;
462 	struct lpfc_rqe *temp_drqe;
463 	struct lpfc_register doorbell;
464 	int put_index;
465 
466 	/* sanity check on queue memory */
467 	if (unlikely(!hq) || unlikely(!dq))
468 		return -ENOMEM;
469 	put_index = hq->host_index;
470 	temp_hrqe = hq->qe[hq->host_index].rqe;
471 	temp_drqe = dq->qe[dq->host_index].rqe;
472 
473 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
474 		return -EINVAL;
475 	if (hq->host_index != dq->host_index)
476 		return -EINVAL;
477 	/* If the host has not yet processed the next entry then we are done */
478 	if (((hq->host_index + 1) % hq->entry_count) == hq->hba_index)
479 		return -EBUSY;
480 	lpfc_sli_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
481 	lpfc_sli_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
482 
483 	/* Update the host index to point to the next slot */
484 	hq->host_index = ((hq->host_index + 1) % hq->entry_count);
485 	dq->host_index = ((dq->host_index + 1) % dq->entry_count);
486 
487 	/* Ring The Header Receive Queue Doorbell */
488 	if (!(hq->host_index % hq->entry_repost)) {
489 		doorbell.word0 = 0;
490 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
491 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
492 			       hq->entry_repost);
493 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
494 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
495 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
496 			       hq->entry_repost);
497 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
498 			       hq->host_index);
499 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
500 		} else {
501 			return -EINVAL;
502 		}
503 		writel(doorbell.word0, hq->db_regaddr);
504 	}
505 	return put_index;
506 }
507 
508 /**
509  * lpfc_sli4_rq_release - Updates internal hba index for RQ
510  * @q: The Header Receive Queue to operate on.
511  *
512  * This routine will update the HBA index of a queue to reflect consumption of
513  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
514  * consumed an entry the host calls this function to update the queue's
515  * internal pointers. This routine returns the number of entries that were
516  * consumed by the HBA.
517  **/
518 static uint32_t
519 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
520 {
521 	/* sanity check on queue memory */
522 	if (unlikely(!hq) || unlikely(!dq))
523 		return 0;
524 
525 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
526 		return 0;
527 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
528 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
529 	return 1;
530 }
531 
532 /**
533  * lpfc_cmd_iocb - Get next command iocb entry in the ring
534  * @phba: Pointer to HBA context object.
535  * @pring: Pointer to driver SLI ring object.
536  *
537  * This function returns pointer to next command iocb entry
538  * in the command ring. The caller must hold hbalock to prevent
539  * other threads consume the next command iocb.
540  * SLI-2/SLI-3 provide different sized iocbs.
541  **/
542 static inline IOCB_t *
543 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
544 {
545 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
546 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
547 }
548 
549 /**
550  * lpfc_resp_iocb - Get next response iocb entry in the ring
551  * @phba: Pointer to HBA context object.
552  * @pring: Pointer to driver SLI ring object.
553  *
554  * This function returns pointer to next response iocb entry
555  * in the response ring. The caller must hold hbalock to make sure
556  * that no other thread consume the next response iocb.
557  * SLI-2/SLI-3 provide different sized iocbs.
558  **/
559 static inline IOCB_t *
560 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
561 {
562 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
563 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
564 }
565 
566 /**
567  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
568  * @phba: Pointer to HBA context object.
569  *
570  * This function is called with hbalock held. This function
571  * allocates a new driver iocb object from the iocb pool. If the
572  * allocation is successful, it returns pointer to the newly
573  * allocated iocb object else it returns NULL.
574  **/
575 struct lpfc_iocbq *
576 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
577 {
578 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
579 	struct lpfc_iocbq * iocbq = NULL;
580 
581 	lockdep_assert_held(&phba->hbalock);
582 
583 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
584 	if (iocbq)
585 		phba->iocb_cnt++;
586 	if (phba->iocb_cnt > phba->iocb_max)
587 		phba->iocb_max = phba->iocb_cnt;
588 	return iocbq;
589 }
590 
591 /**
592  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
593  * @phba: Pointer to HBA context object.
594  * @xritag: XRI value.
595  *
596  * This function clears the sglq pointer from the array of acive
597  * sglq's. The xritag that is passed in is used to index into the
598  * array. Before the xritag can be used it needs to be adjusted
599  * by subtracting the xribase.
600  *
601  * Returns sglq ponter = success, NULL = Failure.
602  **/
603 static struct lpfc_sglq *
604 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
605 {
606 	struct lpfc_sglq *sglq;
607 
608 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
609 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
610 	return sglq;
611 }
612 
613 /**
614  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
615  * @phba: Pointer to HBA context object.
616  * @xritag: XRI value.
617  *
618  * This function returns the sglq pointer from the array of acive
619  * sglq's. The xritag that is passed in is used to index into the
620  * array. Before the xritag can be used it needs to be adjusted
621  * by subtracting the xribase.
622  *
623  * Returns sglq ponter = success, NULL = Failure.
624  **/
625 struct lpfc_sglq *
626 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
627 {
628 	struct lpfc_sglq *sglq;
629 
630 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
631 	return sglq;
632 }
633 
634 /**
635  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
636  * @phba: Pointer to HBA context object.
637  * @xritag: xri used in this exchange.
638  * @rrq: The RRQ to be cleared.
639  *
640  **/
641 void
642 lpfc_clr_rrq_active(struct lpfc_hba *phba,
643 		    uint16_t xritag,
644 		    struct lpfc_node_rrq *rrq)
645 {
646 	struct lpfc_nodelist *ndlp = NULL;
647 
648 	if ((rrq->vport) && NLP_CHK_NODE_ACT(rrq->ndlp))
649 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
650 
651 	/* The target DID could have been swapped (cable swap)
652 	 * we should use the ndlp from the findnode if it is
653 	 * available.
654 	 */
655 	if ((!ndlp) && rrq->ndlp)
656 		ndlp = rrq->ndlp;
657 
658 	if (!ndlp)
659 		goto out;
660 
661 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
662 		rrq->send_rrq = 0;
663 		rrq->xritag = 0;
664 		rrq->rrq_stop_time = 0;
665 	}
666 out:
667 	mempool_free(rrq, phba->rrq_pool);
668 }
669 
670 /**
671  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
672  * @phba: Pointer to HBA context object.
673  *
674  * This function is called with hbalock held. This function
675  * Checks if stop_time (ratov from setting rrq active) has
676  * been reached, if it has and the send_rrq flag is set then
677  * it will call lpfc_send_rrq. If the send_rrq flag is not set
678  * then it will just call the routine to clear the rrq and
679  * free the rrq resource.
680  * The timer is set to the next rrq that is going to expire before
681  * leaving the routine.
682  *
683  **/
684 void
685 lpfc_handle_rrq_active(struct lpfc_hba *phba)
686 {
687 	struct lpfc_node_rrq *rrq;
688 	struct lpfc_node_rrq *nextrrq;
689 	unsigned long next_time;
690 	unsigned long iflags;
691 	LIST_HEAD(send_rrq);
692 
693 	spin_lock_irqsave(&phba->hbalock, iflags);
694 	phba->hba_flag &= ~HBA_RRQ_ACTIVE;
695 	next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
696 	list_for_each_entry_safe(rrq, nextrrq,
697 				 &phba->active_rrq_list, list) {
698 		if (time_after(jiffies, rrq->rrq_stop_time))
699 			list_move(&rrq->list, &send_rrq);
700 		else if (time_before(rrq->rrq_stop_time, next_time))
701 			next_time = rrq->rrq_stop_time;
702 	}
703 	spin_unlock_irqrestore(&phba->hbalock, iflags);
704 	if ((!list_empty(&phba->active_rrq_list)) &&
705 	    (!(phba->pport->load_flag & FC_UNLOADING)))
706 		mod_timer(&phba->rrq_tmr, next_time);
707 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
708 		list_del(&rrq->list);
709 		if (!rrq->send_rrq)
710 			/* this call will free the rrq */
711 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
712 		else if (lpfc_send_rrq(phba, rrq)) {
713 			/* if we send the rrq then the completion handler
714 			*  will clear the bit in the xribitmap.
715 			*/
716 			lpfc_clr_rrq_active(phba, rrq->xritag,
717 					    rrq);
718 		}
719 	}
720 }
721 
722 /**
723  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
724  * @vport: Pointer to vport context object.
725  * @xri: The xri used in the exchange.
726  * @did: The targets DID for this exchange.
727  *
728  * returns NULL = rrq not found in the phba->active_rrq_list.
729  *         rrq = rrq for this xri and target.
730  **/
731 struct lpfc_node_rrq *
732 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
733 {
734 	struct lpfc_hba *phba = vport->phba;
735 	struct lpfc_node_rrq *rrq;
736 	struct lpfc_node_rrq *nextrrq;
737 	unsigned long iflags;
738 
739 	if (phba->sli_rev != LPFC_SLI_REV4)
740 		return NULL;
741 	spin_lock_irqsave(&phba->hbalock, iflags);
742 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
743 		if (rrq->vport == vport && rrq->xritag == xri &&
744 				rrq->nlp_DID == did){
745 			list_del(&rrq->list);
746 			spin_unlock_irqrestore(&phba->hbalock, iflags);
747 			return rrq;
748 		}
749 	}
750 	spin_unlock_irqrestore(&phba->hbalock, iflags);
751 	return NULL;
752 }
753 
754 /**
755  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
756  * @vport: Pointer to vport context object.
757  * @ndlp: Pointer to the lpfc_node_list structure.
758  * If ndlp is NULL Remove all active RRQs for this vport from the
759  * phba->active_rrq_list and clear the rrq.
760  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
761  **/
762 void
763 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
764 
765 {
766 	struct lpfc_hba *phba = vport->phba;
767 	struct lpfc_node_rrq *rrq;
768 	struct lpfc_node_rrq *nextrrq;
769 	unsigned long iflags;
770 	LIST_HEAD(rrq_list);
771 
772 	if (phba->sli_rev != LPFC_SLI_REV4)
773 		return;
774 	if (!ndlp) {
775 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
776 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
777 	}
778 	spin_lock_irqsave(&phba->hbalock, iflags);
779 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list)
780 		if ((rrq->vport == vport) && (!ndlp  || rrq->ndlp == ndlp))
781 			list_move(&rrq->list, &rrq_list);
782 	spin_unlock_irqrestore(&phba->hbalock, iflags);
783 
784 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
785 		list_del(&rrq->list);
786 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
787 	}
788 }
789 
790 /**
791  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
792  * @phba: Pointer to HBA context object.
793  * @ndlp: Targets nodelist pointer for this exchange.
794  * @xritag the xri in the bitmap to test.
795  *
796  * This function is called with hbalock held. This function
797  * returns 0 = rrq not active for this xri
798  *         1 = rrq is valid for this xri.
799  **/
800 int
801 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
802 			uint16_t  xritag)
803 {
804 	lockdep_assert_held(&phba->hbalock);
805 	if (!ndlp)
806 		return 0;
807 	if (!ndlp->active_rrqs_xri_bitmap)
808 		return 0;
809 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
810 			return 1;
811 	else
812 		return 0;
813 }
814 
815 /**
816  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
817  * @phba: Pointer to HBA context object.
818  * @ndlp: nodelist pointer for this target.
819  * @xritag: xri used in this exchange.
820  * @rxid: Remote Exchange ID.
821  * @send_rrq: Flag used to determine if we should send rrq els cmd.
822  *
823  * This function takes the hbalock.
824  * The active bit is always set in the active rrq xri_bitmap even
825  * if there is no slot avaiable for the other rrq information.
826  *
827  * returns 0 rrq actived for this xri
828  *         < 0 No memory or invalid ndlp.
829  **/
830 int
831 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
832 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
833 {
834 	unsigned long iflags;
835 	struct lpfc_node_rrq *rrq;
836 	int empty;
837 
838 	if (!ndlp)
839 		return -EINVAL;
840 
841 	if (!phba->cfg_enable_rrq)
842 		return -EINVAL;
843 
844 	spin_lock_irqsave(&phba->hbalock, iflags);
845 	if (phba->pport->load_flag & FC_UNLOADING) {
846 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
847 		goto out;
848 	}
849 
850 	/*
851 	 * set the active bit even if there is no mem available.
852 	 */
853 	if (NLP_CHK_FREE_REQ(ndlp))
854 		goto out;
855 
856 	if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
857 		goto out;
858 
859 	if (!ndlp->active_rrqs_xri_bitmap)
860 		goto out;
861 
862 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
863 		goto out;
864 
865 	spin_unlock_irqrestore(&phba->hbalock, iflags);
866 	rrq = mempool_alloc(phba->rrq_pool, GFP_KERNEL);
867 	if (!rrq) {
868 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
869 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
870 				" DID:0x%x Send:%d\n",
871 				xritag, rxid, ndlp->nlp_DID, send_rrq);
872 		return -EINVAL;
873 	}
874 	if (phba->cfg_enable_rrq == 1)
875 		rrq->send_rrq = send_rrq;
876 	else
877 		rrq->send_rrq = 0;
878 	rrq->xritag = xritag;
879 	rrq->rrq_stop_time = jiffies +
880 				msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
881 	rrq->ndlp = ndlp;
882 	rrq->nlp_DID = ndlp->nlp_DID;
883 	rrq->vport = ndlp->vport;
884 	rrq->rxid = rxid;
885 	spin_lock_irqsave(&phba->hbalock, iflags);
886 	empty = list_empty(&phba->active_rrq_list);
887 	list_add_tail(&rrq->list, &phba->active_rrq_list);
888 	phba->hba_flag |= HBA_RRQ_ACTIVE;
889 	if (empty)
890 		lpfc_worker_wake_up(phba);
891 	spin_unlock_irqrestore(&phba->hbalock, iflags);
892 	return 0;
893 out:
894 	spin_unlock_irqrestore(&phba->hbalock, iflags);
895 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
896 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
897 			" DID:0x%x Send:%d\n",
898 			xritag, rxid, ndlp->nlp_DID, send_rrq);
899 	return -EINVAL;
900 }
901 
902 /**
903  * __lpfc_sli_get_sglq - Allocates an iocb object from sgl pool
904  * @phba: Pointer to HBA context object.
905  * @piocb: Pointer to the iocbq.
906  *
907  * This function is called with the ring lock held. This function
908  * gets a new driver sglq object from the sglq list. If the
909  * list is not empty then it is successful, it returns pointer to the newly
910  * allocated sglq object else it returns NULL.
911  **/
912 static struct lpfc_sglq *
913 __lpfc_sli_get_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
914 {
915 	struct list_head *lpfc_sgl_list = &phba->sli4_hba.lpfc_sgl_list;
916 	struct lpfc_sglq *sglq = NULL;
917 	struct lpfc_sglq *start_sglq = NULL;
918 	struct lpfc_scsi_buf *lpfc_cmd;
919 	struct lpfc_nodelist *ndlp;
920 	int found = 0;
921 
922 	lockdep_assert_held(&phba->hbalock);
923 
924 	if (piocbq->iocb_flag &  LPFC_IO_FCP) {
925 		lpfc_cmd = (struct lpfc_scsi_buf *) piocbq->context1;
926 		ndlp = lpfc_cmd->rdata->pnode;
927 	} else  if ((piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) &&
928 			!(piocbq->iocb_flag & LPFC_IO_LIBDFC)) {
929 		ndlp = piocbq->context_un.ndlp;
930 	} else  if (piocbq->iocb_flag & LPFC_IO_LIBDFC) {
931 		if (piocbq->iocb_flag & LPFC_IO_LOOPBACK)
932 			ndlp = NULL;
933 		else
934 			ndlp = piocbq->context_un.ndlp;
935 	} else {
936 		ndlp = piocbq->context1;
937 	}
938 
939 	list_remove_head(lpfc_sgl_list, sglq, struct lpfc_sglq, list);
940 	start_sglq = sglq;
941 	while (!found) {
942 		if (!sglq)
943 			return NULL;
944 		if (lpfc_test_rrq_active(phba, ndlp, sglq->sli4_lxritag)) {
945 			/* This xri has an rrq outstanding for this DID.
946 			 * put it back in the list and get another xri.
947 			 */
948 			list_add_tail(&sglq->list, lpfc_sgl_list);
949 			sglq = NULL;
950 			list_remove_head(lpfc_sgl_list, sglq,
951 						struct lpfc_sglq, list);
952 			if (sglq == start_sglq) {
953 				sglq = NULL;
954 				break;
955 			} else
956 				continue;
957 		}
958 		sglq->ndlp = ndlp;
959 		found = 1;
960 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
961 		sglq->state = SGL_ALLOCATED;
962 	}
963 	return sglq;
964 }
965 
966 /**
967  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
968  * @phba: Pointer to HBA context object.
969  *
970  * This function is called with no lock held. This function
971  * allocates a new driver iocb object from the iocb pool. If the
972  * allocation is successful, it returns pointer to the newly
973  * allocated iocb object else it returns NULL.
974  **/
975 struct lpfc_iocbq *
976 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
977 {
978 	struct lpfc_iocbq * iocbq = NULL;
979 	unsigned long iflags;
980 
981 	spin_lock_irqsave(&phba->hbalock, iflags);
982 	iocbq = __lpfc_sli_get_iocbq(phba);
983 	spin_unlock_irqrestore(&phba->hbalock, iflags);
984 	return iocbq;
985 }
986 
987 /**
988  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
989  * @phba: Pointer to HBA context object.
990  * @iocbq: Pointer to driver iocb object.
991  *
992  * This function is called with hbalock held to release driver
993  * iocb object to the iocb pool. The iotag in the iocb object
994  * does not change for each use of the iocb object. This function
995  * clears all other fields of the iocb object when it is freed.
996  * The sqlq structure that holds the xritag and phys and virtual
997  * mappings for the scatter gather list is retrieved from the
998  * active array of sglq. The get of the sglq pointer also clears
999  * the entry in the array. If the status of the IO indiactes that
1000  * this IO was aborted then the sglq entry it put on the
1001  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1002  * IO has good status or fails for any other reason then the sglq
1003  * entry is added to the free list (lpfc_sgl_list).
1004  **/
1005 static void
1006 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1007 {
1008 	struct lpfc_sglq *sglq;
1009 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1010 	unsigned long iflag = 0;
1011 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
1012 
1013 	lockdep_assert_held(&phba->hbalock);
1014 
1015 	if (iocbq->sli4_xritag == NO_XRI)
1016 		sglq = NULL;
1017 	else
1018 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1019 
1020 
1021 	if (sglq)  {
1022 		if ((iocbq->iocb_flag & LPFC_EXCHANGE_BUSY) &&
1023 			(sglq->state != SGL_XRI_ABORTED)) {
1024 			spin_lock_irqsave(&phba->sli4_hba.abts_sgl_list_lock,
1025 					iflag);
1026 			list_add(&sglq->list,
1027 				&phba->sli4_hba.lpfc_abts_els_sgl_list);
1028 			spin_unlock_irqrestore(
1029 				&phba->sli4_hba.abts_sgl_list_lock, iflag);
1030 		} else {
1031 			spin_lock_irqsave(&pring->ring_lock, iflag);
1032 			sglq->state = SGL_FREED;
1033 			sglq->ndlp = NULL;
1034 			list_add_tail(&sglq->list,
1035 				&phba->sli4_hba.lpfc_sgl_list);
1036 			spin_unlock_irqrestore(&pring->ring_lock, iflag);
1037 
1038 			/* Check if TXQ queue needs to be serviced */
1039 			if (!list_empty(&pring->txq))
1040 				lpfc_worker_wake_up(phba);
1041 		}
1042 	}
1043 
1044 
1045 	/*
1046 	 * Clean all volatile data fields, preserve iotag and node struct.
1047 	 */
1048 	memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1049 	iocbq->sli4_lxritag = NO_XRI;
1050 	iocbq->sli4_xritag = NO_XRI;
1051 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1052 }
1053 
1054 
1055 /**
1056  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1057  * @phba: Pointer to HBA context object.
1058  * @iocbq: Pointer to driver iocb object.
1059  *
1060  * This function is called with hbalock held to release driver
1061  * iocb object to the iocb pool. The iotag in the iocb object
1062  * does not change for each use of the iocb object. This function
1063  * clears all other fields of the iocb object when it is freed.
1064  **/
1065 static void
1066 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1067 {
1068 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1069 
1070 	lockdep_assert_held(&phba->hbalock);
1071 
1072 	/*
1073 	 * Clean all volatile data fields, preserve iotag and node struct.
1074 	 */
1075 	memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1076 	iocbq->sli4_xritag = NO_XRI;
1077 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1078 }
1079 
1080 /**
1081  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1082  * @phba: Pointer to HBA context object.
1083  * @iocbq: Pointer to driver iocb object.
1084  *
1085  * This function is called with hbalock held to release driver
1086  * iocb object to the iocb pool. The iotag in the iocb object
1087  * does not change for each use of the iocb object. This function
1088  * clears all other fields of the iocb object when it is freed.
1089  **/
1090 static void
1091 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1092 {
1093 	lockdep_assert_held(&phba->hbalock);
1094 
1095 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1096 	phba->iocb_cnt--;
1097 }
1098 
1099 /**
1100  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1101  * @phba: Pointer to HBA context object.
1102  * @iocbq: Pointer to driver iocb object.
1103  *
1104  * This function is called with no lock held to release the iocb to
1105  * iocb pool.
1106  **/
1107 void
1108 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1109 {
1110 	unsigned long iflags;
1111 
1112 	/*
1113 	 * Clean all volatile data fields, preserve iotag and node struct.
1114 	 */
1115 	spin_lock_irqsave(&phba->hbalock, iflags);
1116 	__lpfc_sli_release_iocbq(phba, iocbq);
1117 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1118 }
1119 
1120 /**
1121  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1122  * @phba: Pointer to HBA context object.
1123  * @iocblist: List of IOCBs.
1124  * @ulpstatus: ULP status in IOCB command field.
1125  * @ulpWord4: ULP word-4 in IOCB command field.
1126  *
1127  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1128  * on the list by invoking the complete callback function associated with the
1129  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1130  * fields.
1131  **/
1132 void
1133 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1134 		      uint32_t ulpstatus, uint32_t ulpWord4)
1135 {
1136 	struct lpfc_iocbq *piocb;
1137 
1138 	while (!list_empty(iocblist)) {
1139 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1140 		if (!piocb->iocb_cmpl)
1141 			lpfc_sli_release_iocbq(phba, piocb);
1142 		else {
1143 			piocb->iocb.ulpStatus = ulpstatus;
1144 			piocb->iocb.un.ulpWord[4] = ulpWord4;
1145 			(piocb->iocb_cmpl) (phba, piocb, piocb);
1146 		}
1147 	}
1148 	return;
1149 }
1150 
1151 /**
1152  * lpfc_sli_iocb_cmd_type - Get the iocb type
1153  * @iocb_cmnd: iocb command code.
1154  *
1155  * This function is called by ring event handler function to get the iocb type.
1156  * This function translates the iocb command to an iocb command type used to
1157  * decide the final disposition of each completed IOCB.
1158  * The function returns
1159  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1160  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1161  * LPFC_ABORT_IOCB   if it is an abort iocb
1162  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1163  *
1164  * The caller is not required to hold any lock.
1165  **/
1166 static lpfc_iocb_type
1167 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1168 {
1169 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1170 
1171 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1172 		return 0;
1173 
1174 	switch (iocb_cmnd) {
1175 	case CMD_XMIT_SEQUENCE_CR:
1176 	case CMD_XMIT_SEQUENCE_CX:
1177 	case CMD_XMIT_BCAST_CN:
1178 	case CMD_XMIT_BCAST_CX:
1179 	case CMD_ELS_REQUEST_CR:
1180 	case CMD_ELS_REQUEST_CX:
1181 	case CMD_CREATE_XRI_CR:
1182 	case CMD_CREATE_XRI_CX:
1183 	case CMD_GET_RPI_CN:
1184 	case CMD_XMIT_ELS_RSP_CX:
1185 	case CMD_GET_RPI_CR:
1186 	case CMD_FCP_IWRITE_CR:
1187 	case CMD_FCP_IWRITE_CX:
1188 	case CMD_FCP_IREAD_CR:
1189 	case CMD_FCP_IREAD_CX:
1190 	case CMD_FCP_ICMND_CR:
1191 	case CMD_FCP_ICMND_CX:
1192 	case CMD_FCP_TSEND_CX:
1193 	case CMD_FCP_TRSP_CX:
1194 	case CMD_FCP_TRECEIVE_CX:
1195 	case CMD_FCP_AUTO_TRSP_CX:
1196 	case CMD_ADAPTER_MSG:
1197 	case CMD_ADAPTER_DUMP:
1198 	case CMD_XMIT_SEQUENCE64_CR:
1199 	case CMD_XMIT_SEQUENCE64_CX:
1200 	case CMD_XMIT_BCAST64_CN:
1201 	case CMD_XMIT_BCAST64_CX:
1202 	case CMD_ELS_REQUEST64_CR:
1203 	case CMD_ELS_REQUEST64_CX:
1204 	case CMD_FCP_IWRITE64_CR:
1205 	case CMD_FCP_IWRITE64_CX:
1206 	case CMD_FCP_IREAD64_CR:
1207 	case CMD_FCP_IREAD64_CX:
1208 	case CMD_FCP_ICMND64_CR:
1209 	case CMD_FCP_ICMND64_CX:
1210 	case CMD_FCP_TSEND64_CX:
1211 	case CMD_FCP_TRSP64_CX:
1212 	case CMD_FCP_TRECEIVE64_CX:
1213 	case CMD_GEN_REQUEST64_CR:
1214 	case CMD_GEN_REQUEST64_CX:
1215 	case CMD_XMIT_ELS_RSP64_CX:
1216 	case DSSCMD_IWRITE64_CR:
1217 	case DSSCMD_IWRITE64_CX:
1218 	case DSSCMD_IREAD64_CR:
1219 	case DSSCMD_IREAD64_CX:
1220 		type = LPFC_SOL_IOCB;
1221 		break;
1222 	case CMD_ABORT_XRI_CN:
1223 	case CMD_ABORT_XRI_CX:
1224 	case CMD_CLOSE_XRI_CN:
1225 	case CMD_CLOSE_XRI_CX:
1226 	case CMD_XRI_ABORTED_CX:
1227 	case CMD_ABORT_MXRI64_CN:
1228 	case CMD_XMIT_BLS_RSP64_CX:
1229 		type = LPFC_ABORT_IOCB;
1230 		break;
1231 	case CMD_RCV_SEQUENCE_CX:
1232 	case CMD_RCV_ELS_REQ_CX:
1233 	case CMD_RCV_SEQUENCE64_CX:
1234 	case CMD_RCV_ELS_REQ64_CX:
1235 	case CMD_ASYNC_STATUS:
1236 	case CMD_IOCB_RCV_SEQ64_CX:
1237 	case CMD_IOCB_RCV_ELS64_CX:
1238 	case CMD_IOCB_RCV_CONT64_CX:
1239 	case CMD_IOCB_RET_XRI64_CX:
1240 		type = LPFC_UNSOL_IOCB;
1241 		break;
1242 	case CMD_IOCB_XMIT_MSEQ64_CR:
1243 	case CMD_IOCB_XMIT_MSEQ64_CX:
1244 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1245 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1246 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1247 	case CMD_IOCB_ABORT_EXTENDED_CN:
1248 	case CMD_IOCB_RET_HBQE64_CN:
1249 	case CMD_IOCB_FCP_IBIDIR64_CR:
1250 	case CMD_IOCB_FCP_IBIDIR64_CX:
1251 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1252 	case CMD_IOCB_LOGENTRY_CN:
1253 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1254 		printk("%s - Unhandled SLI-3 Command x%x\n",
1255 				__func__, iocb_cmnd);
1256 		type = LPFC_UNKNOWN_IOCB;
1257 		break;
1258 	default:
1259 		type = LPFC_UNKNOWN_IOCB;
1260 		break;
1261 	}
1262 
1263 	return type;
1264 }
1265 
1266 /**
1267  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1268  * @phba: Pointer to HBA context object.
1269  *
1270  * This function is called from SLI initialization code
1271  * to configure every ring of the HBA's SLI interface. The
1272  * caller is not required to hold any lock. This function issues
1273  * a config_ring mailbox command for each ring.
1274  * This function returns zero if successful else returns a negative
1275  * error code.
1276  **/
1277 static int
1278 lpfc_sli_ring_map(struct lpfc_hba *phba)
1279 {
1280 	struct lpfc_sli *psli = &phba->sli;
1281 	LPFC_MBOXQ_t *pmb;
1282 	MAILBOX_t *pmbox;
1283 	int i, rc, ret = 0;
1284 
1285 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1286 	if (!pmb)
1287 		return -ENOMEM;
1288 	pmbox = &pmb->u.mb;
1289 	phba->link_state = LPFC_INIT_MBX_CMDS;
1290 	for (i = 0; i < psli->num_rings; i++) {
1291 		lpfc_config_ring(phba, i, pmb);
1292 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1293 		if (rc != MBX_SUCCESS) {
1294 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1295 					"0446 Adapter failed to init (%d), "
1296 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1297 					"ring %d\n",
1298 					rc, pmbox->mbxCommand,
1299 					pmbox->mbxStatus, i);
1300 			phba->link_state = LPFC_HBA_ERROR;
1301 			ret = -ENXIO;
1302 			break;
1303 		}
1304 	}
1305 	mempool_free(pmb, phba->mbox_mem_pool);
1306 	return ret;
1307 }
1308 
1309 /**
1310  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1311  * @phba: Pointer to HBA context object.
1312  * @pring: Pointer to driver SLI ring object.
1313  * @piocb: Pointer to the driver iocb object.
1314  *
1315  * This function is called with hbalock held. The function adds the
1316  * new iocb to txcmplq of the given ring. This function always returns
1317  * 0. If this function is called for ELS ring, this function checks if
1318  * there is a vport associated with the ELS command. This function also
1319  * starts els_tmofunc timer if this is an ELS command.
1320  **/
1321 static int
1322 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1323 			struct lpfc_iocbq *piocb)
1324 {
1325 	lockdep_assert_held(&phba->hbalock);
1326 
1327 	BUG_ON(!piocb);
1328 
1329 	list_add_tail(&piocb->list, &pring->txcmplq);
1330 	piocb->iocb_flag |= LPFC_IO_ON_TXCMPLQ;
1331 
1332 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1333 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
1334 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
1335 		BUG_ON(!piocb->vport);
1336 		if (!(piocb->vport->load_flag & FC_UNLOADING))
1337 			mod_timer(&piocb->vport->els_tmofunc,
1338 				  jiffies +
1339 				  msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
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 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
2683 			/* remove from txcmpl queue list */
2684 			list_del_init(&cmd_iocb->list);
2685 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
2686 			return cmd_iocb;
2687 		}
2688 	}
2689 
2690 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2691 			"0317 iotag x%x is out of "
2692 			"range: max iotag x%x wd0 x%x\n",
2693 			iotag, phba->sli.last_iotag,
2694 			*(((uint32_t *) &prspiocb->iocb) + 7));
2695 	return NULL;
2696 }
2697 
2698 /**
2699  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
2700  * @phba: Pointer to HBA context object.
2701  * @pring: Pointer to driver SLI ring object.
2702  * @iotag: IOCB tag.
2703  *
2704  * This function looks up the iocb_lookup table to get the command iocb
2705  * corresponding to the given iotag. This function is called with the
2706  * hbalock held.
2707  * This function returns the command iocb object if it finds the command
2708  * iocb else returns NULL.
2709  **/
2710 static struct lpfc_iocbq *
2711 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
2712 			     struct lpfc_sli_ring *pring, uint16_t iotag)
2713 {
2714 	struct lpfc_iocbq *cmd_iocb;
2715 
2716 	lockdep_assert_held(&phba->hbalock);
2717 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
2718 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
2719 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
2720 			/* remove from txcmpl queue list */
2721 			list_del_init(&cmd_iocb->list);
2722 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
2723 			return cmd_iocb;
2724 		}
2725 	}
2726 
2727 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2728 			"0372 iotag x%x is out of range: max iotag (x%x)\n",
2729 			iotag, phba->sli.last_iotag);
2730 	return NULL;
2731 }
2732 
2733 /**
2734  * lpfc_sli_process_sol_iocb - process solicited iocb completion
2735  * @phba: Pointer to HBA context object.
2736  * @pring: Pointer to driver SLI ring object.
2737  * @saveq: Pointer to the response iocb to be processed.
2738  *
2739  * This function is called by the ring event handler for non-fcp
2740  * rings when there is a new response iocb in the response ring.
2741  * The caller is not required to hold any locks. This function
2742  * gets the command iocb associated with the response iocb and
2743  * calls the completion handler for the command iocb. If there
2744  * is no completion handler, the function will free the resources
2745  * associated with command iocb. If the response iocb is for
2746  * an already aborted command iocb, the status of the completion
2747  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
2748  * This function always returns 1.
2749  **/
2750 static int
2751 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2752 			  struct lpfc_iocbq *saveq)
2753 {
2754 	struct lpfc_iocbq *cmdiocbp;
2755 	int rc = 1;
2756 	unsigned long iflag;
2757 
2758 	/* Based on the iotag field, get the cmd IOCB from the txcmplq */
2759 	spin_lock_irqsave(&phba->hbalock, iflag);
2760 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
2761 	spin_unlock_irqrestore(&phba->hbalock, iflag);
2762 
2763 	if (cmdiocbp) {
2764 		if (cmdiocbp->iocb_cmpl) {
2765 			/*
2766 			 * If an ELS command failed send an event to mgmt
2767 			 * application.
2768 			 */
2769 			if (saveq->iocb.ulpStatus &&
2770 			     (pring->ringno == LPFC_ELS_RING) &&
2771 			     (cmdiocbp->iocb.ulpCommand ==
2772 				CMD_ELS_REQUEST64_CR))
2773 				lpfc_send_els_failure_event(phba,
2774 					cmdiocbp, saveq);
2775 
2776 			/*
2777 			 * Post all ELS completions to the worker thread.
2778 			 * All other are passed to the completion callback.
2779 			 */
2780 			if (pring->ringno == LPFC_ELS_RING) {
2781 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
2782 				    (cmdiocbp->iocb_flag &
2783 							LPFC_DRIVER_ABORTED)) {
2784 					spin_lock_irqsave(&phba->hbalock,
2785 							  iflag);
2786 					cmdiocbp->iocb_flag &=
2787 						~LPFC_DRIVER_ABORTED;
2788 					spin_unlock_irqrestore(&phba->hbalock,
2789 							       iflag);
2790 					saveq->iocb.ulpStatus =
2791 						IOSTAT_LOCAL_REJECT;
2792 					saveq->iocb.un.ulpWord[4] =
2793 						IOERR_SLI_ABORTED;
2794 
2795 					/* Firmware could still be in progress
2796 					 * of DMAing payload, so don't free data
2797 					 * buffer till after a hbeat.
2798 					 */
2799 					spin_lock_irqsave(&phba->hbalock,
2800 							  iflag);
2801 					saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
2802 					spin_unlock_irqrestore(&phba->hbalock,
2803 							       iflag);
2804 				}
2805 				if (phba->sli_rev == LPFC_SLI_REV4) {
2806 					if (saveq->iocb_flag &
2807 					    LPFC_EXCHANGE_BUSY) {
2808 						/* Set cmdiocb flag for the
2809 						 * exchange busy so sgl (xri)
2810 						 * will not be released until
2811 						 * the abort xri is received
2812 						 * from hba.
2813 						 */
2814 						spin_lock_irqsave(
2815 							&phba->hbalock, iflag);
2816 						cmdiocbp->iocb_flag |=
2817 							LPFC_EXCHANGE_BUSY;
2818 						spin_unlock_irqrestore(
2819 							&phba->hbalock, iflag);
2820 					}
2821 					if (cmdiocbp->iocb_flag &
2822 					    LPFC_DRIVER_ABORTED) {
2823 						/*
2824 						 * Clear LPFC_DRIVER_ABORTED
2825 						 * bit in case it was driver
2826 						 * initiated abort.
2827 						 */
2828 						spin_lock_irqsave(
2829 							&phba->hbalock, iflag);
2830 						cmdiocbp->iocb_flag &=
2831 							~LPFC_DRIVER_ABORTED;
2832 						spin_unlock_irqrestore(
2833 							&phba->hbalock, iflag);
2834 						cmdiocbp->iocb.ulpStatus =
2835 							IOSTAT_LOCAL_REJECT;
2836 						cmdiocbp->iocb.un.ulpWord[4] =
2837 							IOERR_ABORT_REQUESTED;
2838 						/*
2839 						 * For SLI4, irsiocb contains
2840 						 * NO_XRI in sli_xritag, it
2841 						 * shall not affect releasing
2842 						 * sgl (xri) process.
2843 						 */
2844 						saveq->iocb.ulpStatus =
2845 							IOSTAT_LOCAL_REJECT;
2846 						saveq->iocb.un.ulpWord[4] =
2847 							IOERR_SLI_ABORTED;
2848 						spin_lock_irqsave(
2849 							&phba->hbalock, iflag);
2850 						saveq->iocb_flag |=
2851 							LPFC_DELAY_MEM_FREE;
2852 						spin_unlock_irqrestore(
2853 							&phba->hbalock, iflag);
2854 					}
2855 				}
2856 			}
2857 			(cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
2858 		} else
2859 			lpfc_sli_release_iocbq(phba, cmdiocbp);
2860 	} else {
2861 		/*
2862 		 * Unknown initiating command based on the response iotag.
2863 		 * This could be the case on the ELS ring because of
2864 		 * lpfc_els_abort().
2865 		 */
2866 		if (pring->ringno != LPFC_ELS_RING) {
2867 			/*
2868 			 * Ring <ringno> handler: unexpected completion IoTag
2869 			 * <IoTag>
2870 			 */
2871 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2872 					 "0322 Ring %d handler: "
2873 					 "unexpected completion IoTag x%x "
2874 					 "Data: x%x x%x x%x x%x\n",
2875 					 pring->ringno,
2876 					 saveq->iocb.ulpIoTag,
2877 					 saveq->iocb.ulpStatus,
2878 					 saveq->iocb.un.ulpWord[4],
2879 					 saveq->iocb.ulpCommand,
2880 					 saveq->iocb.ulpContext);
2881 		}
2882 	}
2883 
2884 	return rc;
2885 }
2886 
2887 /**
2888  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
2889  * @phba: Pointer to HBA context object.
2890  * @pring: Pointer to driver SLI ring object.
2891  *
2892  * This function is called from the iocb ring event handlers when
2893  * put pointer is ahead of the get pointer for a ring. This function signal
2894  * an error attention condition to the worker thread and the worker
2895  * thread will transition the HBA to offline state.
2896  **/
2897 static void
2898 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2899 {
2900 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2901 	/*
2902 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
2903 	 * rsp ring <portRspMax>
2904 	 */
2905 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2906 			"0312 Ring %d handler: portRspPut %d "
2907 			"is bigger than rsp ring %d\n",
2908 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
2909 			pring->sli.sli3.numRiocb);
2910 
2911 	phba->link_state = LPFC_HBA_ERROR;
2912 
2913 	/*
2914 	 * All error attention handlers are posted to
2915 	 * worker thread
2916 	 */
2917 	phba->work_ha |= HA_ERATT;
2918 	phba->work_hs = HS_FFER3;
2919 
2920 	lpfc_worker_wake_up(phba);
2921 
2922 	return;
2923 }
2924 
2925 /**
2926  * lpfc_poll_eratt - Error attention polling timer timeout handler
2927  * @ptr: Pointer to address of HBA context object.
2928  *
2929  * This function is invoked by the Error Attention polling timer when the
2930  * timer times out. It will check the SLI Error Attention register for
2931  * possible attention events. If so, it will post an Error Attention event
2932  * and wake up worker thread to process it. Otherwise, it will set up the
2933  * Error Attention polling timer for the next poll.
2934  **/
2935 void lpfc_poll_eratt(unsigned long ptr)
2936 {
2937 	struct lpfc_hba *phba;
2938 	uint32_t eratt = 0;
2939 	uint64_t sli_intr, cnt;
2940 
2941 	phba = (struct lpfc_hba *)ptr;
2942 
2943 	/* Here we will also keep track of interrupts per sec of the hba */
2944 	sli_intr = phba->sli.slistat.sli_intr;
2945 
2946 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
2947 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
2948 			sli_intr);
2949 	else
2950 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
2951 
2952 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
2953 	do_div(cnt, phba->eratt_poll_interval);
2954 	phba->sli.slistat.sli_ips = cnt;
2955 
2956 	phba->sli.slistat.sli_prev_intr = sli_intr;
2957 
2958 	/* Check chip HA register for error event */
2959 	eratt = lpfc_sli_check_eratt(phba);
2960 
2961 	if (eratt)
2962 		/* Tell the worker thread there is work to do */
2963 		lpfc_worker_wake_up(phba);
2964 	else
2965 		/* Restart the timer for next eratt poll */
2966 		mod_timer(&phba->eratt_poll,
2967 			  jiffies +
2968 			  msecs_to_jiffies(1000 * phba->eratt_poll_interval));
2969 	return;
2970 }
2971 
2972 
2973 /**
2974  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
2975  * @phba: Pointer to HBA context object.
2976  * @pring: Pointer to driver SLI ring object.
2977  * @mask: Host attention register mask for this ring.
2978  *
2979  * This function is called from the interrupt context when there is a ring
2980  * event for the fcp ring. The caller does not hold any lock.
2981  * The function processes each response iocb in the response ring until it
2982  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
2983  * LE bit set. The function will call the completion handler of the command iocb
2984  * if the response iocb indicates a completion for a command iocb or it is
2985  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
2986  * function if this is an unsolicited iocb.
2987  * This routine presumes LPFC_FCP_RING handling and doesn't bother
2988  * to check it explicitly.
2989  */
2990 int
2991 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
2992 				struct lpfc_sli_ring *pring, uint32_t mask)
2993 {
2994 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2995 	IOCB_t *irsp = NULL;
2996 	IOCB_t *entry = NULL;
2997 	struct lpfc_iocbq *cmdiocbq = NULL;
2998 	struct lpfc_iocbq rspiocbq;
2999 	uint32_t status;
3000 	uint32_t portRspPut, portRspMax;
3001 	int rc = 1;
3002 	lpfc_iocb_type type;
3003 	unsigned long iflag;
3004 	uint32_t rsp_cmpl = 0;
3005 
3006 	spin_lock_irqsave(&phba->hbalock, iflag);
3007 	pring->stats.iocb_event++;
3008 
3009 	/*
3010 	 * The next available response entry should never exceed the maximum
3011 	 * entries.  If it does, treat it as an adapter hardware error.
3012 	 */
3013 	portRspMax = pring->sli.sli3.numRiocb;
3014 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3015 	if (unlikely(portRspPut >= portRspMax)) {
3016 		lpfc_sli_rsp_pointers_error(phba, pring);
3017 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3018 		return 1;
3019 	}
3020 	if (phba->fcp_ring_in_use) {
3021 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3022 		return 1;
3023 	} else
3024 		phba->fcp_ring_in_use = 1;
3025 
3026 	rmb();
3027 	while (pring->sli.sli3.rspidx != portRspPut) {
3028 		/*
3029 		 * Fetch an entry off the ring and copy it into a local data
3030 		 * structure.  The copy involves a byte-swap since the
3031 		 * network byte order and pci byte orders are different.
3032 		 */
3033 		entry = lpfc_resp_iocb(phba, pring);
3034 		phba->last_completion_time = jiffies;
3035 
3036 		if (++pring->sli.sli3.rspidx >= portRspMax)
3037 			pring->sli.sli3.rspidx = 0;
3038 
3039 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
3040 				      (uint32_t *) &rspiocbq.iocb,
3041 				      phba->iocb_rsp_size);
3042 		INIT_LIST_HEAD(&(rspiocbq.list));
3043 		irsp = &rspiocbq.iocb;
3044 
3045 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
3046 		pring->stats.iocb_rsp++;
3047 		rsp_cmpl++;
3048 
3049 		if (unlikely(irsp->ulpStatus)) {
3050 			/*
3051 			 * If resource errors reported from HBA, reduce
3052 			 * queuedepths of the SCSI device.
3053 			 */
3054 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3055 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3056 			     IOERR_NO_RESOURCES)) {
3057 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3058 				phba->lpfc_rampdown_queue_depth(phba);
3059 				spin_lock_irqsave(&phba->hbalock, iflag);
3060 			}
3061 
3062 			/* Rsp ring <ringno> error: IOCB */
3063 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3064 					"0336 Rsp Ring %d error: IOCB Data: "
3065 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
3066 					pring->ringno,
3067 					irsp->un.ulpWord[0],
3068 					irsp->un.ulpWord[1],
3069 					irsp->un.ulpWord[2],
3070 					irsp->un.ulpWord[3],
3071 					irsp->un.ulpWord[4],
3072 					irsp->un.ulpWord[5],
3073 					*(uint32_t *)&irsp->un1,
3074 					*((uint32_t *)&irsp->un1 + 1));
3075 		}
3076 
3077 		switch (type) {
3078 		case LPFC_ABORT_IOCB:
3079 		case LPFC_SOL_IOCB:
3080 			/*
3081 			 * Idle exchange closed via ABTS from port.  No iocb
3082 			 * resources need to be recovered.
3083 			 */
3084 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
3085 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3086 						"0333 IOCB cmd 0x%x"
3087 						" processed. Skipping"
3088 						" completion\n",
3089 						irsp->ulpCommand);
3090 				break;
3091 			}
3092 
3093 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
3094 							 &rspiocbq);
3095 			if (unlikely(!cmdiocbq))
3096 				break;
3097 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
3098 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
3099 			if (cmdiocbq->iocb_cmpl) {
3100 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3101 				(cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
3102 						      &rspiocbq);
3103 				spin_lock_irqsave(&phba->hbalock, iflag);
3104 			}
3105 			break;
3106 		case LPFC_UNSOL_IOCB:
3107 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3108 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
3109 			spin_lock_irqsave(&phba->hbalock, iflag);
3110 			break;
3111 		default:
3112 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3113 				char adaptermsg[LPFC_MAX_ADPTMSG];
3114 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3115 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
3116 				       MAX_MSG_DATA);
3117 				dev_warn(&((phba->pcidev)->dev),
3118 					 "lpfc%d: %s\n",
3119 					 phba->brd_no, adaptermsg);
3120 			} else {
3121 				/* Unknown IOCB command */
3122 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3123 						"0334 Unknown IOCB command "
3124 						"Data: x%x, x%x x%x x%x x%x\n",
3125 						type, irsp->ulpCommand,
3126 						irsp->ulpStatus,
3127 						irsp->ulpIoTag,
3128 						irsp->ulpContext);
3129 			}
3130 			break;
3131 		}
3132 
3133 		/*
3134 		 * The response IOCB has been processed.  Update the ring
3135 		 * pointer in SLIM.  If the port response put pointer has not
3136 		 * been updated, sync the pgp->rspPutInx and fetch the new port
3137 		 * response put pointer.
3138 		 */
3139 		writel(pring->sli.sli3.rspidx,
3140 			&phba->host_gp[pring->ringno].rspGetInx);
3141 
3142 		if (pring->sli.sli3.rspidx == portRspPut)
3143 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3144 	}
3145 
3146 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
3147 		pring->stats.iocb_rsp_full++;
3148 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3149 		writel(status, phba->CAregaddr);
3150 		readl(phba->CAregaddr);
3151 	}
3152 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3153 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3154 		pring->stats.iocb_cmd_empty++;
3155 
3156 		/* Force update of the local copy of cmdGetInx */
3157 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3158 		lpfc_sli_resume_iocb(phba, pring);
3159 
3160 		if ((pring->lpfc_sli_cmd_available))
3161 			(pring->lpfc_sli_cmd_available) (phba, pring);
3162 
3163 	}
3164 
3165 	phba->fcp_ring_in_use = 0;
3166 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3167 	return rc;
3168 }
3169 
3170 /**
3171  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
3172  * @phba: Pointer to HBA context object.
3173  * @pring: Pointer to driver SLI ring object.
3174  * @rspiocbp: Pointer to driver response IOCB object.
3175  *
3176  * This function is called from the worker thread when there is a slow-path
3177  * response IOCB to process. This function chains all the response iocbs until
3178  * seeing the iocb with the LE bit set. The function will call
3179  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
3180  * completion of a command iocb. The function will call the
3181  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
3182  * The function frees the resources or calls the completion handler if this
3183  * iocb is an abort completion. The function returns NULL when the response
3184  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
3185  * this function shall chain the iocb on to the iocb_continueq and return the
3186  * response iocb passed in.
3187  **/
3188 static struct lpfc_iocbq *
3189 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3190 			struct lpfc_iocbq *rspiocbp)
3191 {
3192 	struct lpfc_iocbq *saveq;
3193 	struct lpfc_iocbq *cmdiocbp;
3194 	struct lpfc_iocbq *next_iocb;
3195 	IOCB_t *irsp = NULL;
3196 	uint32_t free_saveq;
3197 	uint8_t iocb_cmd_type;
3198 	lpfc_iocb_type type;
3199 	unsigned long iflag;
3200 	int rc;
3201 
3202 	spin_lock_irqsave(&phba->hbalock, iflag);
3203 	/* First add the response iocb to the countinueq list */
3204 	list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
3205 	pring->iocb_continueq_cnt++;
3206 
3207 	/* Now, determine whether the list is completed for processing */
3208 	irsp = &rspiocbp->iocb;
3209 	if (irsp->ulpLe) {
3210 		/*
3211 		 * By default, the driver expects to free all resources
3212 		 * associated with this iocb completion.
3213 		 */
3214 		free_saveq = 1;
3215 		saveq = list_get_first(&pring->iocb_continueq,
3216 				       struct lpfc_iocbq, list);
3217 		irsp = &(saveq->iocb);
3218 		list_del_init(&pring->iocb_continueq);
3219 		pring->iocb_continueq_cnt = 0;
3220 
3221 		pring->stats.iocb_rsp++;
3222 
3223 		/*
3224 		 * If resource errors reported from HBA, reduce
3225 		 * queuedepths of the SCSI device.
3226 		 */
3227 		if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3228 		    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3229 		     IOERR_NO_RESOURCES)) {
3230 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3231 			phba->lpfc_rampdown_queue_depth(phba);
3232 			spin_lock_irqsave(&phba->hbalock, iflag);
3233 		}
3234 
3235 		if (irsp->ulpStatus) {
3236 			/* Rsp ring <ringno> error: IOCB */
3237 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3238 					"0328 Rsp Ring %d error: "
3239 					"IOCB Data: "
3240 					"x%x x%x x%x x%x "
3241 					"x%x x%x x%x x%x "
3242 					"x%x x%x x%x x%x "
3243 					"x%x x%x x%x x%x\n",
3244 					pring->ringno,
3245 					irsp->un.ulpWord[0],
3246 					irsp->un.ulpWord[1],
3247 					irsp->un.ulpWord[2],
3248 					irsp->un.ulpWord[3],
3249 					irsp->un.ulpWord[4],
3250 					irsp->un.ulpWord[5],
3251 					*(((uint32_t *) irsp) + 6),
3252 					*(((uint32_t *) irsp) + 7),
3253 					*(((uint32_t *) irsp) + 8),
3254 					*(((uint32_t *) irsp) + 9),
3255 					*(((uint32_t *) irsp) + 10),
3256 					*(((uint32_t *) irsp) + 11),
3257 					*(((uint32_t *) irsp) + 12),
3258 					*(((uint32_t *) irsp) + 13),
3259 					*(((uint32_t *) irsp) + 14),
3260 					*(((uint32_t *) irsp) + 15));
3261 		}
3262 
3263 		/*
3264 		 * Fetch the IOCB command type and call the correct completion
3265 		 * routine. Solicited and Unsolicited IOCBs on the ELS ring
3266 		 * get freed back to the lpfc_iocb_list by the discovery
3267 		 * kernel thread.
3268 		 */
3269 		iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
3270 		type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
3271 		switch (type) {
3272 		case LPFC_SOL_IOCB:
3273 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3274 			rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
3275 			spin_lock_irqsave(&phba->hbalock, iflag);
3276 			break;
3277 
3278 		case LPFC_UNSOL_IOCB:
3279 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3280 			rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
3281 			spin_lock_irqsave(&phba->hbalock, iflag);
3282 			if (!rc)
3283 				free_saveq = 0;
3284 			break;
3285 
3286 		case LPFC_ABORT_IOCB:
3287 			cmdiocbp = NULL;
3288 			if (irsp->ulpCommand != CMD_XRI_ABORTED_CX)
3289 				cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
3290 								 saveq);
3291 			if (cmdiocbp) {
3292 				/* Call the specified completion routine */
3293 				if (cmdiocbp->iocb_cmpl) {
3294 					spin_unlock_irqrestore(&phba->hbalock,
3295 							       iflag);
3296 					(cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
3297 							      saveq);
3298 					spin_lock_irqsave(&phba->hbalock,
3299 							  iflag);
3300 				} else
3301 					__lpfc_sli_release_iocbq(phba,
3302 								 cmdiocbp);
3303 			}
3304 			break;
3305 
3306 		case LPFC_UNKNOWN_IOCB:
3307 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3308 				char adaptermsg[LPFC_MAX_ADPTMSG];
3309 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3310 				memcpy(&adaptermsg[0], (uint8_t *)irsp,
3311 				       MAX_MSG_DATA);
3312 				dev_warn(&((phba->pcidev)->dev),
3313 					 "lpfc%d: %s\n",
3314 					 phba->brd_no, adaptermsg);
3315 			} else {
3316 				/* Unknown IOCB command */
3317 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3318 						"0335 Unknown IOCB "
3319 						"command Data: x%x "
3320 						"x%x x%x x%x\n",
3321 						irsp->ulpCommand,
3322 						irsp->ulpStatus,
3323 						irsp->ulpIoTag,
3324 						irsp->ulpContext);
3325 			}
3326 			break;
3327 		}
3328 
3329 		if (free_saveq) {
3330 			list_for_each_entry_safe(rspiocbp, next_iocb,
3331 						 &saveq->list, list) {
3332 				list_del_init(&rspiocbp->list);
3333 				__lpfc_sli_release_iocbq(phba, rspiocbp);
3334 			}
3335 			__lpfc_sli_release_iocbq(phba, saveq);
3336 		}
3337 		rspiocbp = NULL;
3338 	}
3339 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3340 	return rspiocbp;
3341 }
3342 
3343 /**
3344  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
3345  * @phba: Pointer to HBA context object.
3346  * @pring: Pointer to driver SLI ring object.
3347  * @mask: Host attention register mask for this ring.
3348  *
3349  * This routine wraps the actual slow_ring event process routine from the
3350  * API jump table function pointer from the lpfc_hba struct.
3351  **/
3352 void
3353 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
3354 				struct lpfc_sli_ring *pring, uint32_t mask)
3355 {
3356 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
3357 }
3358 
3359 /**
3360  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
3361  * @phba: Pointer to HBA context object.
3362  * @pring: Pointer to driver SLI ring object.
3363  * @mask: Host attention register mask for this ring.
3364  *
3365  * This function is called from the worker thread when there is a ring event
3366  * for non-fcp rings. The caller does not hold any lock. The function will
3367  * remove each response iocb in the response ring and calls the handle
3368  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3369  **/
3370 static void
3371 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
3372 				   struct lpfc_sli_ring *pring, uint32_t mask)
3373 {
3374 	struct lpfc_pgp *pgp;
3375 	IOCB_t *entry;
3376 	IOCB_t *irsp = NULL;
3377 	struct lpfc_iocbq *rspiocbp = NULL;
3378 	uint32_t portRspPut, portRspMax;
3379 	unsigned long iflag;
3380 	uint32_t status;
3381 
3382 	pgp = &phba->port_gp[pring->ringno];
3383 	spin_lock_irqsave(&phba->hbalock, iflag);
3384 	pring->stats.iocb_event++;
3385 
3386 	/*
3387 	 * The next available response entry should never exceed the maximum
3388 	 * entries.  If it does, treat it as an adapter hardware error.
3389 	 */
3390 	portRspMax = pring->sli.sli3.numRiocb;
3391 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3392 	if (portRspPut >= portRspMax) {
3393 		/*
3394 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3395 		 * rsp ring <portRspMax>
3396 		 */
3397 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3398 				"0303 Ring %d handler: portRspPut %d "
3399 				"is bigger than rsp ring %d\n",
3400 				pring->ringno, portRspPut, portRspMax);
3401 
3402 		phba->link_state = LPFC_HBA_ERROR;
3403 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3404 
3405 		phba->work_hs = HS_FFER3;
3406 		lpfc_handle_eratt(phba);
3407 
3408 		return;
3409 	}
3410 
3411 	rmb();
3412 	while (pring->sli.sli3.rspidx != portRspPut) {
3413 		/*
3414 		 * Build a completion list and call the appropriate handler.
3415 		 * The process is to get the next available response iocb, get
3416 		 * a free iocb from the list, copy the response data into the
3417 		 * free iocb, insert to the continuation list, and update the
3418 		 * next response index to slim.  This process makes response
3419 		 * iocb's in the ring available to DMA as fast as possible but
3420 		 * pays a penalty for a copy operation.  Since the iocb is
3421 		 * only 32 bytes, this penalty is considered small relative to
3422 		 * the PCI reads for register values and a slim write.  When
3423 		 * the ulpLe field is set, the entire Command has been
3424 		 * received.
3425 		 */
3426 		entry = lpfc_resp_iocb(phba, pring);
3427 
3428 		phba->last_completion_time = jiffies;
3429 		rspiocbp = __lpfc_sli_get_iocbq(phba);
3430 		if (rspiocbp == NULL) {
3431 			printk(KERN_ERR "%s: out of buffers! Failing "
3432 			       "completion.\n", __func__);
3433 			break;
3434 		}
3435 
3436 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
3437 				      phba->iocb_rsp_size);
3438 		irsp = &rspiocbp->iocb;
3439 
3440 		if (++pring->sli.sli3.rspidx >= portRspMax)
3441 			pring->sli.sli3.rspidx = 0;
3442 
3443 		if (pring->ringno == LPFC_ELS_RING) {
3444 			lpfc_debugfs_slow_ring_trc(phba,
3445 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
3446 				*(((uint32_t *) irsp) + 4),
3447 				*(((uint32_t *) irsp) + 6),
3448 				*(((uint32_t *) irsp) + 7));
3449 		}
3450 
3451 		writel(pring->sli.sli3.rspidx,
3452 			&phba->host_gp[pring->ringno].rspGetInx);
3453 
3454 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3455 		/* Handle the response IOCB */
3456 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
3457 		spin_lock_irqsave(&phba->hbalock, iflag);
3458 
3459 		/*
3460 		 * If the port response put pointer has not been updated, sync
3461 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
3462 		 * response put pointer.
3463 		 */
3464 		if (pring->sli.sli3.rspidx == portRspPut) {
3465 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3466 		}
3467 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
3468 
3469 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
3470 		/* At least one response entry has been freed */
3471 		pring->stats.iocb_rsp_full++;
3472 		/* SET RxRE_RSP in Chip Att register */
3473 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3474 		writel(status, phba->CAregaddr);
3475 		readl(phba->CAregaddr); /* flush */
3476 	}
3477 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3478 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3479 		pring->stats.iocb_cmd_empty++;
3480 
3481 		/* Force update of the local copy of cmdGetInx */
3482 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3483 		lpfc_sli_resume_iocb(phba, pring);
3484 
3485 		if ((pring->lpfc_sli_cmd_available))
3486 			(pring->lpfc_sli_cmd_available) (phba, pring);
3487 
3488 	}
3489 
3490 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3491 	return;
3492 }
3493 
3494 /**
3495  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
3496  * @phba: Pointer to HBA context object.
3497  * @pring: Pointer to driver SLI ring object.
3498  * @mask: Host attention register mask for this ring.
3499  *
3500  * This function is called from the worker thread when there is a pending
3501  * ELS response iocb on the driver internal slow-path response iocb worker
3502  * queue. The caller does not hold any lock. The function will remove each
3503  * response iocb from the response worker queue and calls the handle
3504  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3505  **/
3506 static void
3507 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
3508 				   struct lpfc_sli_ring *pring, uint32_t mask)
3509 {
3510 	struct lpfc_iocbq *irspiocbq;
3511 	struct hbq_dmabuf *dmabuf;
3512 	struct lpfc_cq_event *cq_event;
3513 	unsigned long iflag;
3514 
3515 	spin_lock_irqsave(&phba->hbalock, iflag);
3516 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
3517 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3518 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
3519 		/* Get the response iocb from the head of work queue */
3520 		spin_lock_irqsave(&phba->hbalock, iflag);
3521 		list_remove_head(&phba->sli4_hba.sp_queue_event,
3522 				 cq_event, struct lpfc_cq_event, list);
3523 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3524 
3525 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
3526 		case CQE_CODE_COMPL_WQE:
3527 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
3528 						 cq_event);
3529 			/* Translate ELS WCQE to response IOCBQ */
3530 			irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
3531 								   irspiocbq);
3532 			if (irspiocbq)
3533 				lpfc_sli_sp_handle_rspiocb(phba, pring,
3534 							   irspiocbq);
3535 			break;
3536 		case CQE_CODE_RECEIVE:
3537 		case CQE_CODE_RECEIVE_V1:
3538 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
3539 					      cq_event);
3540 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
3541 			break;
3542 		default:
3543 			break;
3544 		}
3545 	}
3546 }
3547 
3548 /**
3549  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
3550  * @phba: Pointer to HBA context object.
3551  * @pring: Pointer to driver SLI ring object.
3552  *
3553  * This function aborts all iocbs in the given ring and frees all the iocb
3554  * objects in txq. This function issues an abort iocb for all the iocb commands
3555  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3556  * the return of this function. The caller is not required to hold any locks.
3557  **/
3558 void
3559 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3560 {
3561 	LIST_HEAD(completions);
3562 	struct lpfc_iocbq *iocb, *next_iocb;
3563 
3564 	if (pring->ringno == LPFC_ELS_RING) {
3565 		lpfc_fabric_abort_hba(phba);
3566 	}
3567 
3568 	/* Error everything on txq and txcmplq
3569 	 * First do the txq.
3570 	 */
3571 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3572 		spin_lock_irq(&pring->ring_lock);
3573 		list_splice_init(&pring->txq, &completions);
3574 		pring->txq_cnt = 0;
3575 		spin_unlock_irq(&pring->ring_lock);
3576 
3577 		spin_lock_irq(&phba->hbalock);
3578 		/* Next issue ABTS for everything on the txcmplq */
3579 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3580 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3581 		spin_unlock_irq(&phba->hbalock);
3582 	} else {
3583 		spin_lock_irq(&phba->hbalock);
3584 		list_splice_init(&pring->txq, &completions);
3585 		pring->txq_cnt = 0;
3586 
3587 		/* Next issue ABTS for everything on the txcmplq */
3588 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3589 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3590 		spin_unlock_irq(&phba->hbalock);
3591 	}
3592 
3593 	/* Cancel all the IOCBs from the completions list */
3594 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
3595 			      IOERR_SLI_ABORTED);
3596 }
3597 
3598 /**
3599  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
3600  * @phba: Pointer to HBA context object.
3601  * @pring: Pointer to driver SLI ring object.
3602  *
3603  * This function aborts all iocbs in FCP rings and frees all the iocb
3604  * objects in txq. This function issues an abort iocb for all the iocb commands
3605  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3606  * the return of this function. The caller is not required to hold any locks.
3607  **/
3608 void
3609 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
3610 {
3611 	struct lpfc_sli *psli = &phba->sli;
3612 	struct lpfc_sli_ring  *pring;
3613 	uint32_t i;
3614 
3615 	/* Look on all the FCP Rings for the iotag */
3616 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3617 		for (i = 0; i < phba->cfg_fcp_io_channel; i++) {
3618 			pring = &psli->ring[i + MAX_SLI3_CONFIGURED_RINGS];
3619 			lpfc_sli_abort_iocb_ring(phba, pring);
3620 		}
3621 	} else {
3622 		pring = &psli->ring[psli->fcp_ring];
3623 		lpfc_sli_abort_iocb_ring(phba, pring);
3624 	}
3625 }
3626 
3627 
3628 /**
3629  * lpfc_sli_flush_fcp_rings - flush all iocbs in the fcp ring
3630  * @phba: Pointer to HBA context object.
3631  *
3632  * This function flushes all iocbs in the fcp ring and frees all the iocb
3633  * objects in txq and txcmplq. This function will not issue abort iocbs
3634  * for all the iocb commands in txcmplq, they will just be returned with
3635  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
3636  * slot has been permanently disabled.
3637  **/
3638 void
3639 lpfc_sli_flush_fcp_rings(struct lpfc_hba *phba)
3640 {
3641 	LIST_HEAD(txq);
3642 	LIST_HEAD(txcmplq);
3643 	struct lpfc_sli *psli = &phba->sli;
3644 	struct lpfc_sli_ring  *pring;
3645 	uint32_t i;
3646 
3647 	spin_lock_irq(&phba->hbalock);
3648 	/* Indicate the I/O queues are flushed */
3649 	phba->hba_flag |= HBA_FCP_IOQ_FLUSH;
3650 	spin_unlock_irq(&phba->hbalock);
3651 
3652 	/* Look on all the FCP Rings for the iotag */
3653 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3654 		for (i = 0; i < phba->cfg_fcp_io_channel; i++) {
3655 			pring = &psli->ring[i + MAX_SLI3_CONFIGURED_RINGS];
3656 
3657 			spin_lock_irq(&pring->ring_lock);
3658 			/* Retrieve everything on txq */
3659 			list_splice_init(&pring->txq, &txq);
3660 			/* Retrieve everything on the txcmplq */
3661 			list_splice_init(&pring->txcmplq, &txcmplq);
3662 			pring->txq_cnt = 0;
3663 			pring->txcmplq_cnt = 0;
3664 			spin_unlock_irq(&pring->ring_lock);
3665 
3666 			/* Flush the txq */
3667 			lpfc_sli_cancel_iocbs(phba, &txq,
3668 					      IOSTAT_LOCAL_REJECT,
3669 					      IOERR_SLI_DOWN);
3670 			/* Flush the txcmpq */
3671 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
3672 					      IOSTAT_LOCAL_REJECT,
3673 					      IOERR_SLI_DOWN);
3674 		}
3675 	} else {
3676 		pring = &psli->ring[psli->fcp_ring];
3677 
3678 		spin_lock_irq(&phba->hbalock);
3679 		/* Retrieve everything on txq */
3680 		list_splice_init(&pring->txq, &txq);
3681 		/* Retrieve everything on the txcmplq */
3682 		list_splice_init(&pring->txcmplq, &txcmplq);
3683 		pring->txq_cnt = 0;
3684 		pring->txcmplq_cnt = 0;
3685 		spin_unlock_irq(&phba->hbalock);
3686 
3687 		/* Flush the txq */
3688 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
3689 				      IOERR_SLI_DOWN);
3690 		/* Flush the txcmpq */
3691 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
3692 				      IOERR_SLI_DOWN);
3693 	}
3694 }
3695 
3696 /**
3697  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
3698  * @phba: Pointer to HBA context object.
3699  * @mask: Bit mask to be checked.
3700  *
3701  * This function reads the host status register and compares
3702  * with the provided bit mask to check if HBA completed
3703  * the restart. This function will wait in a loop for the
3704  * HBA to complete restart. If the HBA does not restart within
3705  * 15 iterations, the function will reset the HBA again. The
3706  * function returns 1 when HBA fail to restart otherwise returns
3707  * zero.
3708  **/
3709 static int
3710 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
3711 {
3712 	uint32_t status;
3713 	int i = 0;
3714 	int retval = 0;
3715 
3716 	/* Read the HBA Host Status Register */
3717 	if (lpfc_readl(phba->HSregaddr, &status))
3718 		return 1;
3719 
3720 	/*
3721 	 * Check status register every 100ms for 5 retries, then every
3722 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
3723 	 * every 2.5 sec for 4.
3724 	 * Break our of the loop if errors occurred during init.
3725 	 */
3726 	while (((status & mask) != mask) &&
3727 	       !(status & HS_FFERM) &&
3728 	       i++ < 20) {
3729 
3730 		if (i <= 5)
3731 			msleep(10);
3732 		else if (i <= 10)
3733 			msleep(500);
3734 		else
3735 			msleep(2500);
3736 
3737 		if (i == 15) {
3738 				/* Do post */
3739 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
3740 			lpfc_sli_brdrestart(phba);
3741 		}
3742 		/* Read the HBA Host Status Register */
3743 		if (lpfc_readl(phba->HSregaddr, &status)) {
3744 			retval = 1;
3745 			break;
3746 		}
3747 	}
3748 
3749 	/* Check to see if any errors occurred during init */
3750 	if ((status & HS_FFERM) || (i >= 20)) {
3751 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3752 				"2751 Adapter failed to restart, "
3753 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
3754 				status,
3755 				readl(phba->MBslimaddr + 0xa8),
3756 				readl(phba->MBslimaddr + 0xac));
3757 		phba->link_state = LPFC_HBA_ERROR;
3758 		retval = 1;
3759 	}
3760 
3761 	return retval;
3762 }
3763 
3764 /**
3765  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
3766  * @phba: Pointer to HBA context object.
3767  * @mask: Bit mask to be checked.
3768  *
3769  * This function checks the host status register to check if HBA is
3770  * ready. This function will wait in a loop for the HBA to be ready
3771  * If the HBA is not ready , the function will will reset the HBA PCI
3772  * function again. The function returns 1 when HBA fail to be ready
3773  * otherwise returns zero.
3774  **/
3775 static int
3776 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
3777 {
3778 	uint32_t status;
3779 	int retval = 0;
3780 
3781 	/* Read the HBA Host Status Register */
3782 	status = lpfc_sli4_post_status_check(phba);
3783 
3784 	if (status) {
3785 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
3786 		lpfc_sli_brdrestart(phba);
3787 		status = lpfc_sli4_post_status_check(phba);
3788 	}
3789 
3790 	/* Check to see if any errors occurred during init */
3791 	if (status) {
3792 		phba->link_state = LPFC_HBA_ERROR;
3793 		retval = 1;
3794 	} else
3795 		phba->sli4_hba.intr_enable = 0;
3796 
3797 	return retval;
3798 }
3799 
3800 /**
3801  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
3802  * @phba: Pointer to HBA context object.
3803  * @mask: Bit mask to be checked.
3804  *
3805  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
3806  * from the API jump table function pointer from the lpfc_hba struct.
3807  **/
3808 int
3809 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
3810 {
3811 	return phba->lpfc_sli_brdready(phba, mask);
3812 }
3813 
3814 #define BARRIER_TEST_PATTERN (0xdeadbeef)
3815 
3816 /**
3817  * lpfc_reset_barrier - Make HBA ready for HBA reset
3818  * @phba: Pointer to HBA context object.
3819  *
3820  * This function is called before resetting an HBA. This function is called
3821  * with hbalock held and requests HBA to quiesce DMAs before a reset.
3822  **/
3823 void lpfc_reset_barrier(struct lpfc_hba *phba)
3824 {
3825 	uint32_t __iomem *resp_buf;
3826 	uint32_t __iomem *mbox_buf;
3827 	volatile uint32_t mbox;
3828 	uint32_t hc_copy, ha_copy, resp_data;
3829 	int  i;
3830 	uint8_t hdrtype;
3831 
3832 	lockdep_assert_held(&phba->hbalock);
3833 
3834 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
3835 	if (hdrtype != 0x80 ||
3836 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
3837 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
3838 		return;
3839 
3840 	/*
3841 	 * Tell the other part of the chip to suspend temporarily all
3842 	 * its DMA activity.
3843 	 */
3844 	resp_buf = phba->MBslimaddr;
3845 
3846 	/* Disable the error attention */
3847 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
3848 		return;
3849 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
3850 	readl(phba->HCregaddr); /* flush */
3851 	phba->link_flag |= LS_IGNORE_ERATT;
3852 
3853 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
3854 		return;
3855 	if (ha_copy & HA_ERATT) {
3856 		/* Clear Chip error bit */
3857 		writel(HA_ERATT, phba->HAregaddr);
3858 		phba->pport->stopped = 1;
3859 	}
3860 
3861 	mbox = 0;
3862 	((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
3863 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
3864 
3865 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
3866 	mbox_buf = phba->MBslimaddr;
3867 	writel(mbox, mbox_buf);
3868 
3869 	for (i = 0; i < 50; i++) {
3870 		if (lpfc_readl((resp_buf + 1), &resp_data))
3871 			return;
3872 		if (resp_data != ~(BARRIER_TEST_PATTERN))
3873 			mdelay(1);
3874 		else
3875 			break;
3876 	}
3877 	resp_data = 0;
3878 	if (lpfc_readl((resp_buf + 1), &resp_data))
3879 		return;
3880 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
3881 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
3882 		    phba->pport->stopped)
3883 			goto restore_hc;
3884 		else
3885 			goto clear_errat;
3886 	}
3887 
3888 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
3889 	resp_data = 0;
3890 	for (i = 0; i < 500; i++) {
3891 		if (lpfc_readl(resp_buf, &resp_data))
3892 			return;
3893 		if (resp_data != mbox)
3894 			mdelay(1);
3895 		else
3896 			break;
3897 	}
3898 
3899 clear_errat:
3900 
3901 	while (++i < 500) {
3902 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
3903 			return;
3904 		if (!(ha_copy & HA_ERATT))
3905 			mdelay(1);
3906 		else
3907 			break;
3908 	}
3909 
3910 	if (readl(phba->HAregaddr) & HA_ERATT) {
3911 		writel(HA_ERATT, phba->HAregaddr);
3912 		phba->pport->stopped = 1;
3913 	}
3914 
3915 restore_hc:
3916 	phba->link_flag &= ~LS_IGNORE_ERATT;
3917 	writel(hc_copy, phba->HCregaddr);
3918 	readl(phba->HCregaddr); /* flush */
3919 }
3920 
3921 /**
3922  * lpfc_sli_brdkill - Issue a kill_board mailbox command
3923  * @phba: Pointer to HBA context object.
3924  *
3925  * This function issues a kill_board mailbox command and waits for
3926  * the error attention interrupt. This function is called for stopping
3927  * the firmware processing. The caller is not required to hold any
3928  * locks. This function calls lpfc_hba_down_post function to free
3929  * any pending commands after the kill. The function will return 1 when it
3930  * fails to kill the board else will return 0.
3931  **/
3932 int
3933 lpfc_sli_brdkill(struct lpfc_hba *phba)
3934 {
3935 	struct lpfc_sli *psli;
3936 	LPFC_MBOXQ_t *pmb;
3937 	uint32_t status;
3938 	uint32_t ha_copy;
3939 	int retval;
3940 	int i = 0;
3941 
3942 	psli = &phba->sli;
3943 
3944 	/* Kill HBA */
3945 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3946 			"0329 Kill HBA Data: x%x x%x\n",
3947 			phba->pport->port_state, psli->sli_flag);
3948 
3949 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
3950 	if (!pmb)
3951 		return 1;
3952 
3953 	/* Disable the error attention */
3954 	spin_lock_irq(&phba->hbalock);
3955 	if (lpfc_readl(phba->HCregaddr, &status)) {
3956 		spin_unlock_irq(&phba->hbalock);
3957 		mempool_free(pmb, phba->mbox_mem_pool);
3958 		return 1;
3959 	}
3960 	status &= ~HC_ERINT_ENA;
3961 	writel(status, phba->HCregaddr);
3962 	readl(phba->HCregaddr); /* flush */
3963 	phba->link_flag |= LS_IGNORE_ERATT;
3964 	spin_unlock_irq(&phba->hbalock);
3965 
3966 	lpfc_kill_board(phba, pmb);
3967 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
3968 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3969 
3970 	if (retval != MBX_SUCCESS) {
3971 		if (retval != MBX_BUSY)
3972 			mempool_free(pmb, phba->mbox_mem_pool);
3973 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3974 				"2752 KILL_BOARD command failed retval %d\n",
3975 				retval);
3976 		spin_lock_irq(&phba->hbalock);
3977 		phba->link_flag &= ~LS_IGNORE_ERATT;
3978 		spin_unlock_irq(&phba->hbalock);
3979 		return 1;
3980 	}
3981 
3982 	spin_lock_irq(&phba->hbalock);
3983 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
3984 	spin_unlock_irq(&phba->hbalock);
3985 
3986 	mempool_free(pmb, phba->mbox_mem_pool);
3987 
3988 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
3989 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
3990 	 * 3 seconds we still set HBA_ERROR state because the status of the
3991 	 * board is now undefined.
3992 	 */
3993 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
3994 		return 1;
3995 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
3996 		mdelay(100);
3997 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
3998 			return 1;
3999 	}
4000 
4001 	del_timer_sync(&psli->mbox_tmo);
4002 	if (ha_copy & HA_ERATT) {
4003 		writel(HA_ERATT, phba->HAregaddr);
4004 		phba->pport->stopped = 1;
4005 	}
4006 	spin_lock_irq(&phba->hbalock);
4007 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4008 	psli->mbox_active = NULL;
4009 	phba->link_flag &= ~LS_IGNORE_ERATT;
4010 	spin_unlock_irq(&phba->hbalock);
4011 
4012 	lpfc_hba_down_post(phba);
4013 	phba->link_state = LPFC_HBA_ERROR;
4014 
4015 	return ha_copy & HA_ERATT ? 0 : 1;
4016 }
4017 
4018 /**
4019  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
4020  * @phba: Pointer to HBA context object.
4021  *
4022  * This function resets the HBA by writing HC_INITFF to the control
4023  * register. After the HBA resets, this function resets all the iocb ring
4024  * indices. This function disables PCI layer parity checking during
4025  * the reset.
4026  * This function returns 0 always.
4027  * The caller is not required to hold any locks.
4028  **/
4029 int
4030 lpfc_sli_brdreset(struct lpfc_hba *phba)
4031 {
4032 	struct lpfc_sli *psli;
4033 	struct lpfc_sli_ring *pring;
4034 	uint16_t cfg_value;
4035 	int i;
4036 
4037 	psli = &phba->sli;
4038 
4039 	/* Reset HBA */
4040 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4041 			"0325 Reset HBA Data: x%x x%x\n",
4042 			phba->pport->port_state, psli->sli_flag);
4043 
4044 	/* perform board reset */
4045 	phba->fc_eventTag = 0;
4046 	phba->link_events = 0;
4047 	phba->pport->fc_myDID = 0;
4048 	phba->pport->fc_prevDID = 0;
4049 
4050 	/* Turn off parity checking and serr during the physical reset */
4051 	pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value);
4052 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
4053 			      (cfg_value &
4054 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4055 
4056 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
4057 
4058 	/* Now toggle INITFF bit in the Host Control Register */
4059 	writel(HC_INITFF, phba->HCregaddr);
4060 	mdelay(1);
4061 	readl(phba->HCregaddr); /* flush */
4062 	writel(0, phba->HCregaddr);
4063 	readl(phba->HCregaddr); /* flush */
4064 
4065 	/* Restore PCI cmd register */
4066 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4067 
4068 	/* Initialize relevant SLI info */
4069 	for (i = 0; i < psli->num_rings; i++) {
4070 		pring = &psli->ring[i];
4071 		pring->flag = 0;
4072 		pring->sli.sli3.rspidx = 0;
4073 		pring->sli.sli3.next_cmdidx  = 0;
4074 		pring->sli.sli3.local_getidx = 0;
4075 		pring->sli.sli3.cmdidx = 0;
4076 		pring->missbufcnt = 0;
4077 	}
4078 
4079 	phba->link_state = LPFC_WARM_START;
4080 	return 0;
4081 }
4082 
4083 /**
4084  * lpfc_sli4_brdreset - Reset a sli-4 HBA
4085  * @phba: Pointer to HBA context object.
4086  *
4087  * This function resets a SLI4 HBA. This function disables PCI layer parity
4088  * checking during resets the device. The caller is not required to hold
4089  * any locks.
4090  *
4091  * This function returns 0 always.
4092  **/
4093 int
4094 lpfc_sli4_brdreset(struct lpfc_hba *phba)
4095 {
4096 	struct lpfc_sli *psli = &phba->sli;
4097 	uint16_t cfg_value;
4098 	int rc = 0;
4099 
4100 	/* Reset HBA */
4101 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4102 			"0295 Reset HBA Data: x%x x%x x%x\n",
4103 			phba->pport->port_state, psli->sli_flag,
4104 			phba->hba_flag);
4105 
4106 	/* perform board reset */
4107 	phba->fc_eventTag = 0;
4108 	phba->link_events = 0;
4109 	phba->pport->fc_myDID = 0;
4110 	phba->pport->fc_prevDID = 0;
4111 
4112 	spin_lock_irq(&phba->hbalock);
4113 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
4114 	phba->fcf.fcf_flag = 0;
4115 	spin_unlock_irq(&phba->hbalock);
4116 
4117 	/* SLI4 INTF 2: if FW dump is being taken skip INIT_PORT */
4118 	if (phba->hba_flag & HBA_FW_DUMP_OP) {
4119 		phba->hba_flag &= ~HBA_FW_DUMP_OP;
4120 		return rc;
4121 	}
4122 
4123 	/* Now physically reset the device */
4124 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4125 			"0389 Performing PCI function reset!\n");
4126 
4127 	/* Turn off parity checking and serr during the physical reset */
4128 	pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value);
4129 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
4130 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4131 
4132 	/* Perform FCoE PCI function reset before freeing queue memory */
4133 	rc = lpfc_pci_function_reset(phba);
4134 	lpfc_sli4_queue_destroy(phba);
4135 
4136 	/* Restore PCI cmd register */
4137 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4138 
4139 	return rc;
4140 }
4141 
4142 /**
4143  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
4144  * @phba: Pointer to HBA context object.
4145  *
4146  * This function is called in the SLI initialization code path to
4147  * restart the HBA. The caller is not required to hold any lock.
4148  * This function writes MBX_RESTART mailbox command to the SLIM and
4149  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
4150  * function to free any pending commands. The function enables
4151  * POST only during the first initialization. The function returns zero.
4152  * The function does not guarantee completion of MBX_RESTART mailbox
4153  * command before the return of this function.
4154  **/
4155 static int
4156 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
4157 {
4158 	MAILBOX_t *mb;
4159 	struct lpfc_sli *psli;
4160 	volatile uint32_t word0;
4161 	void __iomem *to_slim;
4162 	uint32_t hba_aer_enabled;
4163 
4164 	spin_lock_irq(&phba->hbalock);
4165 
4166 	/* Take PCIe device Advanced Error Reporting (AER) state */
4167 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4168 
4169 	psli = &phba->sli;
4170 
4171 	/* Restart HBA */
4172 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4173 			"0337 Restart HBA Data: x%x x%x\n",
4174 			phba->pport->port_state, psli->sli_flag);
4175 
4176 	word0 = 0;
4177 	mb = (MAILBOX_t *) &word0;
4178 	mb->mbxCommand = MBX_RESTART;
4179 	mb->mbxHc = 1;
4180 
4181 	lpfc_reset_barrier(phba);
4182 
4183 	to_slim = phba->MBslimaddr;
4184 	writel(*(uint32_t *) mb, to_slim);
4185 	readl(to_slim); /* flush */
4186 
4187 	/* Only skip post after fc_ffinit is completed */
4188 	if (phba->pport->port_state)
4189 		word0 = 1;	/* This is really setting up word1 */
4190 	else
4191 		word0 = 0;	/* This is really setting up word1 */
4192 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
4193 	writel(*(uint32_t *) mb, to_slim);
4194 	readl(to_slim); /* flush */
4195 
4196 	lpfc_sli_brdreset(phba);
4197 	phba->pport->stopped = 0;
4198 	phba->link_state = LPFC_INIT_START;
4199 	phba->hba_flag = 0;
4200 	spin_unlock_irq(&phba->hbalock);
4201 
4202 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4203 	psli->stats_start = get_seconds();
4204 
4205 	/* Give the INITFF and Post time to settle. */
4206 	mdelay(100);
4207 
4208 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4209 	if (hba_aer_enabled)
4210 		pci_disable_pcie_error_reporting(phba->pcidev);
4211 
4212 	lpfc_hba_down_post(phba);
4213 
4214 	return 0;
4215 }
4216 
4217 /**
4218  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
4219  * @phba: Pointer to HBA context object.
4220  *
4221  * This function is called in the SLI initialization code path to restart
4222  * a SLI4 HBA. The caller is not required to hold any lock.
4223  * At the end of the function, it calls lpfc_hba_down_post function to
4224  * free any pending commands.
4225  **/
4226 static int
4227 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
4228 {
4229 	struct lpfc_sli *psli = &phba->sli;
4230 	uint32_t hba_aer_enabled;
4231 	int rc;
4232 
4233 	/* Restart HBA */
4234 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4235 			"0296 Restart HBA Data: x%x x%x\n",
4236 			phba->pport->port_state, psli->sli_flag);
4237 
4238 	/* Take PCIe device Advanced Error Reporting (AER) state */
4239 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4240 
4241 	rc = lpfc_sli4_brdreset(phba);
4242 
4243 	spin_lock_irq(&phba->hbalock);
4244 	phba->pport->stopped = 0;
4245 	phba->link_state = LPFC_INIT_START;
4246 	phba->hba_flag = 0;
4247 	spin_unlock_irq(&phba->hbalock);
4248 
4249 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4250 	psli->stats_start = get_seconds();
4251 
4252 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4253 	if (hba_aer_enabled)
4254 		pci_disable_pcie_error_reporting(phba->pcidev);
4255 
4256 	lpfc_hba_down_post(phba);
4257 
4258 	return rc;
4259 }
4260 
4261 /**
4262  * lpfc_sli_brdrestart - Wrapper func for restarting hba
4263  * @phba: Pointer to HBA context object.
4264  *
4265  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
4266  * API jump table function pointer from the lpfc_hba struct.
4267 **/
4268 int
4269 lpfc_sli_brdrestart(struct lpfc_hba *phba)
4270 {
4271 	return phba->lpfc_sli_brdrestart(phba);
4272 }
4273 
4274 /**
4275  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
4276  * @phba: Pointer to HBA context object.
4277  *
4278  * This function is called after a HBA restart to wait for successful
4279  * restart of the HBA. Successful restart of the HBA is indicated by
4280  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
4281  * iteration, the function will restart the HBA again. The function returns
4282  * zero if HBA successfully restarted else returns negative error code.
4283  **/
4284 static int
4285 lpfc_sli_chipset_init(struct lpfc_hba *phba)
4286 {
4287 	uint32_t status, i = 0;
4288 
4289 	/* Read the HBA Host Status Register */
4290 	if (lpfc_readl(phba->HSregaddr, &status))
4291 		return -EIO;
4292 
4293 	/* Check status register to see what current state is */
4294 	i = 0;
4295 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
4296 
4297 		/* Check every 10ms for 10 retries, then every 100ms for 90
4298 		 * retries, then every 1 sec for 50 retires for a total of
4299 		 * ~60 seconds before reset the board again and check every
4300 		 * 1 sec for 50 retries. The up to 60 seconds before the
4301 		 * board ready is required by the Falcon FIPS zeroization
4302 		 * complete, and any reset the board in between shall cause
4303 		 * restart of zeroization, further delay the board ready.
4304 		 */
4305 		if (i++ >= 200) {
4306 			/* Adapter failed to init, timeout, status reg
4307 			   <status> */
4308 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4309 					"0436 Adapter failed to init, "
4310 					"timeout, status reg x%x, "
4311 					"FW Data: A8 x%x AC x%x\n", status,
4312 					readl(phba->MBslimaddr + 0xa8),
4313 					readl(phba->MBslimaddr + 0xac));
4314 			phba->link_state = LPFC_HBA_ERROR;
4315 			return -ETIMEDOUT;
4316 		}
4317 
4318 		/* Check to see if any errors occurred during init */
4319 		if (status & HS_FFERM) {
4320 			/* ERROR: During chipset initialization */
4321 			/* Adapter failed to init, chipset, status reg
4322 			   <status> */
4323 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4324 					"0437 Adapter failed to init, "
4325 					"chipset, status reg x%x, "
4326 					"FW Data: A8 x%x AC x%x\n", status,
4327 					readl(phba->MBslimaddr + 0xa8),
4328 					readl(phba->MBslimaddr + 0xac));
4329 			phba->link_state = LPFC_HBA_ERROR;
4330 			return -EIO;
4331 		}
4332 
4333 		if (i <= 10)
4334 			msleep(10);
4335 		else if (i <= 100)
4336 			msleep(100);
4337 		else
4338 			msleep(1000);
4339 
4340 		if (i == 150) {
4341 			/* Do post */
4342 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4343 			lpfc_sli_brdrestart(phba);
4344 		}
4345 		/* Read the HBA Host Status Register */
4346 		if (lpfc_readl(phba->HSregaddr, &status))
4347 			return -EIO;
4348 	}
4349 
4350 	/* Check to see if any errors occurred during init */
4351 	if (status & HS_FFERM) {
4352 		/* ERROR: During chipset initialization */
4353 		/* Adapter failed to init, chipset, status reg <status> */
4354 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4355 				"0438 Adapter failed to init, chipset, "
4356 				"status reg x%x, "
4357 				"FW Data: A8 x%x AC x%x\n", status,
4358 				readl(phba->MBslimaddr + 0xa8),
4359 				readl(phba->MBslimaddr + 0xac));
4360 		phba->link_state = LPFC_HBA_ERROR;
4361 		return -EIO;
4362 	}
4363 
4364 	/* Clear all interrupt enable conditions */
4365 	writel(0, phba->HCregaddr);
4366 	readl(phba->HCregaddr); /* flush */
4367 
4368 	/* setup host attn register */
4369 	writel(0xffffffff, phba->HAregaddr);
4370 	readl(phba->HAregaddr); /* flush */
4371 	return 0;
4372 }
4373 
4374 /**
4375  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
4376  *
4377  * This function calculates and returns the number of HBQs required to be
4378  * configured.
4379  **/
4380 int
4381 lpfc_sli_hbq_count(void)
4382 {
4383 	return ARRAY_SIZE(lpfc_hbq_defs);
4384 }
4385 
4386 /**
4387  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
4388  *
4389  * This function adds the number of hbq entries in every HBQ to get
4390  * the total number of hbq entries required for the HBA and returns
4391  * the total count.
4392  **/
4393 static int
4394 lpfc_sli_hbq_entry_count(void)
4395 {
4396 	int  hbq_count = lpfc_sli_hbq_count();
4397 	int  count = 0;
4398 	int  i;
4399 
4400 	for (i = 0; i < hbq_count; ++i)
4401 		count += lpfc_hbq_defs[i]->entry_count;
4402 	return count;
4403 }
4404 
4405 /**
4406  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
4407  *
4408  * This function calculates amount of memory required for all hbq entries
4409  * to be configured and returns the total memory required.
4410  **/
4411 int
4412 lpfc_sli_hbq_size(void)
4413 {
4414 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
4415 }
4416 
4417 /**
4418  * lpfc_sli_hbq_setup - configure and initialize HBQs
4419  * @phba: Pointer to HBA context object.
4420  *
4421  * This function is called during the SLI initialization to configure
4422  * all the HBQs and post buffers to the HBQ. The caller is not
4423  * required to hold any locks. This function will return zero if successful
4424  * else it will return negative error code.
4425  **/
4426 static int
4427 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
4428 {
4429 	int  hbq_count = lpfc_sli_hbq_count();
4430 	LPFC_MBOXQ_t *pmb;
4431 	MAILBOX_t *pmbox;
4432 	uint32_t hbqno;
4433 	uint32_t hbq_entry_index;
4434 
4435 				/* Get a Mailbox buffer to setup mailbox
4436 				 * commands for HBA initialization
4437 				 */
4438 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4439 
4440 	if (!pmb)
4441 		return -ENOMEM;
4442 
4443 	pmbox = &pmb->u.mb;
4444 
4445 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
4446 	phba->link_state = LPFC_INIT_MBX_CMDS;
4447 	phba->hbq_in_use = 1;
4448 
4449 	hbq_entry_index = 0;
4450 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
4451 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
4452 		phba->hbqs[hbqno].hbqPutIdx      = 0;
4453 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
4454 		phba->hbqs[hbqno].entry_count =
4455 			lpfc_hbq_defs[hbqno]->entry_count;
4456 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
4457 			hbq_entry_index, pmb);
4458 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
4459 
4460 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
4461 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
4462 			   mbxStatus <status>, ring <num> */
4463 
4464 			lpfc_printf_log(phba, KERN_ERR,
4465 					LOG_SLI | LOG_VPORT,
4466 					"1805 Adapter failed to init. "
4467 					"Data: x%x x%x x%x\n",
4468 					pmbox->mbxCommand,
4469 					pmbox->mbxStatus, hbqno);
4470 
4471 			phba->link_state = LPFC_HBA_ERROR;
4472 			mempool_free(pmb, phba->mbox_mem_pool);
4473 			return -ENXIO;
4474 		}
4475 	}
4476 	phba->hbq_count = hbq_count;
4477 
4478 	mempool_free(pmb, phba->mbox_mem_pool);
4479 
4480 	/* Initially populate or replenish the HBQs */
4481 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
4482 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
4483 	return 0;
4484 }
4485 
4486 /**
4487  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
4488  * @phba: Pointer to HBA context object.
4489  *
4490  * This function is called during the SLI initialization to configure
4491  * all the HBQs and post buffers to the HBQ. The caller is not
4492  * required to hold any locks. This function will return zero if successful
4493  * else it will return negative error code.
4494  **/
4495 static int
4496 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
4497 {
4498 	phba->hbq_in_use = 1;
4499 	phba->hbqs[0].entry_count = lpfc_hbq_defs[0]->entry_count;
4500 	phba->hbq_count = 1;
4501 	/* Initially populate or replenish the HBQs */
4502 	lpfc_sli_hbqbuf_init_hbqs(phba, 0);
4503 	return 0;
4504 }
4505 
4506 /**
4507  * lpfc_sli_config_port - Issue config port mailbox command
4508  * @phba: Pointer to HBA context object.
4509  * @sli_mode: sli mode - 2/3
4510  *
4511  * This function is called by the sli intialization code path
4512  * to issue config_port mailbox command. This function restarts the
4513  * HBA firmware and issues a config_port mailbox command to configure
4514  * the SLI interface in the sli mode specified by sli_mode
4515  * variable. The caller is not required to hold any locks.
4516  * The function returns 0 if successful, else returns negative error
4517  * code.
4518  **/
4519 int
4520 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
4521 {
4522 	LPFC_MBOXQ_t *pmb;
4523 	uint32_t resetcount = 0, rc = 0, done = 0;
4524 
4525 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4526 	if (!pmb) {
4527 		phba->link_state = LPFC_HBA_ERROR;
4528 		return -ENOMEM;
4529 	}
4530 
4531 	phba->sli_rev = sli_mode;
4532 	while (resetcount < 2 && !done) {
4533 		spin_lock_irq(&phba->hbalock);
4534 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
4535 		spin_unlock_irq(&phba->hbalock);
4536 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4537 		lpfc_sli_brdrestart(phba);
4538 		rc = lpfc_sli_chipset_init(phba);
4539 		if (rc)
4540 			break;
4541 
4542 		spin_lock_irq(&phba->hbalock);
4543 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4544 		spin_unlock_irq(&phba->hbalock);
4545 		resetcount++;
4546 
4547 		/* Call pre CONFIG_PORT mailbox command initialization.  A
4548 		 * value of 0 means the call was successful.  Any other
4549 		 * nonzero value is a failure, but if ERESTART is returned,
4550 		 * the driver may reset the HBA and try again.
4551 		 */
4552 		rc = lpfc_config_port_prep(phba);
4553 		if (rc == -ERESTART) {
4554 			phba->link_state = LPFC_LINK_UNKNOWN;
4555 			continue;
4556 		} else if (rc)
4557 			break;
4558 
4559 		phba->link_state = LPFC_INIT_MBX_CMDS;
4560 		lpfc_config_port(phba, pmb);
4561 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
4562 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
4563 					LPFC_SLI3_HBQ_ENABLED |
4564 					LPFC_SLI3_CRP_ENABLED |
4565 					LPFC_SLI3_BG_ENABLED |
4566 					LPFC_SLI3_DSS_ENABLED);
4567 		if (rc != MBX_SUCCESS) {
4568 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4569 				"0442 Adapter failed to init, mbxCmd x%x "
4570 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
4571 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
4572 			spin_lock_irq(&phba->hbalock);
4573 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
4574 			spin_unlock_irq(&phba->hbalock);
4575 			rc = -ENXIO;
4576 		} else {
4577 			/* Allow asynchronous mailbox command to go through */
4578 			spin_lock_irq(&phba->hbalock);
4579 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
4580 			spin_unlock_irq(&phba->hbalock);
4581 			done = 1;
4582 
4583 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
4584 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
4585 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
4586 					"3110 Port did not grant ASABT\n");
4587 		}
4588 	}
4589 	if (!done) {
4590 		rc = -EINVAL;
4591 		goto do_prep_failed;
4592 	}
4593 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
4594 		if (!pmb->u.mb.un.varCfgPort.cMA) {
4595 			rc = -ENXIO;
4596 			goto do_prep_failed;
4597 		}
4598 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
4599 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
4600 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
4601 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
4602 				phba->max_vpi : phba->max_vports;
4603 
4604 		} else
4605 			phba->max_vpi = 0;
4606 		phba->fips_level = 0;
4607 		phba->fips_spec_rev = 0;
4608 		if (pmb->u.mb.un.varCfgPort.gdss) {
4609 			phba->sli3_options |= LPFC_SLI3_DSS_ENABLED;
4610 			phba->fips_level = pmb->u.mb.un.varCfgPort.fips_level;
4611 			phba->fips_spec_rev = pmb->u.mb.un.varCfgPort.fips_rev;
4612 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4613 					"2850 Security Crypto Active. FIPS x%d "
4614 					"(Spec Rev: x%d)",
4615 					phba->fips_level, phba->fips_spec_rev);
4616 		}
4617 		if (pmb->u.mb.un.varCfgPort.sec_err) {
4618 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4619 					"2856 Config Port Security Crypto "
4620 					"Error: x%x ",
4621 					pmb->u.mb.un.varCfgPort.sec_err);
4622 		}
4623 		if (pmb->u.mb.un.varCfgPort.gerbm)
4624 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
4625 		if (pmb->u.mb.un.varCfgPort.gcrp)
4626 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
4627 
4628 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
4629 		phba->port_gp = phba->mbox->us.s3_pgp.port;
4630 
4631 		if (phba->cfg_enable_bg) {
4632 			if (pmb->u.mb.un.varCfgPort.gbg)
4633 				phba->sli3_options |= LPFC_SLI3_BG_ENABLED;
4634 			else
4635 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4636 						"0443 Adapter did not grant "
4637 						"BlockGuard\n");
4638 		}
4639 	} else {
4640 		phba->hbq_get = NULL;
4641 		phba->port_gp = phba->mbox->us.s2.port;
4642 		phba->max_vpi = 0;
4643 	}
4644 do_prep_failed:
4645 	mempool_free(pmb, phba->mbox_mem_pool);
4646 	return rc;
4647 }
4648 
4649 
4650 /**
4651  * lpfc_sli_hba_setup - SLI intialization function
4652  * @phba: Pointer to HBA context object.
4653  *
4654  * This function is the main SLI intialization function. This function
4655  * is called by the HBA intialization code, HBA reset code and HBA
4656  * error attention handler code. Caller is not required to hold any
4657  * locks. This function issues config_port mailbox command to configure
4658  * the SLI, setup iocb rings and HBQ rings. In the end the function
4659  * calls the config_port_post function to issue init_link mailbox
4660  * command and to start the discovery. The function will return zero
4661  * if successful, else it will return negative error code.
4662  **/
4663 int
4664 lpfc_sli_hba_setup(struct lpfc_hba *phba)
4665 {
4666 	uint32_t rc;
4667 	int  mode = 3, i;
4668 	int longs;
4669 
4670 	switch (phba->cfg_sli_mode) {
4671 	case 2:
4672 		if (phba->cfg_enable_npiv) {
4673 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4674 				"1824 NPIV enabled: Override sli_mode "
4675 				"parameter (%d) to auto (0).\n",
4676 				phba->cfg_sli_mode);
4677 			break;
4678 		}
4679 		mode = 2;
4680 		break;
4681 	case 0:
4682 	case 3:
4683 		break;
4684 	default:
4685 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4686 				"1819 Unrecognized sli_mode parameter: %d.\n",
4687 				phba->cfg_sli_mode);
4688 
4689 		break;
4690 	}
4691 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
4692 
4693 	rc = lpfc_sli_config_port(phba, mode);
4694 
4695 	if (rc && phba->cfg_sli_mode == 3)
4696 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4697 				"1820 Unable to select SLI-3.  "
4698 				"Not supported by adapter.\n");
4699 	if (rc && mode != 2)
4700 		rc = lpfc_sli_config_port(phba, 2);
4701 	else if (rc && mode == 2)
4702 		rc = lpfc_sli_config_port(phba, 3);
4703 	if (rc)
4704 		goto lpfc_sli_hba_setup_error;
4705 
4706 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
4707 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
4708 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
4709 		if (!rc) {
4710 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4711 					"2709 This device supports "
4712 					"Advanced Error Reporting (AER)\n");
4713 			spin_lock_irq(&phba->hbalock);
4714 			phba->hba_flag |= HBA_AER_ENABLED;
4715 			spin_unlock_irq(&phba->hbalock);
4716 		} else {
4717 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4718 					"2708 This device does not support "
4719 					"Advanced Error Reporting (AER): %d\n",
4720 					rc);
4721 			phba->cfg_aer_support = 0;
4722 		}
4723 	}
4724 
4725 	if (phba->sli_rev == 3) {
4726 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
4727 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
4728 	} else {
4729 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
4730 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
4731 		phba->sli3_options = 0;
4732 	}
4733 
4734 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4735 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
4736 			phba->sli_rev, phba->max_vpi);
4737 	rc = lpfc_sli_ring_map(phba);
4738 
4739 	if (rc)
4740 		goto lpfc_sli_hba_setup_error;
4741 
4742 	/* Initialize VPIs. */
4743 	if (phba->sli_rev == LPFC_SLI_REV3) {
4744 		/*
4745 		 * The VPI bitmask and physical ID array are allocated
4746 		 * and initialized once only - at driver load.  A port
4747 		 * reset doesn't need to reinitialize this memory.
4748 		 */
4749 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
4750 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
4751 			phba->vpi_bmask = kzalloc(longs * sizeof(unsigned long),
4752 						  GFP_KERNEL);
4753 			if (!phba->vpi_bmask) {
4754 				rc = -ENOMEM;
4755 				goto lpfc_sli_hba_setup_error;
4756 			}
4757 
4758 			phba->vpi_ids = kzalloc(
4759 					(phba->max_vpi+1) * sizeof(uint16_t),
4760 					GFP_KERNEL);
4761 			if (!phba->vpi_ids) {
4762 				kfree(phba->vpi_bmask);
4763 				rc = -ENOMEM;
4764 				goto lpfc_sli_hba_setup_error;
4765 			}
4766 			for (i = 0; i < phba->max_vpi; i++)
4767 				phba->vpi_ids[i] = i;
4768 		}
4769 	}
4770 
4771 	/* Init HBQs */
4772 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
4773 		rc = lpfc_sli_hbq_setup(phba);
4774 		if (rc)
4775 			goto lpfc_sli_hba_setup_error;
4776 	}
4777 	spin_lock_irq(&phba->hbalock);
4778 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
4779 	spin_unlock_irq(&phba->hbalock);
4780 
4781 	rc = lpfc_config_port_post(phba);
4782 	if (rc)
4783 		goto lpfc_sli_hba_setup_error;
4784 
4785 	return rc;
4786 
4787 lpfc_sli_hba_setup_error:
4788 	phba->link_state = LPFC_HBA_ERROR;
4789 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4790 			"0445 Firmware initialization failed\n");
4791 	return rc;
4792 }
4793 
4794 /**
4795  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
4796  * @phba: Pointer to HBA context object.
4797  * @mboxq: mailbox pointer.
4798  * This function issue a dump mailbox command to read config region
4799  * 23 and parse the records in the region and populate driver
4800  * data structure.
4801  **/
4802 static int
4803 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
4804 {
4805 	LPFC_MBOXQ_t *mboxq;
4806 	struct lpfc_dmabuf *mp;
4807 	struct lpfc_mqe *mqe;
4808 	uint32_t data_length;
4809 	int rc;
4810 
4811 	/* Program the default value of vlan_id and fc_map */
4812 	phba->valid_vlan = 0;
4813 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
4814 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
4815 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
4816 
4817 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4818 	if (!mboxq)
4819 		return -ENOMEM;
4820 
4821 	mqe = &mboxq->u.mqe;
4822 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
4823 		rc = -ENOMEM;
4824 		goto out_free_mboxq;
4825 	}
4826 
4827 	mp = (struct lpfc_dmabuf *) mboxq->context1;
4828 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4829 
4830 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
4831 			"(%d):2571 Mailbox cmd x%x Status x%x "
4832 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
4833 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
4834 			"CQ: x%x x%x x%x x%x\n",
4835 			mboxq->vport ? mboxq->vport->vpi : 0,
4836 			bf_get(lpfc_mqe_command, mqe),
4837 			bf_get(lpfc_mqe_status, mqe),
4838 			mqe->un.mb_words[0], mqe->un.mb_words[1],
4839 			mqe->un.mb_words[2], mqe->un.mb_words[3],
4840 			mqe->un.mb_words[4], mqe->un.mb_words[5],
4841 			mqe->un.mb_words[6], mqe->un.mb_words[7],
4842 			mqe->un.mb_words[8], mqe->un.mb_words[9],
4843 			mqe->un.mb_words[10], mqe->un.mb_words[11],
4844 			mqe->un.mb_words[12], mqe->un.mb_words[13],
4845 			mqe->un.mb_words[14], mqe->un.mb_words[15],
4846 			mqe->un.mb_words[16], mqe->un.mb_words[50],
4847 			mboxq->mcqe.word0,
4848 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
4849 			mboxq->mcqe.trailer);
4850 
4851 	if (rc) {
4852 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
4853 		kfree(mp);
4854 		rc = -EIO;
4855 		goto out_free_mboxq;
4856 	}
4857 	data_length = mqe->un.mb_words[5];
4858 	if (data_length > DMP_RGN23_SIZE) {
4859 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
4860 		kfree(mp);
4861 		rc = -EIO;
4862 		goto out_free_mboxq;
4863 	}
4864 
4865 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
4866 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
4867 	kfree(mp);
4868 	rc = 0;
4869 
4870 out_free_mboxq:
4871 	mempool_free(mboxq, phba->mbox_mem_pool);
4872 	return rc;
4873 }
4874 
4875 /**
4876  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
4877  * @phba: pointer to lpfc hba data structure.
4878  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
4879  * @vpd: pointer to the memory to hold resulting port vpd data.
4880  * @vpd_size: On input, the number of bytes allocated to @vpd.
4881  *	      On output, the number of data bytes in @vpd.
4882  *
4883  * This routine executes a READ_REV SLI4 mailbox command.  In
4884  * addition, this routine gets the port vpd data.
4885  *
4886  * Return codes
4887  * 	0 - successful
4888  * 	-ENOMEM - could not allocated memory.
4889  **/
4890 static int
4891 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
4892 		    uint8_t *vpd, uint32_t *vpd_size)
4893 {
4894 	int rc = 0;
4895 	uint32_t dma_size;
4896 	struct lpfc_dmabuf *dmabuf;
4897 	struct lpfc_mqe *mqe;
4898 
4899 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
4900 	if (!dmabuf)
4901 		return -ENOMEM;
4902 
4903 	/*
4904 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
4905 	 * mailbox command.
4906 	 */
4907 	dma_size = *vpd_size;
4908 	dmabuf->virt = dma_zalloc_coherent(&phba->pcidev->dev, dma_size,
4909 					   &dmabuf->phys, GFP_KERNEL);
4910 	if (!dmabuf->virt) {
4911 		kfree(dmabuf);
4912 		return -ENOMEM;
4913 	}
4914 
4915 	/*
4916 	 * The SLI4 implementation of READ_REV conflicts at word1,
4917 	 * bits 31:16 and SLI4 adds vpd functionality not present
4918 	 * in SLI3.  This code corrects the conflicts.
4919 	 */
4920 	lpfc_read_rev(phba, mboxq);
4921 	mqe = &mboxq->u.mqe;
4922 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
4923 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
4924 	mqe->un.read_rev.word1 &= 0x0000FFFF;
4925 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
4926 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
4927 
4928 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4929 	if (rc) {
4930 		dma_free_coherent(&phba->pcidev->dev, dma_size,
4931 				  dmabuf->virt, dmabuf->phys);
4932 		kfree(dmabuf);
4933 		return -EIO;
4934 	}
4935 
4936 	/*
4937 	 * The available vpd length cannot be bigger than the
4938 	 * DMA buffer passed to the port.  Catch the less than
4939 	 * case and update the caller's size.
4940 	 */
4941 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
4942 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
4943 
4944 	memcpy(vpd, dmabuf->virt, *vpd_size);
4945 
4946 	dma_free_coherent(&phba->pcidev->dev, dma_size,
4947 			  dmabuf->virt, dmabuf->phys);
4948 	kfree(dmabuf);
4949 	return 0;
4950 }
4951 
4952 /**
4953  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
4954  * @phba: pointer to lpfc hba data structure.
4955  *
4956  * This routine retrieves SLI4 device physical port name this PCI function
4957  * is attached to.
4958  *
4959  * Return codes
4960  *      0 - successful
4961  *      otherwise - failed to retrieve physical port name
4962  **/
4963 static int
4964 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
4965 {
4966 	LPFC_MBOXQ_t *mboxq;
4967 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
4968 	struct lpfc_controller_attribute *cntl_attr;
4969 	struct lpfc_mbx_get_port_name *get_port_name;
4970 	void *virtaddr = NULL;
4971 	uint32_t alloclen, reqlen;
4972 	uint32_t shdr_status, shdr_add_status;
4973 	union lpfc_sli4_cfg_shdr *shdr;
4974 	char cport_name = 0;
4975 	int rc;
4976 
4977 	/* We assume nothing at this point */
4978 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
4979 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
4980 
4981 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4982 	if (!mboxq)
4983 		return -ENOMEM;
4984 	/* obtain link type and link number via READ_CONFIG */
4985 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
4986 	lpfc_sli4_read_config(phba);
4987 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
4988 		goto retrieve_ppname;
4989 
4990 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
4991 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
4992 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
4993 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
4994 			LPFC_SLI4_MBX_NEMBED);
4995 	if (alloclen < reqlen) {
4996 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4997 				"3084 Allocated DMA memory size (%d) is "
4998 				"less than the requested DMA memory size "
4999 				"(%d)\n", alloclen, reqlen);
5000 		rc = -ENOMEM;
5001 		goto out_free_mboxq;
5002 	}
5003 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5004 	virtaddr = mboxq->sge_array->addr[0];
5005 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5006 	shdr = &mbx_cntl_attr->cfg_shdr;
5007 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5008 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5009 	if (shdr_status || shdr_add_status || rc) {
5010 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5011 				"3085 Mailbox x%x (x%x/x%x) failed, "
5012 				"rc:x%x, status:x%x, add_status:x%x\n",
5013 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5014 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5015 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5016 				rc, shdr_status, shdr_add_status);
5017 		rc = -ENXIO;
5018 		goto out_free_mboxq;
5019 	}
5020 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5021 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5022 	phba->sli4_hba.lnk_info.lnk_tp =
5023 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5024 	phba->sli4_hba.lnk_info.lnk_no =
5025 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5026 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5027 			"3086 lnk_type:%d, lnk_numb:%d\n",
5028 			phba->sli4_hba.lnk_info.lnk_tp,
5029 			phba->sli4_hba.lnk_info.lnk_no);
5030 
5031 retrieve_ppname:
5032 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5033 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
5034 		sizeof(struct lpfc_mbx_get_port_name) -
5035 		sizeof(struct lpfc_sli4_cfg_mhdr),
5036 		LPFC_SLI4_MBX_EMBED);
5037 	get_port_name = &mboxq->u.mqe.un.get_port_name;
5038 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5039 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
5040 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
5041 		phba->sli4_hba.lnk_info.lnk_tp);
5042 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5043 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5044 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5045 	if (shdr_status || shdr_add_status || rc) {
5046 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5047 				"3087 Mailbox x%x (x%x/x%x) failed: "
5048 				"rc:x%x, status:x%x, add_status:x%x\n",
5049 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5050 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5051 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5052 				rc, shdr_status, shdr_add_status);
5053 		rc = -ENXIO;
5054 		goto out_free_mboxq;
5055 	}
5056 	switch (phba->sli4_hba.lnk_info.lnk_no) {
5057 	case LPFC_LINK_NUMBER_0:
5058 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
5059 				&get_port_name->u.response);
5060 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5061 		break;
5062 	case LPFC_LINK_NUMBER_1:
5063 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
5064 				&get_port_name->u.response);
5065 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5066 		break;
5067 	case LPFC_LINK_NUMBER_2:
5068 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
5069 				&get_port_name->u.response);
5070 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5071 		break;
5072 	case LPFC_LINK_NUMBER_3:
5073 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
5074 				&get_port_name->u.response);
5075 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5076 		break;
5077 	default:
5078 		break;
5079 	}
5080 
5081 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
5082 		phba->Port[0] = cport_name;
5083 		phba->Port[1] = '\0';
5084 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5085 				"3091 SLI get port name: %s\n", phba->Port);
5086 	}
5087 
5088 out_free_mboxq:
5089 	if (rc != MBX_TIMEOUT) {
5090 		if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5091 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
5092 		else
5093 			mempool_free(mboxq, phba->mbox_mem_pool);
5094 	}
5095 	return rc;
5096 }
5097 
5098 /**
5099  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
5100  * @phba: pointer to lpfc hba data structure.
5101  *
5102  * This routine is called to explicitly arm the SLI4 device's completion and
5103  * event queues
5104  **/
5105 static void
5106 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
5107 {
5108 	int fcp_eqidx;
5109 
5110 	lpfc_sli4_cq_release(phba->sli4_hba.mbx_cq, LPFC_QUEUE_REARM);
5111 	lpfc_sli4_cq_release(phba->sli4_hba.els_cq, LPFC_QUEUE_REARM);
5112 	fcp_eqidx = 0;
5113 	if (phba->sli4_hba.fcp_cq) {
5114 		do {
5115 			lpfc_sli4_cq_release(phba->sli4_hba.fcp_cq[fcp_eqidx],
5116 					     LPFC_QUEUE_REARM);
5117 		} while (++fcp_eqidx < phba->cfg_fcp_io_channel);
5118 	}
5119 
5120 	if (phba->cfg_fof)
5121 		lpfc_sli4_cq_release(phba->sli4_hba.oas_cq, LPFC_QUEUE_REARM);
5122 
5123 	if (phba->sli4_hba.hba_eq) {
5124 		for (fcp_eqidx = 0; fcp_eqidx < phba->cfg_fcp_io_channel;
5125 		     fcp_eqidx++)
5126 			lpfc_sli4_eq_release(phba->sli4_hba.hba_eq[fcp_eqidx],
5127 					     LPFC_QUEUE_REARM);
5128 	}
5129 
5130 	if (phba->cfg_fof)
5131 		lpfc_sli4_eq_release(phba->sli4_hba.fof_eq, LPFC_QUEUE_REARM);
5132 }
5133 
5134 /**
5135  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
5136  * @phba: Pointer to HBA context object.
5137  * @type: The resource extent type.
5138  * @extnt_count: buffer to hold port available extent count.
5139  * @extnt_size: buffer to hold element count per extent.
5140  *
5141  * This function calls the port and retrievs the number of available
5142  * extents and their size for a particular extent type.
5143  *
5144  * Returns: 0 if successful.  Nonzero otherwise.
5145  **/
5146 int
5147 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
5148 			       uint16_t *extnt_count, uint16_t *extnt_size)
5149 {
5150 	int rc = 0;
5151 	uint32_t length;
5152 	uint32_t mbox_tmo;
5153 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
5154 	LPFC_MBOXQ_t *mbox;
5155 
5156 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5157 	if (!mbox)
5158 		return -ENOMEM;
5159 
5160 	/* Find out how many extents are available for this resource type */
5161 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
5162 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5163 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5164 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
5165 			 length, LPFC_SLI4_MBX_EMBED);
5166 
5167 	/* Send an extents count of 0 - the GET doesn't use it. */
5168 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5169 					LPFC_SLI4_MBX_EMBED);
5170 	if (unlikely(rc)) {
5171 		rc = -EIO;
5172 		goto err_exit;
5173 	}
5174 
5175 	if (!phba->sli4_hba.intr_enable)
5176 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5177 	else {
5178 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5179 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5180 	}
5181 	if (unlikely(rc)) {
5182 		rc = -EIO;
5183 		goto err_exit;
5184 	}
5185 
5186 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
5187 	if (bf_get(lpfc_mbox_hdr_status,
5188 		   &rsrc_info->header.cfg_shdr.response)) {
5189 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5190 				"2930 Failed to get resource extents "
5191 				"Status 0x%x Add'l Status 0x%x\n",
5192 				bf_get(lpfc_mbox_hdr_status,
5193 				       &rsrc_info->header.cfg_shdr.response),
5194 				bf_get(lpfc_mbox_hdr_add_status,
5195 				       &rsrc_info->header.cfg_shdr.response));
5196 		rc = -EIO;
5197 		goto err_exit;
5198 	}
5199 
5200 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
5201 			      &rsrc_info->u.rsp);
5202 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
5203 			     &rsrc_info->u.rsp);
5204 
5205 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5206 			"3162 Retrieved extents type-%d from port: count:%d, "
5207 			"size:%d\n", type, *extnt_count, *extnt_size);
5208 
5209 err_exit:
5210 	mempool_free(mbox, phba->mbox_mem_pool);
5211 	return rc;
5212 }
5213 
5214 /**
5215  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
5216  * @phba: Pointer to HBA context object.
5217  * @type: The extent type to check.
5218  *
5219  * This function reads the current available extents from the port and checks
5220  * if the extent count or extent size has changed since the last access.
5221  * Callers use this routine post port reset to understand if there is a
5222  * extent reprovisioning requirement.
5223  *
5224  * Returns:
5225  *   -Error: error indicates problem.
5226  *   1: Extent count or size has changed.
5227  *   0: No changes.
5228  **/
5229 static int
5230 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
5231 {
5232 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
5233 	uint16_t size_diff, rsrc_ext_size;
5234 	int rc = 0;
5235 	struct lpfc_rsrc_blks *rsrc_entry;
5236 	struct list_head *rsrc_blk_list = NULL;
5237 
5238 	size_diff = 0;
5239 	curr_ext_cnt = 0;
5240 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5241 					    &rsrc_ext_cnt,
5242 					    &rsrc_ext_size);
5243 	if (unlikely(rc))
5244 		return -EIO;
5245 
5246 	switch (type) {
5247 	case LPFC_RSC_TYPE_FCOE_RPI:
5248 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5249 		break;
5250 	case LPFC_RSC_TYPE_FCOE_VPI:
5251 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
5252 		break;
5253 	case LPFC_RSC_TYPE_FCOE_XRI:
5254 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5255 		break;
5256 	case LPFC_RSC_TYPE_FCOE_VFI:
5257 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5258 		break;
5259 	default:
5260 		break;
5261 	}
5262 
5263 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
5264 		curr_ext_cnt++;
5265 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
5266 			size_diff++;
5267 	}
5268 
5269 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
5270 		rc = 1;
5271 
5272 	return rc;
5273 }
5274 
5275 /**
5276  * lpfc_sli4_cfg_post_extnts -
5277  * @phba: Pointer to HBA context object.
5278  * @extnt_cnt - number of available extents.
5279  * @type - the extent type (rpi, xri, vfi, vpi).
5280  * @emb - buffer to hold either MBX_EMBED or MBX_NEMBED operation.
5281  * @mbox - pointer to the caller's allocated mailbox structure.
5282  *
5283  * This function executes the extents allocation request.  It also
5284  * takes care of the amount of memory needed to allocate or get the
5285  * allocated extents. It is the caller's responsibility to evaluate
5286  * the response.
5287  *
5288  * Returns:
5289  *   -Error:  Error value describes the condition found.
5290  *   0: if successful
5291  **/
5292 static int
5293 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
5294 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
5295 {
5296 	int rc = 0;
5297 	uint32_t req_len;
5298 	uint32_t emb_len;
5299 	uint32_t alloc_len, mbox_tmo;
5300 
5301 	/* Calculate the total requested length of the dma memory */
5302 	req_len = extnt_cnt * sizeof(uint16_t);
5303 
5304 	/*
5305 	 * Calculate the size of an embedded mailbox.  The uint32_t
5306 	 * accounts for extents-specific word.
5307 	 */
5308 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
5309 		sizeof(uint32_t);
5310 
5311 	/*
5312 	 * Presume the allocation and response will fit into an embedded
5313 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
5314 	 */
5315 	*emb = LPFC_SLI4_MBX_EMBED;
5316 	if (req_len > emb_len) {
5317 		req_len = extnt_cnt * sizeof(uint16_t) +
5318 			sizeof(union lpfc_sli4_cfg_shdr) +
5319 			sizeof(uint32_t);
5320 		*emb = LPFC_SLI4_MBX_NEMBED;
5321 	}
5322 
5323 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5324 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
5325 				     req_len, *emb);
5326 	if (alloc_len < req_len) {
5327 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5328 			"2982 Allocated DMA memory size (x%x) is "
5329 			"less than the requested DMA memory "
5330 			"size (x%x)\n", alloc_len, req_len);
5331 		return -ENOMEM;
5332 	}
5333 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
5334 	if (unlikely(rc))
5335 		return -EIO;
5336 
5337 	if (!phba->sli4_hba.intr_enable)
5338 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5339 	else {
5340 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5341 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5342 	}
5343 
5344 	if (unlikely(rc))
5345 		rc = -EIO;
5346 	return rc;
5347 }
5348 
5349 /**
5350  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
5351  * @phba: Pointer to HBA context object.
5352  * @type:  The resource extent type to allocate.
5353  *
5354  * This function allocates the number of elements for the specified
5355  * resource type.
5356  **/
5357 static int
5358 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
5359 {
5360 	bool emb = false;
5361 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
5362 	uint16_t rsrc_id, rsrc_start, j, k;
5363 	uint16_t *ids;
5364 	int i, rc;
5365 	unsigned long longs;
5366 	unsigned long *bmask;
5367 	struct lpfc_rsrc_blks *rsrc_blks;
5368 	LPFC_MBOXQ_t *mbox;
5369 	uint32_t length;
5370 	struct lpfc_id_range *id_array = NULL;
5371 	void *virtaddr = NULL;
5372 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
5373 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
5374 	struct list_head *ext_blk_list;
5375 
5376 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5377 					    &rsrc_cnt,
5378 					    &rsrc_size);
5379 	if (unlikely(rc))
5380 		return -EIO;
5381 
5382 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
5383 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5384 			"3009 No available Resource Extents "
5385 			"for resource type 0x%x: Count: 0x%x, "
5386 			"Size 0x%x\n", type, rsrc_cnt,
5387 			rsrc_size);
5388 		return -ENOMEM;
5389 	}
5390 
5391 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
5392 			"2903 Post resource extents type-0x%x: "
5393 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
5394 
5395 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5396 	if (!mbox)
5397 		return -ENOMEM;
5398 
5399 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
5400 	if (unlikely(rc)) {
5401 		rc = -EIO;
5402 		goto err_exit;
5403 	}
5404 
5405 	/*
5406 	 * Figure out where the response is located.  Then get local pointers
5407 	 * to the response data.  The port does not guarantee to respond to
5408 	 * all extents counts request so update the local variable with the
5409 	 * allocated count from the port.
5410 	 */
5411 	if (emb == LPFC_SLI4_MBX_EMBED) {
5412 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
5413 		id_array = &rsrc_ext->u.rsp.id[0];
5414 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
5415 	} else {
5416 		virtaddr = mbox->sge_array->addr[0];
5417 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
5418 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
5419 		id_array = &n_rsrc->id;
5420 	}
5421 
5422 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
5423 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
5424 
5425 	/*
5426 	 * Based on the resource size and count, correct the base and max
5427 	 * resource values.
5428 	 */
5429 	length = sizeof(struct lpfc_rsrc_blks);
5430 	switch (type) {
5431 	case LPFC_RSC_TYPE_FCOE_RPI:
5432 		phba->sli4_hba.rpi_bmask = kzalloc(longs *
5433 						   sizeof(unsigned long),
5434 						   GFP_KERNEL);
5435 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
5436 			rc = -ENOMEM;
5437 			goto err_exit;
5438 		}
5439 		phba->sli4_hba.rpi_ids = kzalloc(rsrc_id_cnt *
5440 						 sizeof(uint16_t),
5441 						 GFP_KERNEL);
5442 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
5443 			kfree(phba->sli4_hba.rpi_bmask);
5444 			rc = -ENOMEM;
5445 			goto err_exit;
5446 		}
5447 
5448 		/*
5449 		 * The next_rpi was initialized with the maximum available
5450 		 * count but the port may allocate a smaller number.  Catch
5451 		 * that case and update the next_rpi.
5452 		 */
5453 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
5454 
5455 		/* Initialize local ptrs for common extent processing later. */
5456 		bmask = phba->sli4_hba.rpi_bmask;
5457 		ids = phba->sli4_hba.rpi_ids;
5458 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5459 		break;
5460 	case LPFC_RSC_TYPE_FCOE_VPI:
5461 		phba->vpi_bmask = kzalloc(longs *
5462 					  sizeof(unsigned long),
5463 					  GFP_KERNEL);
5464 		if (unlikely(!phba->vpi_bmask)) {
5465 			rc = -ENOMEM;
5466 			goto err_exit;
5467 		}
5468 		phba->vpi_ids = kzalloc(rsrc_id_cnt *
5469 					 sizeof(uint16_t),
5470 					 GFP_KERNEL);
5471 		if (unlikely(!phba->vpi_ids)) {
5472 			kfree(phba->vpi_bmask);
5473 			rc = -ENOMEM;
5474 			goto err_exit;
5475 		}
5476 
5477 		/* Initialize local ptrs for common extent processing later. */
5478 		bmask = phba->vpi_bmask;
5479 		ids = phba->vpi_ids;
5480 		ext_blk_list = &phba->lpfc_vpi_blk_list;
5481 		break;
5482 	case LPFC_RSC_TYPE_FCOE_XRI:
5483 		phba->sli4_hba.xri_bmask = kzalloc(longs *
5484 						   sizeof(unsigned long),
5485 						   GFP_KERNEL);
5486 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
5487 			rc = -ENOMEM;
5488 			goto err_exit;
5489 		}
5490 		phba->sli4_hba.max_cfg_param.xri_used = 0;
5491 		phba->sli4_hba.xri_ids = kzalloc(rsrc_id_cnt *
5492 						 sizeof(uint16_t),
5493 						 GFP_KERNEL);
5494 		if (unlikely(!phba->sli4_hba.xri_ids)) {
5495 			kfree(phba->sli4_hba.xri_bmask);
5496 			rc = -ENOMEM;
5497 			goto err_exit;
5498 		}
5499 
5500 		/* Initialize local ptrs for common extent processing later. */
5501 		bmask = phba->sli4_hba.xri_bmask;
5502 		ids = phba->sli4_hba.xri_ids;
5503 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5504 		break;
5505 	case LPFC_RSC_TYPE_FCOE_VFI:
5506 		phba->sli4_hba.vfi_bmask = kzalloc(longs *
5507 						   sizeof(unsigned long),
5508 						   GFP_KERNEL);
5509 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
5510 			rc = -ENOMEM;
5511 			goto err_exit;
5512 		}
5513 		phba->sli4_hba.vfi_ids = kzalloc(rsrc_id_cnt *
5514 						 sizeof(uint16_t),
5515 						 GFP_KERNEL);
5516 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
5517 			kfree(phba->sli4_hba.vfi_bmask);
5518 			rc = -ENOMEM;
5519 			goto err_exit;
5520 		}
5521 
5522 		/* Initialize local ptrs for common extent processing later. */
5523 		bmask = phba->sli4_hba.vfi_bmask;
5524 		ids = phba->sli4_hba.vfi_ids;
5525 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5526 		break;
5527 	default:
5528 		/* Unsupported Opcode.  Fail call. */
5529 		id_array = NULL;
5530 		bmask = NULL;
5531 		ids = NULL;
5532 		ext_blk_list = NULL;
5533 		goto err_exit;
5534 	}
5535 
5536 	/*
5537 	 * Complete initializing the extent configuration with the
5538 	 * allocated ids assigned to this function.  The bitmask serves
5539 	 * as an index into the array and manages the available ids.  The
5540 	 * array just stores the ids communicated to the port via the wqes.
5541 	 */
5542 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
5543 		if ((i % 2) == 0)
5544 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
5545 					 &id_array[k]);
5546 		else
5547 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
5548 					 &id_array[k]);
5549 
5550 		rsrc_blks = kzalloc(length, GFP_KERNEL);
5551 		if (unlikely(!rsrc_blks)) {
5552 			rc = -ENOMEM;
5553 			kfree(bmask);
5554 			kfree(ids);
5555 			goto err_exit;
5556 		}
5557 		rsrc_blks->rsrc_start = rsrc_id;
5558 		rsrc_blks->rsrc_size = rsrc_size;
5559 		list_add_tail(&rsrc_blks->list, ext_blk_list);
5560 		rsrc_start = rsrc_id;
5561 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0))
5562 			phba->sli4_hba.scsi_xri_start = rsrc_start +
5563 				lpfc_sli4_get_els_iocb_cnt(phba);
5564 
5565 		while (rsrc_id < (rsrc_start + rsrc_size)) {
5566 			ids[j] = rsrc_id;
5567 			rsrc_id++;
5568 			j++;
5569 		}
5570 		/* Entire word processed.  Get next word.*/
5571 		if ((i % 2) == 1)
5572 			k++;
5573 	}
5574  err_exit:
5575 	lpfc_sli4_mbox_cmd_free(phba, mbox);
5576 	return rc;
5577 }
5578 
5579 /**
5580  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
5581  * @phba: Pointer to HBA context object.
5582  * @type: the extent's type.
5583  *
5584  * This function deallocates all extents of a particular resource type.
5585  * SLI4 does not allow for deallocating a particular extent range.  It
5586  * is the caller's responsibility to release all kernel memory resources.
5587  **/
5588 static int
5589 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
5590 {
5591 	int rc;
5592 	uint32_t length, mbox_tmo = 0;
5593 	LPFC_MBOXQ_t *mbox;
5594 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
5595 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
5596 
5597 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5598 	if (!mbox)
5599 		return -ENOMEM;
5600 
5601 	/*
5602 	 * This function sends an embedded mailbox because it only sends the
5603 	 * the resource type.  All extents of this type are released by the
5604 	 * port.
5605 	 */
5606 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
5607 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5608 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5609 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
5610 			 length, LPFC_SLI4_MBX_EMBED);
5611 
5612 	/* Send an extents count of 0 - the dealloc doesn't use it. */
5613 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5614 					LPFC_SLI4_MBX_EMBED);
5615 	if (unlikely(rc)) {
5616 		rc = -EIO;
5617 		goto out_free_mbox;
5618 	}
5619 	if (!phba->sli4_hba.intr_enable)
5620 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5621 	else {
5622 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5623 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5624 	}
5625 	if (unlikely(rc)) {
5626 		rc = -EIO;
5627 		goto out_free_mbox;
5628 	}
5629 
5630 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
5631 	if (bf_get(lpfc_mbox_hdr_status,
5632 		   &dealloc_rsrc->header.cfg_shdr.response)) {
5633 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5634 				"2919 Failed to release resource extents "
5635 				"for type %d - Status 0x%x Add'l Status 0x%x. "
5636 				"Resource memory not released.\n",
5637 				type,
5638 				bf_get(lpfc_mbox_hdr_status,
5639 				    &dealloc_rsrc->header.cfg_shdr.response),
5640 				bf_get(lpfc_mbox_hdr_add_status,
5641 				    &dealloc_rsrc->header.cfg_shdr.response));
5642 		rc = -EIO;
5643 		goto out_free_mbox;
5644 	}
5645 
5646 	/* Release kernel memory resources for the specific type. */
5647 	switch (type) {
5648 	case LPFC_RSC_TYPE_FCOE_VPI:
5649 		kfree(phba->vpi_bmask);
5650 		kfree(phba->vpi_ids);
5651 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5652 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5653 				    &phba->lpfc_vpi_blk_list, list) {
5654 			list_del_init(&rsrc_blk->list);
5655 			kfree(rsrc_blk);
5656 		}
5657 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
5658 		break;
5659 	case LPFC_RSC_TYPE_FCOE_XRI:
5660 		kfree(phba->sli4_hba.xri_bmask);
5661 		kfree(phba->sli4_hba.xri_ids);
5662 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5663 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
5664 			list_del_init(&rsrc_blk->list);
5665 			kfree(rsrc_blk);
5666 		}
5667 		break;
5668 	case LPFC_RSC_TYPE_FCOE_VFI:
5669 		kfree(phba->sli4_hba.vfi_bmask);
5670 		kfree(phba->sli4_hba.vfi_ids);
5671 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5672 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5673 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
5674 			list_del_init(&rsrc_blk->list);
5675 			kfree(rsrc_blk);
5676 		}
5677 		break;
5678 	case LPFC_RSC_TYPE_FCOE_RPI:
5679 		/* RPI bitmask and physical id array are cleaned up earlier. */
5680 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
5681 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
5682 			list_del_init(&rsrc_blk->list);
5683 			kfree(rsrc_blk);
5684 		}
5685 		break;
5686 	default:
5687 		break;
5688 	}
5689 
5690 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5691 
5692  out_free_mbox:
5693 	mempool_free(mbox, phba->mbox_mem_pool);
5694 	return rc;
5695 }
5696 
5697 static void
5698 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
5699 		  uint32_t feature)
5700 {
5701 	uint32_t len;
5702 
5703 	len = sizeof(struct lpfc_mbx_set_feature) -
5704 		sizeof(struct lpfc_sli4_cfg_mhdr);
5705 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5706 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
5707 			 LPFC_SLI4_MBX_EMBED);
5708 
5709 	switch (feature) {
5710 	case LPFC_SET_UE_RECOVERY:
5711 		bf_set(lpfc_mbx_set_feature_UER,
5712 		       &mbox->u.mqe.un.set_feature, 1);
5713 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
5714 		mbox->u.mqe.un.set_feature.param_len = 8;
5715 		break;
5716 	case LPFC_SET_MDS_DIAGS:
5717 		bf_set(lpfc_mbx_set_feature_mds,
5718 		       &mbox->u.mqe.un.set_feature, 1);
5719 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
5720 		       &mbox->u.mqe.un.set_feature, 0);
5721 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
5722 		mbox->u.mqe.un.set_feature.param_len = 8;
5723 		break;
5724 	}
5725 
5726 	return;
5727 }
5728 
5729 /**
5730  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
5731  * @phba: Pointer to HBA context object.
5732  *
5733  * This function allocates all SLI4 resource identifiers.
5734  **/
5735 int
5736 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
5737 {
5738 	int i, rc, error = 0;
5739 	uint16_t count, base;
5740 	unsigned long longs;
5741 
5742 	if (!phba->sli4_hba.rpi_hdrs_in_use)
5743 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
5744 	if (phba->sli4_hba.extents_in_use) {
5745 		/*
5746 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
5747 		 * resource extent count must be read and allocated before
5748 		 * provisioning the resource id arrays.
5749 		 */
5750 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
5751 		    LPFC_IDX_RSRC_RDY) {
5752 			/*
5753 			 * Extent-based resources are set - the driver could
5754 			 * be in a port reset. Figure out if any corrective
5755 			 * actions need to be taken.
5756 			 */
5757 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5758 						 LPFC_RSC_TYPE_FCOE_VFI);
5759 			if (rc != 0)
5760 				error++;
5761 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5762 						 LPFC_RSC_TYPE_FCOE_VPI);
5763 			if (rc != 0)
5764 				error++;
5765 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5766 						 LPFC_RSC_TYPE_FCOE_XRI);
5767 			if (rc != 0)
5768 				error++;
5769 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
5770 						 LPFC_RSC_TYPE_FCOE_RPI);
5771 			if (rc != 0)
5772 				error++;
5773 
5774 			/*
5775 			 * It's possible that the number of resources
5776 			 * provided to this port instance changed between
5777 			 * resets.  Detect this condition and reallocate
5778 			 * resources.  Otherwise, there is no action.
5779 			 */
5780 			if (error) {
5781 				lpfc_printf_log(phba, KERN_INFO,
5782 						LOG_MBOX | LOG_INIT,
5783 						"2931 Detected extent resource "
5784 						"change.  Reallocating all "
5785 						"extents.\n");
5786 				rc = lpfc_sli4_dealloc_extent(phba,
5787 						 LPFC_RSC_TYPE_FCOE_VFI);
5788 				rc = lpfc_sli4_dealloc_extent(phba,
5789 						 LPFC_RSC_TYPE_FCOE_VPI);
5790 				rc = lpfc_sli4_dealloc_extent(phba,
5791 						 LPFC_RSC_TYPE_FCOE_XRI);
5792 				rc = lpfc_sli4_dealloc_extent(phba,
5793 						 LPFC_RSC_TYPE_FCOE_RPI);
5794 			} else
5795 				return 0;
5796 		}
5797 
5798 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
5799 		if (unlikely(rc))
5800 			goto err_exit;
5801 
5802 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
5803 		if (unlikely(rc))
5804 			goto err_exit;
5805 
5806 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
5807 		if (unlikely(rc))
5808 			goto err_exit;
5809 
5810 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
5811 		if (unlikely(rc))
5812 			goto err_exit;
5813 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
5814 		       LPFC_IDX_RSRC_RDY);
5815 		return rc;
5816 	} else {
5817 		/*
5818 		 * The port does not support resource extents.  The XRI, VPI,
5819 		 * VFI, RPI resource ids were determined from READ_CONFIG.
5820 		 * Just allocate the bitmasks and provision the resource id
5821 		 * arrays.  If a port reset is active, the resources don't
5822 		 * need any action - just exit.
5823 		 */
5824 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
5825 		    LPFC_IDX_RSRC_RDY) {
5826 			lpfc_sli4_dealloc_resource_identifiers(phba);
5827 			lpfc_sli4_remove_rpis(phba);
5828 		}
5829 		/* RPIs. */
5830 		count = phba->sli4_hba.max_cfg_param.max_rpi;
5831 		if (count <= 0) {
5832 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5833 					"3279 Invalid provisioning of "
5834 					"rpi:%d\n", count);
5835 			rc = -EINVAL;
5836 			goto err_exit;
5837 		}
5838 		base = phba->sli4_hba.max_cfg_param.rpi_base;
5839 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5840 		phba->sli4_hba.rpi_bmask = kzalloc(longs *
5841 						   sizeof(unsigned long),
5842 						   GFP_KERNEL);
5843 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
5844 			rc = -ENOMEM;
5845 			goto err_exit;
5846 		}
5847 		phba->sli4_hba.rpi_ids = kzalloc(count *
5848 						 sizeof(uint16_t),
5849 						 GFP_KERNEL);
5850 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
5851 			rc = -ENOMEM;
5852 			goto free_rpi_bmask;
5853 		}
5854 
5855 		for (i = 0; i < count; i++)
5856 			phba->sli4_hba.rpi_ids[i] = base + i;
5857 
5858 		/* VPIs. */
5859 		count = phba->sli4_hba.max_cfg_param.max_vpi;
5860 		if (count <= 0) {
5861 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5862 					"3280 Invalid provisioning of "
5863 					"vpi:%d\n", count);
5864 			rc = -EINVAL;
5865 			goto free_rpi_ids;
5866 		}
5867 		base = phba->sli4_hba.max_cfg_param.vpi_base;
5868 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5869 		phba->vpi_bmask = kzalloc(longs *
5870 					  sizeof(unsigned long),
5871 					  GFP_KERNEL);
5872 		if (unlikely(!phba->vpi_bmask)) {
5873 			rc = -ENOMEM;
5874 			goto free_rpi_ids;
5875 		}
5876 		phba->vpi_ids = kzalloc(count *
5877 					sizeof(uint16_t),
5878 					GFP_KERNEL);
5879 		if (unlikely(!phba->vpi_ids)) {
5880 			rc = -ENOMEM;
5881 			goto free_vpi_bmask;
5882 		}
5883 
5884 		for (i = 0; i < count; i++)
5885 			phba->vpi_ids[i] = base + i;
5886 
5887 		/* XRIs. */
5888 		count = phba->sli4_hba.max_cfg_param.max_xri;
5889 		if (count <= 0) {
5890 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5891 					"3281 Invalid provisioning of "
5892 					"xri:%d\n", count);
5893 			rc = -EINVAL;
5894 			goto free_vpi_ids;
5895 		}
5896 		base = phba->sli4_hba.max_cfg_param.xri_base;
5897 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5898 		phba->sli4_hba.xri_bmask = kzalloc(longs *
5899 						   sizeof(unsigned long),
5900 						   GFP_KERNEL);
5901 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
5902 			rc = -ENOMEM;
5903 			goto free_vpi_ids;
5904 		}
5905 		phba->sli4_hba.max_cfg_param.xri_used = 0;
5906 		phba->sli4_hba.xri_ids = kzalloc(count *
5907 						 sizeof(uint16_t),
5908 						 GFP_KERNEL);
5909 		if (unlikely(!phba->sli4_hba.xri_ids)) {
5910 			rc = -ENOMEM;
5911 			goto free_xri_bmask;
5912 		}
5913 
5914 		for (i = 0; i < count; i++)
5915 			phba->sli4_hba.xri_ids[i] = base + i;
5916 
5917 		/* VFIs. */
5918 		count = phba->sli4_hba.max_cfg_param.max_vfi;
5919 		if (count <= 0) {
5920 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5921 					"3282 Invalid provisioning of "
5922 					"vfi:%d\n", count);
5923 			rc = -EINVAL;
5924 			goto free_xri_ids;
5925 		}
5926 		base = phba->sli4_hba.max_cfg_param.vfi_base;
5927 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
5928 		phba->sli4_hba.vfi_bmask = kzalloc(longs *
5929 						   sizeof(unsigned long),
5930 						   GFP_KERNEL);
5931 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
5932 			rc = -ENOMEM;
5933 			goto free_xri_ids;
5934 		}
5935 		phba->sli4_hba.vfi_ids = kzalloc(count *
5936 						 sizeof(uint16_t),
5937 						 GFP_KERNEL);
5938 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
5939 			rc = -ENOMEM;
5940 			goto free_vfi_bmask;
5941 		}
5942 
5943 		for (i = 0; i < count; i++)
5944 			phba->sli4_hba.vfi_ids[i] = base + i;
5945 
5946 		/*
5947 		 * Mark all resources ready.  An HBA reset doesn't need
5948 		 * to reset the initialization.
5949 		 */
5950 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
5951 		       LPFC_IDX_RSRC_RDY);
5952 		return 0;
5953 	}
5954 
5955  free_vfi_bmask:
5956 	kfree(phba->sli4_hba.vfi_bmask);
5957  free_xri_ids:
5958 	kfree(phba->sli4_hba.xri_ids);
5959  free_xri_bmask:
5960 	kfree(phba->sli4_hba.xri_bmask);
5961  free_vpi_ids:
5962 	kfree(phba->vpi_ids);
5963  free_vpi_bmask:
5964 	kfree(phba->vpi_bmask);
5965  free_rpi_ids:
5966 	kfree(phba->sli4_hba.rpi_ids);
5967  free_rpi_bmask:
5968 	kfree(phba->sli4_hba.rpi_bmask);
5969  err_exit:
5970 	return rc;
5971 }
5972 
5973 /**
5974  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
5975  * @phba: Pointer to HBA context object.
5976  *
5977  * This function allocates the number of elements for the specified
5978  * resource type.
5979  **/
5980 int
5981 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
5982 {
5983 	if (phba->sli4_hba.extents_in_use) {
5984 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
5985 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
5986 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
5987 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
5988 	} else {
5989 		kfree(phba->vpi_bmask);
5990 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
5991 		kfree(phba->vpi_ids);
5992 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5993 		kfree(phba->sli4_hba.xri_bmask);
5994 		kfree(phba->sli4_hba.xri_ids);
5995 		kfree(phba->sli4_hba.vfi_bmask);
5996 		kfree(phba->sli4_hba.vfi_ids);
5997 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5998 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
5999 	}
6000 
6001 	return 0;
6002 }
6003 
6004 /**
6005  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
6006  * @phba: Pointer to HBA context object.
6007  * @type: The resource extent type.
6008  * @extnt_count: buffer to hold port extent count response
6009  * @extnt_size: buffer to hold port extent size response.
6010  *
6011  * This function calls the port to read the host allocated extents
6012  * for a particular type.
6013  **/
6014 int
6015 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
6016 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
6017 {
6018 	bool emb;
6019 	int rc = 0;
6020 	uint16_t curr_blks = 0;
6021 	uint32_t req_len, emb_len;
6022 	uint32_t alloc_len, mbox_tmo;
6023 	struct list_head *blk_list_head;
6024 	struct lpfc_rsrc_blks *rsrc_blk;
6025 	LPFC_MBOXQ_t *mbox;
6026 	void *virtaddr = NULL;
6027 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6028 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6029 	union  lpfc_sli4_cfg_shdr *shdr;
6030 
6031 	switch (type) {
6032 	case LPFC_RSC_TYPE_FCOE_VPI:
6033 		blk_list_head = &phba->lpfc_vpi_blk_list;
6034 		break;
6035 	case LPFC_RSC_TYPE_FCOE_XRI:
6036 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
6037 		break;
6038 	case LPFC_RSC_TYPE_FCOE_VFI:
6039 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
6040 		break;
6041 	case LPFC_RSC_TYPE_FCOE_RPI:
6042 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
6043 		break;
6044 	default:
6045 		return -EIO;
6046 	}
6047 
6048 	/* Count the number of extents currently allocatd for this type. */
6049 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
6050 		if (curr_blks == 0) {
6051 			/*
6052 			 * The GET_ALLOCATED mailbox does not return the size,
6053 			 * just the count.  The size should be just the size
6054 			 * stored in the current allocated block and all sizes
6055 			 * for an extent type are the same so set the return
6056 			 * value now.
6057 			 */
6058 			*extnt_size = rsrc_blk->rsrc_size;
6059 		}
6060 		curr_blks++;
6061 	}
6062 
6063 	/*
6064 	 * Calculate the size of an embedded mailbox.  The uint32_t
6065 	 * accounts for extents-specific word.
6066 	 */
6067 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6068 		sizeof(uint32_t);
6069 
6070 	/*
6071 	 * Presume the allocation and response will fit into an embedded
6072 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6073 	 */
6074 	emb = LPFC_SLI4_MBX_EMBED;
6075 	req_len = emb_len;
6076 	if (req_len > emb_len) {
6077 		req_len = curr_blks * sizeof(uint16_t) +
6078 			sizeof(union lpfc_sli4_cfg_shdr) +
6079 			sizeof(uint32_t);
6080 		emb = LPFC_SLI4_MBX_NEMBED;
6081 	}
6082 
6083 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6084 	if (!mbox)
6085 		return -ENOMEM;
6086 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
6087 
6088 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6089 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
6090 				     req_len, emb);
6091 	if (alloc_len < req_len) {
6092 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6093 			"2983 Allocated DMA memory size (x%x) is "
6094 			"less than the requested DMA memory "
6095 			"size (x%x)\n", alloc_len, req_len);
6096 		rc = -ENOMEM;
6097 		goto err_exit;
6098 	}
6099 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
6100 	if (unlikely(rc)) {
6101 		rc = -EIO;
6102 		goto err_exit;
6103 	}
6104 
6105 	if (!phba->sli4_hba.intr_enable)
6106 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6107 	else {
6108 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6109 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6110 	}
6111 
6112 	if (unlikely(rc)) {
6113 		rc = -EIO;
6114 		goto err_exit;
6115 	}
6116 
6117 	/*
6118 	 * Figure out where the response is located.  Then get local pointers
6119 	 * to the response data.  The port does not guarantee to respond to
6120 	 * all extents counts request so update the local variable with the
6121 	 * allocated count from the port.
6122 	 */
6123 	if (emb == LPFC_SLI4_MBX_EMBED) {
6124 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6125 		shdr = &rsrc_ext->header.cfg_shdr;
6126 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6127 	} else {
6128 		virtaddr = mbox->sge_array->addr[0];
6129 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6130 		shdr = &n_rsrc->cfg_shdr;
6131 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6132 	}
6133 
6134 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
6135 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
6136 			"2984 Failed to read allocated resources "
6137 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
6138 			type,
6139 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
6140 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
6141 		rc = -EIO;
6142 		goto err_exit;
6143 	}
6144  err_exit:
6145 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6146 	return rc;
6147 }
6148 
6149 /**
6150  * lpfc_sli4_repost_els_sgl_list - Repsot the els buffers sgl pages as block
6151  * @phba: pointer to lpfc hba data structure.
6152  *
6153  * This routine walks the list of els buffers that have been allocated and
6154  * repost them to the port by using SGL block post. This is needed after a
6155  * pci_function_reset/warm_start or start. It attempts to construct blocks
6156  * of els buffer sgls which contains contiguous xris and uses the non-embedded
6157  * SGL block post mailbox commands to post them to the port. For single els
6158  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
6159  * mailbox command for posting.
6160  *
6161  * Returns: 0 = success, non-zero failure.
6162  **/
6163 static int
6164 lpfc_sli4_repost_els_sgl_list(struct lpfc_hba *phba)
6165 {
6166 	struct lpfc_sglq *sglq_entry = NULL;
6167 	struct lpfc_sglq *sglq_entry_next = NULL;
6168 	struct lpfc_sglq *sglq_entry_first = NULL;
6169 	int status, total_cnt, post_cnt = 0, num_posted = 0, block_cnt = 0;
6170 	int last_xritag = NO_XRI;
6171 	struct lpfc_sli_ring *pring;
6172 	LIST_HEAD(prep_sgl_list);
6173 	LIST_HEAD(blck_sgl_list);
6174 	LIST_HEAD(allc_sgl_list);
6175 	LIST_HEAD(post_sgl_list);
6176 	LIST_HEAD(free_sgl_list);
6177 
6178 	pring = &phba->sli.ring[LPFC_ELS_RING];
6179 	spin_lock_irq(&phba->hbalock);
6180 	spin_lock(&pring->ring_lock);
6181 	list_splice_init(&phba->sli4_hba.lpfc_sgl_list, &allc_sgl_list);
6182 	spin_unlock(&pring->ring_lock);
6183 	spin_unlock_irq(&phba->hbalock);
6184 
6185 	total_cnt = phba->sli4_hba.els_xri_cnt;
6186 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
6187 				 &allc_sgl_list, list) {
6188 		list_del_init(&sglq_entry->list);
6189 		block_cnt++;
6190 		if ((last_xritag != NO_XRI) &&
6191 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
6192 			/* a hole in xri block, form a sgl posting block */
6193 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
6194 			post_cnt = block_cnt - 1;
6195 			/* prepare list for next posting block */
6196 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
6197 			block_cnt = 1;
6198 		} else {
6199 			/* prepare list for next posting block */
6200 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
6201 			/* enough sgls for non-embed sgl mbox command */
6202 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
6203 				list_splice_init(&prep_sgl_list,
6204 						 &blck_sgl_list);
6205 				post_cnt = block_cnt;
6206 				block_cnt = 0;
6207 			}
6208 		}
6209 		num_posted++;
6210 
6211 		/* keep track of last sgl's xritag */
6212 		last_xritag = sglq_entry->sli4_xritag;
6213 
6214 		/* end of repost sgl list condition for els buffers */
6215 		if (num_posted == phba->sli4_hba.els_xri_cnt) {
6216 			if (post_cnt == 0) {
6217 				list_splice_init(&prep_sgl_list,
6218 						 &blck_sgl_list);
6219 				post_cnt = block_cnt;
6220 			} else if (block_cnt == 1) {
6221 				status = lpfc_sli4_post_sgl(phba,
6222 						sglq_entry->phys, 0,
6223 						sglq_entry->sli4_xritag);
6224 				if (!status) {
6225 					/* successful, put sgl to posted list */
6226 					list_add_tail(&sglq_entry->list,
6227 						      &post_sgl_list);
6228 				} else {
6229 					/* Failure, put sgl to free list */
6230 					lpfc_printf_log(phba, KERN_WARNING,
6231 						LOG_SLI,
6232 						"3159 Failed to post els "
6233 						"sgl, xritag:x%x\n",
6234 						sglq_entry->sli4_xritag);
6235 					list_add_tail(&sglq_entry->list,
6236 						      &free_sgl_list);
6237 					total_cnt--;
6238 				}
6239 			}
6240 		}
6241 
6242 		/* continue until a nembed page worth of sgls */
6243 		if (post_cnt == 0)
6244 			continue;
6245 
6246 		/* post the els buffer list sgls as a block */
6247 		status = lpfc_sli4_post_els_sgl_list(phba, &blck_sgl_list,
6248 						     post_cnt);
6249 
6250 		if (!status) {
6251 			/* success, put sgl list to posted sgl list */
6252 			list_splice_init(&blck_sgl_list, &post_sgl_list);
6253 		} else {
6254 			/* Failure, put sgl list to free sgl list */
6255 			sglq_entry_first = list_first_entry(&blck_sgl_list,
6256 							    struct lpfc_sglq,
6257 							    list);
6258 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6259 					"3160 Failed to post els sgl-list, "
6260 					"xritag:x%x-x%x\n",
6261 					sglq_entry_first->sli4_xritag,
6262 					(sglq_entry_first->sli4_xritag +
6263 					 post_cnt - 1));
6264 			list_splice_init(&blck_sgl_list, &free_sgl_list);
6265 			total_cnt -= post_cnt;
6266 		}
6267 
6268 		/* don't reset xirtag due to hole in xri block */
6269 		if (block_cnt == 0)
6270 			last_xritag = NO_XRI;
6271 
6272 		/* reset els sgl post count for next round of posting */
6273 		post_cnt = 0;
6274 	}
6275 	/* update the number of XRIs posted for ELS */
6276 	phba->sli4_hba.els_xri_cnt = total_cnt;
6277 
6278 	/* free the els sgls failed to post */
6279 	lpfc_free_sgl_list(phba, &free_sgl_list);
6280 
6281 	/* push els sgls posted to the availble list */
6282 	if (!list_empty(&post_sgl_list)) {
6283 		spin_lock_irq(&phba->hbalock);
6284 		spin_lock(&pring->ring_lock);
6285 		list_splice_init(&post_sgl_list,
6286 				 &phba->sli4_hba.lpfc_sgl_list);
6287 		spin_unlock(&pring->ring_lock);
6288 		spin_unlock_irq(&phba->hbalock);
6289 	} else {
6290 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6291 				"3161 Failure to post els sgl to port.\n");
6292 		return -EIO;
6293 	}
6294 	return 0;
6295 }
6296 
6297 void
6298 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
6299 {
6300 	uint32_t len;
6301 
6302 	len = sizeof(struct lpfc_mbx_set_host_data) -
6303 		sizeof(struct lpfc_sli4_cfg_mhdr);
6304 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6305 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
6306 			 LPFC_SLI4_MBX_EMBED);
6307 
6308 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
6309 	mbox->u.mqe.un.set_host_data.param_len = 8;
6310 	snprintf(mbox->u.mqe.un.set_host_data.data,
6311 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
6312 		 "Linux %s v"LPFC_DRIVER_VERSION,
6313 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
6314 }
6315 
6316 /**
6317  * lpfc_sli4_hba_setup - SLI4 device intialization PCI function
6318  * @phba: Pointer to HBA context object.
6319  *
6320  * This function is the main SLI4 device intialization PCI function. This
6321  * function is called by the HBA intialization code, HBA reset code and
6322  * HBA error attention handler code. Caller is not required to hold any
6323  * locks.
6324  **/
6325 int
6326 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
6327 {
6328 	int rc;
6329 	LPFC_MBOXQ_t *mboxq;
6330 	struct lpfc_mqe *mqe;
6331 	uint8_t *vpd;
6332 	uint32_t vpd_size;
6333 	uint32_t ftr_rsp = 0;
6334 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
6335 	struct lpfc_vport *vport = phba->pport;
6336 	struct lpfc_dmabuf *mp;
6337 
6338 	/* Perform a PCI function reset to start from clean */
6339 	rc = lpfc_pci_function_reset(phba);
6340 	if (unlikely(rc))
6341 		return -ENODEV;
6342 
6343 	/* Check the HBA Host Status Register for readyness */
6344 	rc = lpfc_sli4_post_status_check(phba);
6345 	if (unlikely(rc))
6346 		return -ENODEV;
6347 	else {
6348 		spin_lock_irq(&phba->hbalock);
6349 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
6350 		spin_unlock_irq(&phba->hbalock);
6351 	}
6352 
6353 	/*
6354 	 * Allocate a single mailbox container for initializing the
6355 	 * port.
6356 	 */
6357 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6358 	if (!mboxq)
6359 		return -ENOMEM;
6360 
6361 	/* Issue READ_REV to collect vpd and FW information. */
6362 	vpd_size = SLI4_PAGE_SIZE;
6363 	vpd = kzalloc(vpd_size, GFP_KERNEL);
6364 	if (!vpd) {
6365 		rc = -ENOMEM;
6366 		goto out_free_mbox;
6367 	}
6368 
6369 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
6370 	if (unlikely(rc)) {
6371 		kfree(vpd);
6372 		goto out_free_mbox;
6373 	}
6374 
6375 	mqe = &mboxq->u.mqe;
6376 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
6377 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
6378 		phba->hba_flag |= HBA_FCOE_MODE;
6379 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
6380 	} else {
6381 		phba->hba_flag &= ~HBA_FCOE_MODE;
6382 	}
6383 
6384 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
6385 		LPFC_DCBX_CEE_MODE)
6386 		phba->hba_flag |= HBA_FIP_SUPPORT;
6387 	else
6388 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
6389 
6390 	phba->hba_flag &= ~HBA_FCP_IOQ_FLUSH;
6391 
6392 	if (phba->sli_rev != LPFC_SLI_REV4) {
6393 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6394 			"0376 READ_REV Error. SLI Level %d "
6395 			"FCoE enabled %d\n",
6396 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
6397 		rc = -EIO;
6398 		kfree(vpd);
6399 		goto out_free_mbox;
6400 	}
6401 
6402 	/*
6403 	 * Continue initialization with default values even if driver failed
6404 	 * to read FCoE param config regions, only read parameters if the
6405 	 * board is FCoE
6406 	 */
6407 	if (phba->hba_flag & HBA_FCOE_MODE &&
6408 	    lpfc_sli4_read_fcoe_params(phba))
6409 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
6410 			"2570 Failed to read FCoE parameters\n");
6411 
6412 	/*
6413 	 * Retrieve sli4 device physical port name, failure of doing it
6414 	 * is considered as non-fatal.
6415 	 */
6416 	rc = lpfc_sli4_retrieve_pport_name(phba);
6417 	if (!rc)
6418 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
6419 				"3080 Successful retrieving SLI4 device "
6420 				"physical port name: %s.\n", phba->Port);
6421 
6422 	/*
6423 	 * Evaluate the read rev and vpd data. Populate the driver
6424 	 * state with the results. If this routine fails, the failure
6425 	 * is not fatal as the driver will use generic values.
6426 	 */
6427 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
6428 	if (unlikely(!rc)) {
6429 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6430 				"0377 Error %d parsing vpd. "
6431 				"Using defaults.\n", rc);
6432 		rc = 0;
6433 	}
6434 	kfree(vpd);
6435 
6436 	/* Save information as VPD data */
6437 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
6438 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
6439 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
6440 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
6441 					 &mqe->un.read_rev);
6442 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
6443 				       &mqe->un.read_rev);
6444 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
6445 					    &mqe->un.read_rev);
6446 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
6447 					   &mqe->un.read_rev);
6448 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
6449 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
6450 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
6451 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
6452 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
6453 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
6454 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
6455 			"(%d):0380 READ_REV Status x%x "
6456 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
6457 			mboxq->vport ? mboxq->vport->vpi : 0,
6458 			bf_get(lpfc_mqe_status, mqe),
6459 			phba->vpd.rev.opFwName,
6460 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
6461 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
6462 
6463 	/* Reset the DFT_LUN_Q_DEPTH to (max xri >> 3)  */
6464 	rc = (phba->sli4_hba.max_cfg_param.max_xri >> 3);
6465 	if (phba->pport->cfg_lun_queue_depth > rc) {
6466 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6467 				"3362 LUN queue depth changed from %d to %d\n",
6468 				phba->pport->cfg_lun_queue_depth, rc);
6469 		phba->pport->cfg_lun_queue_depth = rc;
6470 	}
6471 
6472 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
6473 	    LPFC_SLI_INTF_IF_TYPE_0) {
6474 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
6475 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6476 		if (rc == MBX_SUCCESS) {
6477 			phba->hba_flag |= HBA_RECOVERABLE_UE;
6478 			/* Set 1Sec interval to detect UE */
6479 			phba->eratt_poll_interval = 1;
6480 			phba->sli4_hba.ue_to_sr = bf_get(
6481 					lpfc_mbx_set_feature_UESR,
6482 					&mboxq->u.mqe.un.set_feature);
6483 			phba->sli4_hba.ue_to_rp = bf_get(
6484 					lpfc_mbx_set_feature_UERP,
6485 					&mboxq->u.mqe.un.set_feature);
6486 		}
6487 	}
6488 
6489 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
6490 		/* Enable MDS Diagnostics only if the SLI Port supports it */
6491 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
6492 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6493 		if (rc != MBX_SUCCESS)
6494 			phba->mds_diags_support = 0;
6495 	}
6496 
6497 	/*
6498 	 * Discover the port's supported feature set and match it against the
6499 	 * hosts requests.
6500 	 */
6501 	lpfc_request_features(phba, mboxq);
6502 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6503 	if (unlikely(rc)) {
6504 		rc = -EIO;
6505 		goto out_free_mbox;
6506 	}
6507 
6508 	/*
6509 	 * The port must support FCP initiator mode as this is the
6510 	 * only mode running in the host.
6511 	 */
6512 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
6513 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
6514 				"0378 No support for fcpi mode.\n");
6515 		ftr_rsp++;
6516 	}
6517 	if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
6518 		phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
6519 	else
6520 		phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
6521 	/*
6522 	 * If the port cannot support the host's requested features
6523 	 * then turn off the global config parameters to disable the
6524 	 * feature in the driver.  This is not a fatal error.
6525 	 */
6526 	phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
6527 	if (phba->cfg_enable_bg) {
6528 		if (bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))
6529 			phba->sli3_options |= LPFC_SLI3_BG_ENABLED;
6530 		else
6531 			ftr_rsp++;
6532 	}
6533 
6534 	if (phba->max_vpi && phba->cfg_enable_npiv &&
6535 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
6536 		ftr_rsp++;
6537 
6538 	if (ftr_rsp) {
6539 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
6540 				"0379 Feature Mismatch Data: x%08x %08x "
6541 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
6542 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
6543 				phba->cfg_enable_npiv, phba->max_vpi);
6544 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
6545 			phba->cfg_enable_bg = 0;
6546 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
6547 			phba->cfg_enable_npiv = 0;
6548 	}
6549 
6550 	/* These SLI3 features are assumed in SLI4 */
6551 	spin_lock_irq(&phba->hbalock);
6552 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
6553 	spin_unlock_irq(&phba->hbalock);
6554 
6555 	/*
6556 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
6557 	 * calls depends on these resources to complete port setup.
6558 	 */
6559 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
6560 	if (rc) {
6561 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6562 				"2920 Failed to alloc Resource IDs "
6563 				"rc = x%x\n", rc);
6564 		goto out_free_mbox;
6565 	}
6566 
6567 	lpfc_set_host_data(phba, mboxq);
6568 
6569 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6570 	if (rc) {
6571 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
6572 				"2134 Failed to set host os driver version %x",
6573 				rc);
6574 	}
6575 
6576 	/* Read the port's service parameters. */
6577 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
6578 	if (rc) {
6579 		phba->link_state = LPFC_HBA_ERROR;
6580 		rc = -ENOMEM;
6581 		goto out_free_mbox;
6582 	}
6583 
6584 	mboxq->vport = vport;
6585 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6586 	mp = (struct lpfc_dmabuf *) mboxq->context1;
6587 	if (rc == MBX_SUCCESS) {
6588 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
6589 		rc = 0;
6590 	}
6591 
6592 	/*
6593 	 * This memory was allocated by the lpfc_read_sparam routine. Release
6594 	 * it to the mbuf pool.
6595 	 */
6596 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
6597 	kfree(mp);
6598 	mboxq->context1 = NULL;
6599 	if (unlikely(rc)) {
6600 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6601 				"0382 READ_SPARAM command failed "
6602 				"status %d, mbxStatus x%x\n",
6603 				rc, bf_get(lpfc_mqe_status, mqe));
6604 		phba->link_state = LPFC_HBA_ERROR;
6605 		rc = -EIO;
6606 		goto out_free_mbox;
6607 	}
6608 
6609 	lpfc_update_vport_wwn(vport);
6610 
6611 	/* Update the fc_host data structures with new wwn. */
6612 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
6613 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
6614 
6615 	/* update host els and scsi xri-sgl sizes and mappings */
6616 	rc = lpfc_sli4_xri_sgl_update(phba);
6617 	if (unlikely(rc)) {
6618 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6619 				"1400 Failed to update xri-sgl size and "
6620 				"mapping: %d\n", rc);
6621 		goto out_free_mbox;
6622 	}
6623 
6624 	/* register the els sgl pool to the port */
6625 	rc = lpfc_sli4_repost_els_sgl_list(phba);
6626 	if (unlikely(rc)) {
6627 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6628 				"0582 Error %d during els sgl post "
6629 				"operation\n", rc);
6630 		rc = -ENODEV;
6631 		goto out_free_mbox;
6632 	}
6633 
6634 	/* register the allocated scsi sgl pool to the port */
6635 	rc = lpfc_sli4_repost_scsi_sgl_list(phba);
6636 	if (unlikely(rc)) {
6637 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6638 				"0383 Error %d during scsi sgl post "
6639 				"operation\n", rc);
6640 		/* Some Scsi buffers were moved to the abort scsi list */
6641 		/* A pci function reset will repost them */
6642 		rc = -ENODEV;
6643 		goto out_free_mbox;
6644 	}
6645 
6646 	/* Post the rpi header region to the device. */
6647 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
6648 	if (unlikely(rc)) {
6649 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6650 				"0393 Error %d during rpi post operation\n",
6651 				rc);
6652 		rc = -ENODEV;
6653 		goto out_free_mbox;
6654 	}
6655 	lpfc_sli4_node_prep(phba);
6656 
6657 	/* Create all the SLI4 queues */
6658 	rc = lpfc_sli4_queue_create(phba);
6659 	if (rc) {
6660 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6661 				"3089 Failed to allocate queues\n");
6662 		rc = -ENODEV;
6663 		goto out_stop_timers;
6664 	}
6665 	/* Set up all the queues to the device */
6666 	rc = lpfc_sli4_queue_setup(phba);
6667 	if (unlikely(rc)) {
6668 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6669 				"0381 Error %d during queue setup.\n ", rc);
6670 		goto out_destroy_queue;
6671 	}
6672 
6673 	/* Arm the CQs and then EQs on device */
6674 	lpfc_sli4_arm_cqeq_intr(phba);
6675 
6676 	/* Indicate device interrupt mode */
6677 	phba->sli4_hba.intr_enable = 1;
6678 
6679 	/* Allow asynchronous mailbox command to go through */
6680 	spin_lock_irq(&phba->hbalock);
6681 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
6682 	spin_unlock_irq(&phba->hbalock);
6683 
6684 	/* Post receive buffers to the device */
6685 	lpfc_sli4_rb_setup(phba);
6686 
6687 	/* Reset HBA FCF states after HBA reset */
6688 	phba->fcf.fcf_flag = 0;
6689 	phba->fcf.current_rec.flag = 0;
6690 
6691 	/* Start the ELS watchdog timer */
6692 	mod_timer(&vport->els_tmofunc,
6693 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
6694 
6695 	/* Start heart beat timer */
6696 	mod_timer(&phba->hb_tmofunc,
6697 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
6698 	phba->hb_outstanding = 0;
6699 	phba->last_completion_time = jiffies;
6700 
6701 	/* Start error attention (ERATT) polling timer */
6702 	mod_timer(&phba->eratt_poll,
6703 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
6704 
6705 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
6706 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
6707 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
6708 		if (!rc) {
6709 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6710 					"2829 This device supports "
6711 					"Advanced Error Reporting (AER)\n");
6712 			spin_lock_irq(&phba->hbalock);
6713 			phba->hba_flag |= HBA_AER_ENABLED;
6714 			spin_unlock_irq(&phba->hbalock);
6715 		} else {
6716 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
6717 					"2830 This device does not support "
6718 					"Advanced Error Reporting (AER)\n");
6719 			phba->cfg_aer_support = 0;
6720 		}
6721 		rc = 0;
6722 	}
6723 
6724 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
6725 		/*
6726 		 * The FC Port needs to register FCFI (index 0)
6727 		 */
6728 		lpfc_reg_fcfi(phba, mboxq);
6729 		mboxq->vport = phba->pport;
6730 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6731 		if (rc != MBX_SUCCESS)
6732 			goto out_unset_queue;
6733 		rc = 0;
6734 		phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
6735 					&mboxq->u.mqe.un.reg_fcfi);
6736 
6737 		/* Check if the port is configured to be disabled */
6738 		lpfc_sli_read_link_ste(phba);
6739 	}
6740 
6741 	/*
6742 	 * The port is ready, set the host's link state to LINK_DOWN
6743 	 * in preparation for link interrupts.
6744 	 */
6745 	spin_lock_irq(&phba->hbalock);
6746 	phba->link_state = LPFC_LINK_DOWN;
6747 	spin_unlock_irq(&phba->hbalock);
6748 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
6749 	    (phba->hba_flag & LINK_DISABLED)) {
6750 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
6751 				"3103 Adapter Link is disabled.\n");
6752 		lpfc_down_link(phba, mboxq);
6753 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6754 		if (rc != MBX_SUCCESS) {
6755 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
6756 					"3104 Adapter failed to issue "
6757 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
6758 			goto out_unset_queue;
6759 		}
6760 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
6761 		/* don't perform init_link on SLI4 FC port loopback test */
6762 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
6763 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
6764 			if (rc)
6765 				goto out_unset_queue;
6766 		}
6767 	}
6768 	mempool_free(mboxq, phba->mbox_mem_pool);
6769 	return rc;
6770 out_unset_queue:
6771 	/* Unset all the queues set up in this routine when error out */
6772 	lpfc_sli4_queue_unset(phba);
6773 out_destroy_queue:
6774 	lpfc_sli4_queue_destroy(phba);
6775 out_stop_timers:
6776 	lpfc_stop_hba_timers(phba);
6777 out_free_mbox:
6778 	mempool_free(mboxq, phba->mbox_mem_pool);
6779 	return rc;
6780 }
6781 
6782 /**
6783  * lpfc_mbox_timeout - Timeout call back function for mbox timer
6784  * @ptr: context object - pointer to hba structure.
6785  *
6786  * This is the callback function for mailbox timer. The mailbox
6787  * timer is armed when a new mailbox command is issued and the timer
6788  * is deleted when the mailbox complete. The function is called by
6789  * the kernel timer code when a mailbox does not complete within
6790  * expected time. This function wakes up the worker thread to
6791  * process the mailbox timeout and returns. All the processing is
6792  * done by the worker thread function lpfc_mbox_timeout_handler.
6793  **/
6794 void
6795 lpfc_mbox_timeout(unsigned long ptr)
6796 {
6797 	struct lpfc_hba  *phba = (struct lpfc_hba *) ptr;
6798 	unsigned long iflag;
6799 	uint32_t tmo_posted;
6800 
6801 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
6802 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
6803 	if (!tmo_posted)
6804 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
6805 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
6806 
6807 	if (!tmo_posted)
6808 		lpfc_worker_wake_up(phba);
6809 	return;
6810 }
6811 
6812 /**
6813  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
6814  *                                    are pending
6815  * @phba: Pointer to HBA context object.
6816  *
6817  * This function checks if any mailbox completions are present on the mailbox
6818  * completion queue.
6819  **/
6820 static bool
6821 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
6822 {
6823 
6824 	uint32_t idx;
6825 	struct lpfc_queue *mcq;
6826 	struct lpfc_mcqe *mcqe;
6827 	bool pending_completions = false;
6828 
6829 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
6830 		return false;
6831 
6832 	/* Check for completions on mailbox completion queue */
6833 
6834 	mcq = phba->sli4_hba.mbx_cq;
6835 	idx = mcq->hba_index;
6836 	while (bf_get_le32(lpfc_cqe_valid, mcq->qe[idx].cqe)) {
6837 		mcqe = (struct lpfc_mcqe *)mcq->qe[idx].cqe;
6838 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
6839 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
6840 			pending_completions = true;
6841 			break;
6842 		}
6843 		idx = (idx + 1) % mcq->entry_count;
6844 		if (mcq->hba_index == idx)
6845 			break;
6846 	}
6847 	return pending_completions;
6848 
6849 }
6850 
6851 /**
6852  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
6853  *					      that were missed.
6854  * @phba: Pointer to HBA context object.
6855  *
6856  * For sli4, it is possible to miss an interrupt. As such mbox completions
6857  * maybe missed causing erroneous mailbox timeouts to occur. This function
6858  * checks to see if mbox completions are on the mailbox completion queue
6859  * and will process all the completions associated with the eq for the
6860  * mailbox completion queue.
6861  **/
6862 bool
6863 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
6864 {
6865 
6866 	uint32_t eqidx;
6867 	struct lpfc_queue *fpeq = NULL;
6868 	struct lpfc_eqe *eqe;
6869 	bool mbox_pending;
6870 
6871 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
6872 		return false;
6873 
6874 	/* Find the eq associated with the mcq */
6875 
6876 	if (phba->sli4_hba.hba_eq)
6877 		for (eqidx = 0; eqidx < phba->cfg_fcp_io_channel; eqidx++)
6878 			if (phba->sli4_hba.hba_eq[eqidx]->queue_id ==
6879 			    phba->sli4_hba.mbx_cq->assoc_qid) {
6880 				fpeq = phba->sli4_hba.hba_eq[eqidx];
6881 				break;
6882 			}
6883 	if (!fpeq)
6884 		return false;
6885 
6886 	/* Turn off interrupts from this EQ */
6887 
6888 	lpfc_sli4_eq_clr_intr(fpeq);
6889 
6890 	/* Check to see if a mbox completion is pending */
6891 
6892 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
6893 
6894 	/*
6895 	 * If a mbox completion is pending, process all the events on EQ
6896 	 * associated with the mbox completion queue (this could include
6897 	 * mailbox commands, async events, els commands, receive queue data
6898 	 * and fcp commands)
6899 	 */
6900 
6901 	if (mbox_pending)
6902 		while ((eqe = lpfc_sli4_eq_get(fpeq))) {
6903 			lpfc_sli4_hba_handle_eqe(phba, eqe, eqidx);
6904 			fpeq->EQ_processed++;
6905 		}
6906 
6907 	/* Always clear and re-arm the EQ */
6908 
6909 	lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_REARM);
6910 
6911 	return mbox_pending;
6912 
6913 }
6914 
6915 /**
6916  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
6917  * @phba: Pointer to HBA context object.
6918  *
6919  * This function is called from worker thread when a mailbox command times out.
6920  * The caller is not required to hold any locks. This function will reset the
6921  * HBA and recover all the pending commands.
6922  **/
6923 void
6924 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
6925 {
6926 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
6927 	MAILBOX_t *mb = NULL;
6928 
6929 	struct lpfc_sli *psli = &phba->sli;
6930 
6931 	/* If the mailbox completed, process the completion and return */
6932 	if (lpfc_sli4_process_missed_mbox_completions(phba))
6933 		return;
6934 
6935 	if (pmbox != NULL)
6936 		mb = &pmbox->u.mb;
6937 	/* Check the pmbox pointer first.  There is a race condition
6938 	 * between the mbox timeout handler getting executed in the
6939 	 * worklist and the mailbox actually completing. When this
6940 	 * race condition occurs, the mbox_active will be NULL.
6941 	 */
6942 	spin_lock_irq(&phba->hbalock);
6943 	if (pmbox == NULL) {
6944 		lpfc_printf_log(phba, KERN_WARNING,
6945 				LOG_MBOX | LOG_SLI,
6946 				"0353 Active Mailbox cleared - mailbox timeout "
6947 				"exiting\n");
6948 		spin_unlock_irq(&phba->hbalock);
6949 		return;
6950 	}
6951 
6952 	/* Mbox cmd <mbxCommand> timeout */
6953 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6954 			"0310 Mailbox command x%x timeout Data: x%x x%x x%p\n",
6955 			mb->mbxCommand,
6956 			phba->pport->port_state,
6957 			phba->sli.sli_flag,
6958 			phba->sli.mbox_active);
6959 	spin_unlock_irq(&phba->hbalock);
6960 
6961 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
6962 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
6963 	 * it to fail all outstanding SCSI IO.
6964 	 */
6965 	spin_lock_irq(&phba->pport->work_port_lock);
6966 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
6967 	spin_unlock_irq(&phba->pport->work_port_lock);
6968 	spin_lock_irq(&phba->hbalock);
6969 	phba->link_state = LPFC_LINK_UNKNOWN;
6970 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
6971 	spin_unlock_irq(&phba->hbalock);
6972 
6973 	lpfc_sli_abort_fcp_rings(phba);
6974 
6975 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
6976 			"0345 Resetting board due to mailbox timeout\n");
6977 
6978 	/* Reset the HBA device */
6979 	lpfc_reset_hba(phba);
6980 }
6981 
6982 /**
6983  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
6984  * @phba: Pointer to HBA context object.
6985  * @pmbox: Pointer to mailbox object.
6986  * @flag: Flag indicating how the mailbox need to be processed.
6987  *
6988  * This function is called by discovery code and HBA management code
6989  * to submit a mailbox command to firmware with SLI-3 interface spec. This
6990  * function gets the hbalock to protect the data structures.
6991  * The mailbox command can be submitted in polling mode, in which case
6992  * this function will wait in a polling loop for the completion of the
6993  * mailbox.
6994  * If the mailbox is submitted in no_wait mode (not polling) the
6995  * function will submit the command and returns immediately without waiting
6996  * for the mailbox completion. The no_wait is supported only when HBA
6997  * is in SLI2/SLI3 mode - interrupts are enabled.
6998  * The SLI interface allows only one mailbox pending at a time. If the
6999  * mailbox is issued in polling mode and there is already a mailbox
7000  * pending, then the function will return an error. If the mailbox is issued
7001  * in NO_WAIT mode and there is a mailbox pending already, the function
7002  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
7003  * The sli layer owns the mailbox object until the completion of mailbox
7004  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
7005  * return codes the caller owns the mailbox command after the return of
7006  * the function.
7007  **/
7008 static int
7009 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
7010 		       uint32_t flag)
7011 {
7012 	MAILBOX_t *mbx;
7013 	struct lpfc_sli *psli = &phba->sli;
7014 	uint32_t status, evtctr;
7015 	uint32_t ha_copy, hc_copy;
7016 	int i;
7017 	unsigned long timeout;
7018 	unsigned long drvr_flag = 0;
7019 	uint32_t word0, ldata;
7020 	void __iomem *to_slim;
7021 	int processing_queue = 0;
7022 
7023 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
7024 	if (!pmbox) {
7025 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7026 		/* processing mbox queue from intr_handler */
7027 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
7028 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7029 			return MBX_SUCCESS;
7030 		}
7031 		processing_queue = 1;
7032 		pmbox = lpfc_mbox_get(phba);
7033 		if (!pmbox) {
7034 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7035 			return MBX_SUCCESS;
7036 		}
7037 	}
7038 
7039 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
7040 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
7041 		if(!pmbox->vport) {
7042 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7043 			lpfc_printf_log(phba, KERN_ERR,
7044 					LOG_MBOX | LOG_VPORT,
7045 					"1806 Mbox x%x failed. No vport\n",
7046 					pmbox->u.mb.mbxCommand);
7047 			dump_stack();
7048 			goto out_not_finished;
7049 		}
7050 	}
7051 
7052 	/* If the PCI channel is in offline state, do not post mbox. */
7053 	if (unlikely(pci_channel_offline(phba->pcidev))) {
7054 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7055 		goto out_not_finished;
7056 	}
7057 
7058 	/* If HBA has a deferred error attention, fail the iocb. */
7059 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
7060 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7061 		goto out_not_finished;
7062 	}
7063 
7064 	psli = &phba->sli;
7065 
7066 	mbx = &pmbox->u.mb;
7067 	status = MBX_SUCCESS;
7068 
7069 	if (phba->link_state == LPFC_HBA_ERROR) {
7070 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7071 
7072 		/* Mbox command <mbxCommand> cannot issue */
7073 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7074 				"(%d):0311 Mailbox command x%x cannot "
7075 				"issue Data: x%x x%x\n",
7076 				pmbox->vport ? pmbox->vport->vpi : 0,
7077 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
7078 		goto out_not_finished;
7079 	}
7080 
7081 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
7082 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
7083 			!(hc_copy & HC_MBINT_ENA)) {
7084 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7085 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7086 				"(%d):2528 Mailbox command x%x cannot "
7087 				"issue Data: x%x x%x\n",
7088 				pmbox->vport ? pmbox->vport->vpi : 0,
7089 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
7090 			goto out_not_finished;
7091 		}
7092 	}
7093 
7094 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
7095 		/* Polling for a mbox command when another one is already active
7096 		 * is not allowed in SLI. Also, the driver must have established
7097 		 * SLI2 mode to queue and process multiple mbox commands.
7098 		 */
7099 
7100 		if (flag & MBX_POLL) {
7101 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7102 
7103 			/* Mbox command <mbxCommand> cannot issue */
7104 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7105 					"(%d):2529 Mailbox command x%x "
7106 					"cannot issue Data: x%x x%x\n",
7107 					pmbox->vport ? pmbox->vport->vpi : 0,
7108 					pmbox->u.mb.mbxCommand,
7109 					psli->sli_flag, flag);
7110 			goto out_not_finished;
7111 		}
7112 
7113 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
7114 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7115 			/* Mbox command <mbxCommand> cannot issue */
7116 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7117 					"(%d):2530 Mailbox command x%x "
7118 					"cannot issue Data: x%x x%x\n",
7119 					pmbox->vport ? pmbox->vport->vpi : 0,
7120 					pmbox->u.mb.mbxCommand,
7121 					psli->sli_flag, flag);
7122 			goto out_not_finished;
7123 		}
7124 
7125 		/* Another mailbox command is still being processed, queue this
7126 		 * command to be processed later.
7127 		 */
7128 		lpfc_mbox_put(phba, pmbox);
7129 
7130 		/* Mbox cmd issue - BUSY */
7131 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7132 				"(%d):0308 Mbox cmd issue - BUSY Data: "
7133 				"x%x x%x x%x x%x\n",
7134 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
7135 				mbx->mbxCommand, phba->pport->port_state,
7136 				psli->sli_flag, flag);
7137 
7138 		psli->slistat.mbox_busy++;
7139 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7140 
7141 		if (pmbox->vport) {
7142 			lpfc_debugfs_disc_trc(pmbox->vport,
7143 				LPFC_DISC_TRC_MBOX_VPORT,
7144 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
7145 				(uint32_t)mbx->mbxCommand,
7146 				mbx->un.varWords[0], mbx->un.varWords[1]);
7147 		}
7148 		else {
7149 			lpfc_debugfs_disc_trc(phba->pport,
7150 				LPFC_DISC_TRC_MBOX,
7151 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
7152 				(uint32_t)mbx->mbxCommand,
7153 				mbx->un.varWords[0], mbx->un.varWords[1]);
7154 		}
7155 
7156 		return MBX_BUSY;
7157 	}
7158 
7159 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
7160 
7161 	/* If we are not polling, we MUST be in SLI2 mode */
7162 	if (flag != MBX_POLL) {
7163 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
7164 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
7165 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7166 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7167 			/* Mbox command <mbxCommand> cannot issue */
7168 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7169 					"(%d):2531 Mailbox command x%x "
7170 					"cannot issue Data: x%x x%x\n",
7171 					pmbox->vport ? pmbox->vport->vpi : 0,
7172 					pmbox->u.mb.mbxCommand,
7173 					psli->sli_flag, flag);
7174 			goto out_not_finished;
7175 		}
7176 		/* timeout active mbox command */
7177 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
7178 					   1000);
7179 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
7180 	}
7181 
7182 	/* Mailbox cmd <cmd> issue */
7183 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7184 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
7185 			"x%x\n",
7186 			pmbox->vport ? pmbox->vport->vpi : 0,
7187 			mbx->mbxCommand, phba->pport->port_state,
7188 			psli->sli_flag, flag);
7189 
7190 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
7191 		if (pmbox->vport) {
7192 			lpfc_debugfs_disc_trc(pmbox->vport,
7193 				LPFC_DISC_TRC_MBOX_VPORT,
7194 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
7195 				(uint32_t)mbx->mbxCommand,
7196 				mbx->un.varWords[0], mbx->un.varWords[1]);
7197 		}
7198 		else {
7199 			lpfc_debugfs_disc_trc(phba->pport,
7200 				LPFC_DISC_TRC_MBOX,
7201 				"MBOX Send:       cmd:x%x mb:x%x x%x",
7202 				(uint32_t)mbx->mbxCommand,
7203 				mbx->un.varWords[0], mbx->un.varWords[1]);
7204 		}
7205 	}
7206 
7207 	psli->slistat.mbox_cmd++;
7208 	evtctr = psli->slistat.mbox_event;
7209 
7210 	/* next set own bit for the adapter and copy over command word */
7211 	mbx->mbxOwner = OWN_CHIP;
7212 
7213 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7214 		/* Populate mbox extension offset word. */
7215 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
7216 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
7217 				= (uint8_t *)phba->mbox_ext
7218 				  - (uint8_t *)phba->mbox;
7219 		}
7220 
7221 		/* Copy the mailbox extension data */
7222 		if (pmbox->in_ext_byte_len && pmbox->context2) {
7223 			lpfc_sli_pcimem_bcopy(pmbox->context2,
7224 				(uint8_t *)phba->mbox_ext,
7225 				pmbox->in_ext_byte_len);
7226 		}
7227 		/* Copy command data to host SLIM area */
7228 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
7229 	} else {
7230 		/* Populate mbox extension offset word. */
7231 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
7232 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
7233 				= MAILBOX_HBA_EXT_OFFSET;
7234 
7235 		/* Copy the mailbox extension data */
7236 		if (pmbox->in_ext_byte_len && pmbox->context2) {
7237 			lpfc_memcpy_to_slim(phba->MBslimaddr +
7238 				MAILBOX_HBA_EXT_OFFSET,
7239 				pmbox->context2, pmbox->in_ext_byte_len);
7240 
7241 		}
7242 		if (mbx->mbxCommand == MBX_CONFIG_PORT) {
7243 			/* copy command data into host mbox for cmpl */
7244 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
7245 		}
7246 
7247 		/* First copy mbox command data to HBA SLIM, skip past first
7248 		   word */
7249 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
7250 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
7251 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
7252 
7253 		/* Next copy over first word, with mbxOwner set */
7254 		ldata = *((uint32_t *)mbx);
7255 		to_slim = phba->MBslimaddr;
7256 		writel(ldata, to_slim);
7257 		readl(to_slim); /* flush */
7258 
7259 		if (mbx->mbxCommand == MBX_CONFIG_PORT) {
7260 			/* switch over to host mailbox */
7261 			psli->sli_flag |= LPFC_SLI_ACTIVE;
7262 		}
7263 	}
7264 
7265 	wmb();
7266 
7267 	switch (flag) {
7268 	case MBX_NOWAIT:
7269 		/* Set up reference to mailbox command */
7270 		psli->mbox_active = pmbox;
7271 		/* Interrupt board to do it */
7272 		writel(CA_MBATT, phba->CAregaddr);
7273 		readl(phba->CAregaddr); /* flush */
7274 		/* Don't wait for it to finish, just return */
7275 		break;
7276 
7277 	case MBX_POLL:
7278 		/* Set up null reference to mailbox command */
7279 		psli->mbox_active = NULL;
7280 		/* Interrupt board to do it */
7281 		writel(CA_MBATT, phba->CAregaddr);
7282 		readl(phba->CAregaddr); /* flush */
7283 
7284 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7285 			/* First read mbox status word */
7286 			word0 = *((uint32_t *)phba->mbox);
7287 			word0 = le32_to_cpu(word0);
7288 		} else {
7289 			/* First read mbox status word */
7290 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
7291 				spin_unlock_irqrestore(&phba->hbalock,
7292 						       drvr_flag);
7293 				goto out_not_finished;
7294 			}
7295 		}
7296 
7297 		/* Read the HBA Host Attention Register */
7298 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
7299 			spin_unlock_irqrestore(&phba->hbalock,
7300 						       drvr_flag);
7301 			goto out_not_finished;
7302 		}
7303 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
7304 							1000) + jiffies;
7305 		i = 0;
7306 		/* Wait for command to complete */
7307 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
7308 		       (!(ha_copy & HA_MBATT) &&
7309 			(phba->link_state > LPFC_WARM_START))) {
7310 			if (time_after(jiffies, timeout)) {
7311 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7312 				spin_unlock_irqrestore(&phba->hbalock,
7313 						       drvr_flag);
7314 				goto out_not_finished;
7315 			}
7316 
7317 			/* Check if we took a mbox interrupt while we were
7318 			   polling */
7319 			if (((word0 & OWN_CHIP) != OWN_CHIP)
7320 			    && (evtctr != psli->slistat.mbox_event))
7321 				break;
7322 
7323 			if (i++ > 10) {
7324 				spin_unlock_irqrestore(&phba->hbalock,
7325 						       drvr_flag);
7326 				msleep(1);
7327 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
7328 			}
7329 
7330 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7331 				/* First copy command data */
7332 				word0 = *((uint32_t *)phba->mbox);
7333 				word0 = le32_to_cpu(word0);
7334 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
7335 					MAILBOX_t *slimmb;
7336 					uint32_t slimword0;
7337 					/* Check real SLIM for any errors */
7338 					slimword0 = readl(phba->MBslimaddr);
7339 					slimmb = (MAILBOX_t *) & slimword0;
7340 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
7341 					    && slimmb->mbxStatus) {
7342 						psli->sli_flag &=
7343 						    ~LPFC_SLI_ACTIVE;
7344 						word0 = slimword0;
7345 					}
7346 				}
7347 			} else {
7348 				/* First copy command data */
7349 				word0 = readl(phba->MBslimaddr);
7350 			}
7351 			/* Read the HBA Host Attention Register */
7352 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
7353 				spin_unlock_irqrestore(&phba->hbalock,
7354 						       drvr_flag);
7355 				goto out_not_finished;
7356 			}
7357 		}
7358 
7359 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7360 			/* copy results back to user */
7361 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx, MAILBOX_CMD_SIZE);
7362 			/* Copy the mailbox extension data */
7363 			if (pmbox->out_ext_byte_len && pmbox->context2) {
7364 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
7365 						      pmbox->context2,
7366 						      pmbox->out_ext_byte_len);
7367 			}
7368 		} else {
7369 			/* First copy command data */
7370 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
7371 							MAILBOX_CMD_SIZE);
7372 			/* Copy the mailbox extension data */
7373 			if (pmbox->out_ext_byte_len && pmbox->context2) {
7374 				lpfc_memcpy_from_slim(pmbox->context2,
7375 					phba->MBslimaddr +
7376 					MAILBOX_HBA_EXT_OFFSET,
7377 					pmbox->out_ext_byte_len);
7378 			}
7379 		}
7380 
7381 		writel(HA_MBATT, phba->HAregaddr);
7382 		readl(phba->HAregaddr); /* flush */
7383 
7384 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7385 		status = mbx->mbxStatus;
7386 	}
7387 
7388 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
7389 	return status;
7390 
7391 out_not_finished:
7392 	if (processing_queue) {
7393 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
7394 		lpfc_mbox_cmpl_put(phba, pmbox);
7395 	}
7396 	return MBX_NOT_FINISHED;
7397 }
7398 
7399 /**
7400  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
7401  * @phba: Pointer to HBA context object.
7402  *
7403  * The function blocks the posting of SLI4 asynchronous mailbox commands from
7404  * the driver internal pending mailbox queue. It will then try to wait out the
7405  * possible outstanding mailbox command before return.
7406  *
7407  * Returns:
7408  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
7409  * 	the outstanding mailbox command timed out.
7410  **/
7411 static int
7412 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
7413 {
7414 	struct lpfc_sli *psli = &phba->sli;
7415 	int rc = 0;
7416 	unsigned long timeout = 0;
7417 
7418 	/* Mark the asynchronous mailbox command posting as blocked */
7419 	spin_lock_irq(&phba->hbalock);
7420 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
7421 	/* Determine how long we might wait for the active mailbox
7422 	 * command to be gracefully completed by firmware.
7423 	 */
7424 	if (phba->sli.mbox_active)
7425 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
7426 						phba->sli.mbox_active) *
7427 						1000) + jiffies;
7428 	spin_unlock_irq(&phba->hbalock);
7429 
7430 	/* Make sure the mailbox is really active */
7431 	if (timeout)
7432 		lpfc_sli4_process_missed_mbox_completions(phba);
7433 
7434 	/* Wait for the outstnading mailbox command to complete */
7435 	while (phba->sli.mbox_active) {
7436 		/* Check active mailbox complete status every 2ms */
7437 		msleep(2);
7438 		if (time_after(jiffies, timeout)) {
7439 			/* Timeout, marked the outstanding cmd not complete */
7440 			rc = 1;
7441 			break;
7442 		}
7443 	}
7444 
7445 	/* Can not cleanly block async mailbox command, fails it */
7446 	if (rc) {
7447 		spin_lock_irq(&phba->hbalock);
7448 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7449 		spin_unlock_irq(&phba->hbalock);
7450 	}
7451 	return rc;
7452 }
7453 
7454 /**
7455  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
7456  * @phba: Pointer to HBA context object.
7457  *
7458  * The function unblocks and resume posting of SLI4 asynchronous mailbox
7459  * commands from the driver internal pending mailbox queue. It makes sure
7460  * that there is no outstanding mailbox command before resuming posting
7461  * asynchronous mailbox commands. If, for any reason, there is outstanding
7462  * mailbox command, it will try to wait it out before resuming asynchronous
7463  * mailbox command posting.
7464  **/
7465 static void
7466 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
7467 {
7468 	struct lpfc_sli *psli = &phba->sli;
7469 
7470 	spin_lock_irq(&phba->hbalock);
7471 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
7472 		/* Asynchronous mailbox posting is not blocked, do nothing */
7473 		spin_unlock_irq(&phba->hbalock);
7474 		return;
7475 	}
7476 
7477 	/* Outstanding synchronous mailbox command is guaranteed to be done,
7478 	 * successful or timeout, after timing-out the outstanding mailbox
7479 	 * command shall always be removed, so just unblock posting async
7480 	 * mailbox command and resume
7481 	 */
7482 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7483 	spin_unlock_irq(&phba->hbalock);
7484 
7485 	/* wake up worker thread to post asynchronlous mailbox command */
7486 	lpfc_worker_wake_up(phba);
7487 }
7488 
7489 /**
7490  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
7491  * @phba: Pointer to HBA context object.
7492  * @mboxq: Pointer to mailbox object.
7493  *
7494  * The function waits for the bootstrap mailbox register ready bit from
7495  * port for twice the regular mailbox command timeout value.
7496  *
7497  *      0 - no timeout on waiting for bootstrap mailbox register ready.
7498  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
7499  **/
7500 static int
7501 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
7502 {
7503 	uint32_t db_ready;
7504 	unsigned long timeout;
7505 	struct lpfc_register bmbx_reg;
7506 
7507 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
7508 				   * 1000) + jiffies;
7509 
7510 	do {
7511 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
7512 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
7513 		if (!db_ready)
7514 			msleep(2);
7515 
7516 		if (time_after(jiffies, timeout))
7517 			return MBXERR_ERROR;
7518 	} while (!db_ready);
7519 
7520 	return 0;
7521 }
7522 
7523 /**
7524  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
7525  * @phba: Pointer to HBA context object.
7526  * @mboxq: Pointer to mailbox object.
7527  *
7528  * The function posts a mailbox to the port.  The mailbox is expected
7529  * to be comletely filled in and ready for the port to operate on it.
7530  * This routine executes a synchronous completion operation on the
7531  * mailbox by polling for its completion.
7532  *
7533  * The caller must not be holding any locks when calling this routine.
7534  *
7535  * Returns:
7536  *	MBX_SUCCESS - mailbox posted successfully
7537  *	Any of the MBX error values.
7538  **/
7539 static int
7540 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
7541 {
7542 	int rc = MBX_SUCCESS;
7543 	unsigned long iflag;
7544 	uint32_t mcqe_status;
7545 	uint32_t mbx_cmnd;
7546 	struct lpfc_sli *psli = &phba->sli;
7547 	struct lpfc_mqe *mb = &mboxq->u.mqe;
7548 	struct lpfc_bmbx_create *mbox_rgn;
7549 	struct dma_address *dma_address;
7550 
7551 	/*
7552 	 * Only one mailbox can be active to the bootstrap mailbox region
7553 	 * at a time and there is no queueing provided.
7554 	 */
7555 	spin_lock_irqsave(&phba->hbalock, iflag);
7556 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
7557 		spin_unlock_irqrestore(&phba->hbalock, iflag);
7558 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7559 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
7560 				"cannot issue Data: x%x x%x\n",
7561 				mboxq->vport ? mboxq->vport->vpi : 0,
7562 				mboxq->u.mb.mbxCommand,
7563 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7564 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7565 				psli->sli_flag, MBX_POLL);
7566 		return MBXERR_ERROR;
7567 	}
7568 	/* The server grabs the token and owns it until release */
7569 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
7570 	phba->sli.mbox_active = mboxq;
7571 	spin_unlock_irqrestore(&phba->hbalock, iflag);
7572 
7573 	/* wait for bootstrap mbox register for readyness */
7574 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7575 	if (rc)
7576 		goto exit;
7577 
7578 	/*
7579 	 * Initialize the bootstrap memory region to avoid stale data areas
7580 	 * in the mailbox post.  Then copy the caller's mailbox contents to
7581 	 * the bmbx mailbox region.
7582 	 */
7583 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
7584 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
7585 	lpfc_sli_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
7586 			      sizeof(struct lpfc_mqe));
7587 
7588 	/* Post the high mailbox dma address to the port and wait for ready. */
7589 	dma_address = &phba->sli4_hba.bmbx.dma_address;
7590 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
7591 
7592 	/* wait for bootstrap mbox register for hi-address write done */
7593 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7594 	if (rc)
7595 		goto exit;
7596 
7597 	/* Post the low mailbox dma address to the port. */
7598 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
7599 
7600 	/* wait for bootstrap mbox register for low address write done */
7601 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
7602 	if (rc)
7603 		goto exit;
7604 
7605 	/*
7606 	 * Read the CQ to ensure the mailbox has completed.
7607 	 * If so, update the mailbox status so that the upper layers
7608 	 * can complete the request normally.
7609 	 */
7610 	lpfc_sli_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
7611 			      sizeof(struct lpfc_mqe));
7612 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
7613 	lpfc_sli_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
7614 			      sizeof(struct lpfc_mcqe));
7615 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
7616 	/*
7617 	 * When the CQE status indicates a failure and the mailbox status
7618 	 * indicates success then copy the CQE status into the mailbox status
7619 	 * (and prefix it with x4000).
7620 	 */
7621 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
7622 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
7623 			bf_set(lpfc_mqe_status, mb,
7624 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
7625 		rc = MBXERR_ERROR;
7626 	} else
7627 		lpfc_sli4_swap_str(phba, mboxq);
7628 
7629 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7630 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
7631 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
7632 			" x%x x%x CQ: x%x x%x x%x x%x\n",
7633 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
7634 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7635 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7636 			bf_get(lpfc_mqe_status, mb),
7637 			mb->un.mb_words[0], mb->un.mb_words[1],
7638 			mb->un.mb_words[2], mb->un.mb_words[3],
7639 			mb->un.mb_words[4], mb->un.mb_words[5],
7640 			mb->un.mb_words[6], mb->un.mb_words[7],
7641 			mb->un.mb_words[8], mb->un.mb_words[9],
7642 			mb->un.mb_words[10], mb->un.mb_words[11],
7643 			mb->un.mb_words[12], mboxq->mcqe.word0,
7644 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
7645 			mboxq->mcqe.trailer);
7646 exit:
7647 	/* We are holding the token, no needed for lock when release */
7648 	spin_lock_irqsave(&phba->hbalock, iflag);
7649 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7650 	phba->sli.mbox_active = NULL;
7651 	spin_unlock_irqrestore(&phba->hbalock, iflag);
7652 	return rc;
7653 }
7654 
7655 /**
7656  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
7657  * @phba: Pointer to HBA context object.
7658  * @pmbox: Pointer to mailbox object.
7659  * @flag: Flag indicating how the mailbox need to be processed.
7660  *
7661  * This function is called by discovery code and HBA management code to submit
7662  * a mailbox command to firmware with SLI-4 interface spec.
7663  *
7664  * Return codes the caller owns the mailbox command after the return of the
7665  * function.
7666  **/
7667 static int
7668 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
7669 		       uint32_t flag)
7670 {
7671 	struct lpfc_sli *psli = &phba->sli;
7672 	unsigned long iflags;
7673 	int rc;
7674 
7675 	/* dump from issue mailbox command if setup */
7676 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
7677 
7678 	rc = lpfc_mbox_dev_check(phba);
7679 	if (unlikely(rc)) {
7680 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7681 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
7682 				"cannot issue Data: x%x x%x\n",
7683 				mboxq->vport ? mboxq->vport->vpi : 0,
7684 				mboxq->u.mb.mbxCommand,
7685 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7686 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7687 				psli->sli_flag, flag);
7688 		goto out_not_finished;
7689 	}
7690 
7691 	/* Detect polling mode and jump to a handler */
7692 	if (!phba->sli4_hba.intr_enable) {
7693 		if (flag == MBX_POLL)
7694 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
7695 		else
7696 			rc = -EIO;
7697 		if (rc != MBX_SUCCESS)
7698 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7699 					"(%d):2541 Mailbox command x%x "
7700 					"(x%x/x%x) failure: "
7701 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
7702 					"Data: x%x x%x\n,",
7703 					mboxq->vport ? mboxq->vport->vpi : 0,
7704 					mboxq->u.mb.mbxCommand,
7705 					lpfc_sli_config_mbox_subsys_get(phba,
7706 									mboxq),
7707 					lpfc_sli_config_mbox_opcode_get(phba,
7708 									mboxq),
7709 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
7710 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
7711 					bf_get(lpfc_mcqe_ext_status,
7712 					       &mboxq->mcqe),
7713 					psli->sli_flag, flag);
7714 		return rc;
7715 	} else if (flag == MBX_POLL) {
7716 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7717 				"(%d):2542 Try to issue mailbox command "
7718 				"x%x (x%x/x%x) synchronously ahead of async"
7719 				"mailbox command queue: x%x x%x\n",
7720 				mboxq->vport ? mboxq->vport->vpi : 0,
7721 				mboxq->u.mb.mbxCommand,
7722 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7723 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7724 				psli->sli_flag, flag);
7725 		/* Try to block the asynchronous mailbox posting */
7726 		rc = lpfc_sli4_async_mbox_block(phba);
7727 		if (!rc) {
7728 			/* Successfully blocked, now issue sync mbox cmd */
7729 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
7730 			if (rc != MBX_SUCCESS)
7731 				lpfc_printf_log(phba, KERN_WARNING,
7732 					LOG_MBOX | LOG_SLI,
7733 					"(%d):2597 Sync Mailbox command "
7734 					"x%x (x%x/x%x) failure: "
7735 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
7736 					"Data: x%x x%x\n,",
7737 					mboxq->vport ? mboxq->vport->vpi : 0,
7738 					mboxq->u.mb.mbxCommand,
7739 					lpfc_sli_config_mbox_subsys_get(phba,
7740 									mboxq),
7741 					lpfc_sli_config_mbox_opcode_get(phba,
7742 									mboxq),
7743 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
7744 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
7745 					bf_get(lpfc_mcqe_ext_status,
7746 					       &mboxq->mcqe),
7747 					psli->sli_flag, flag);
7748 			/* Unblock the async mailbox posting afterward */
7749 			lpfc_sli4_async_mbox_unblock(phba);
7750 		}
7751 		return rc;
7752 	}
7753 
7754 	/* Now, interrupt mode asynchrous mailbox command */
7755 	rc = lpfc_mbox_cmd_check(phba, mboxq);
7756 	if (rc) {
7757 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7758 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
7759 				"cannot issue Data: x%x x%x\n",
7760 				mboxq->vport ? mboxq->vport->vpi : 0,
7761 				mboxq->u.mb.mbxCommand,
7762 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7763 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7764 				psli->sli_flag, flag);
7765 		goto out_not_finished;
7766 	}
7767 
7768 	/* Put the mailbox command to the driver internal FIFO */
7769 	psli->slistat.mbox_busy++;
7770 	spin_lock_irqsave(&phba->hbalock, iflags);
7771 	lpfc_mbox_put(phba, mboxq);
7772 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7773 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7774 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
7775 			"x%x (x%x/x%x) x%x x%x x%x\n",
7776 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
7777 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7778 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7779 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7780 			phba->pport->port_state,
7781 			psli->sli_flag, MBX_NOWAIT);
7782 	/* Wake up worker thread to transport mailbox command from head */
7783 	lpfc_worker_wake_up(phba);
7784 
7785 	return MBX_BUSY;
7786 
7787 out_not_finished:
7788 	return MBX_NOT_FINISHED;
7789 }
7790 
7791 /**
7792  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
7793  * @phba: Pointer to HBA context object.
7794  *
7795  * This function is called by worker thread to send a mailbox command to
7796  * SLI4 HBA firmware.
7797  *
7798  **/
7799 int
7800 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
7801 {
7802 	struct lpfc_sli *psli = &phba->sli;
7803 	LPFC_MBOXQ_t *mboxq;
7804 	int rc = MBX_SUCCESS;
7805 	unsigned long iflags;
7806 	struct lpfc_mqe *mqe;
7807 	uint32_t mbx_cmnd;
7808 
7809 	/* Check interrupt mode before post async mailbox command */
7810 	if (unlikely(!phba->sli4_hba.intr_enable))
7811 		return MBX_NOT_FINISHED;
7812 
7813 	/* Check for mailbox command service token */
7814 	spin_lock_irqsave(&phba->hbalock, iflags);
7815 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
7816 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7817 		return MBX_NOT_FINISHED;
7818 	}
7819 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
7820 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7821 		return MBX_NOT_FINISHED;
7822 	}
7823 	if (unlikely(phba->sli.mbox_active)) {
7824 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7825 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7826 				"0384 There is pending active mailbox cmd\n");
7827 		return MBX_NOT_FINISHED;
7828 	}
7829 	/* Take the mailbox command service token */
7830 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
7831 
7832 	/* Get the next mailbox command from head of queue */
7833 	mboxq = lpfc_mbox_get(phba);
7834 
7835 	/* If no more mailbox command waiting for post, we're done */
7836 	if (!mboxq) {
7837 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7838 		spin_unlock_irqrestore(&phba->hbalock, iflags);
7839 		return MBX_SUCCESS;
7840 	}
7841 	phba->sli.mbox_active = mboxq;
7842 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7843 
7844 	/* Check device readiness for posting mailbox command */
7845 	rc = lpfc_mbox_dev_check(phba);
7846 	if (unlikely(rc))
7847 		/* Driver clean routine will clean up pending mailbox */
7848 		goto out_not_finished;
7849 
7850 	/* Prepare the mbox command to be posted */
7851 	mqe = &mboxq->u.mqe;
7852 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
7853 
7854 	/* Start timer for the mbox_tmo and log some mailbox post messages */
7855 	mod_timer(&psli->mbox_tmo, (jiffies +
7856 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
7857 
7858 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7859 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
7860 			"x%x x%x\n",
7861 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
7862 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7863 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7864 			phba->pport->port_state, psli->sli_flag);
7865 
7866 	if (mbx_cmnd != MBX_HEARTBEAT) {
7867 		if (mboxq->vport) {
7868 			lpfc_debugfs_disc_trc(mboxq->vport,
7869 				LPFC_DISC_TRC_MBOX_VPORT,
7870 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
7871 				mbx_cmnd, mqe->un.mb_words[0],
7872 				mqe->un.mb_words[1]);
7873 		} else {
7874 			lpfc_debugfs_disc_trc(phba->pport,
7875 				LPFC_DISC_TRC_MBOX,
7876 				"MBOX Send: cmd:x%x mb:x%x x%x",
7877 				mbx_cmnd, mqe->un.mb_words[0],
7878 				mqe->un.mb_words[1]);
7879 		}
7880 	}
7881 	psli->slistat.mbox_cmd++;
7882 
7883 	/* Post the mailbox command to the port */
7884 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
7885 	if (rc != MBX_SUCCESS) {
7886 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7887 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
7888 				"cannot issue Data: x%x x%x\n",
7889 				mboxq->vport ? mboxq->vport->vpi : 0,
7890 				mboxq->u.mb.mbxCommand,
7891 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
7892 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
7893 				psli->sli_flag, MBX_NOWAIT);
7894 		goto out_not_finished;
7895 	}
7896 
7897 	return rc;
7898 
7899 out_not_finished:
7900 	spin_lock_irqsave(&phba->hbalock, iflags);
7901 	if (phba->sli.mbox_active) {
7902 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
7903 		__lpfc_mbox_cmpl_put(phba, mboxq);
7904 		/* Release the token */
7905 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
7906 		phba->sli.mbox_active = NULL;
7907 	}
7908 	spin_unlock_irqrestore(&phba->hbalock, iflags);
7909 
7910 	return MBX_NOT_FINISHED;
7911 }
7912 
7913 /**
7914  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
7915  * @phba: Pointer to HBA context object.
7916  * @pmbox: Pointer to mailbox object.
7917  * @flag: Flag indicating how the mailbox need to be processed.
7918  *
7919  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
7920  * the API jump table function pointer from the lpfc_hba struct.
7921  *
7922  * Return codes the caller owns the mailbox command after the return of the
7923  * function.
7924  **/
7925 int
7926 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
7927 {
7928 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
7929 }
7930 
7931 /**
7932  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
7933  * @phba: The hba struct for which this call is being executed.
7934  * @dev_grp: The HBA PCI-Device group number.
7935  *
7936  * This routine sets up the mbox interface API function jump table in @phba
7937  * struct.
7938  * Returns: 0 - success, -ENODEV - failure.
7939  **/
7940 int
7941 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
7942 {
7943 
7944 	switch (dev_grp) {
7945 	case LPFC_PCI_DEV_LP:
7946 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
7947 		phba->lpfc_sli_handle_slow_ring_event =
7948 				lpfc_sli_handle_slow_ring_event_s3;
7949 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
7950 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
7951 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
7952 		break;
7953 	case LPFC_PCI_DEV_OC:
7954 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
7955 		phba->lpfc_sli_handle_slow_ring_event =
7956 				lpfc_sli_handle_slow_ring_event_s4;
7957 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
7958 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
7959 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
7960 		break;
7961 	default:
7962 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7963 				"1420 Invalid HBA PCI-device group: 0x%x\n",
7964 				dev_grp);
7965 		return -ENODEV;
7966 		break;
7967 	}
7968 	return 0;
7969 }
7970 
7971 /**
7972  * __lpfc_sli_ringtx_put - Add an iocb to the txq
7973  * @phba: Pointer to HBA context object.
7974  * @pring: Pointer to driver SLI ring object.
7975  * @piocb: Pointer to address of newly added command iocb.
7976  *
7977  * This function is called with hbalock held to add a command
7978  * iocb to the txq when SLI layer cannot submit the command iocb
7979  * to the ring.
7980  **/
7981 void
7982 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
7983 		    struct lpfc_iocbq *piocb)
7984 {
7985 	lockdep_assert_held(&phba->hbalock);
7986 	/* Insert the caller's iocb in the txq tail for later processing. */
7987 	list_add_tail(&piocb->list, &pring->txq);
7988 }
7989 
7990 /**
7991  * lpfc_sli_next_iocb - Get the next iocb in the txq
7992  * @phba: Pointer to HBA context object.
7993  * @pring: Pointer to driver SLI ring object.
7994  * @piocb: Pointer to address of newly added command iocb.
7995  *
7996  * This function is called with hbalock held before a new
7997  * iocb is submitted to the firmware. This function checks
7998  * txq to flush the iocbs in txq to Firmware before
7999  * submitting new iocbs to the Firmware.
8000  * If there are iocbs in the txq which need to be submitted
8001  * to firmware, lpfc_sli_next_iocb returns the first element
8002  * of the txq after dequeuing it from txq.
8003  * If there is no iocb in the txq then the function will return
8004  * *piocb and *piocb is set to NULL. Caller needs to check
8005  * *piocb to find if there are more commands in the txq.
8006  **/
8007 static struct lpfc_iocbq *
8008 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
8009 		   struct lpfc_iocbq **piocb)
8010 {
8011 	struct lpfc_iocbq * nextiocb;
8012 
8013 	lockdep_assert_held(&phba->hbalock);
8014 
8015 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
8016 	if (!nextiocb) {
8017 		nextiocb = *piocb;
8018 		*piocb = NULL;
8019 	}
8020 
8021 	return nextiocb;
8022 }
8023 
8024 /**
8025  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
8026  * @phba: Pointer to HBA context object.
8027  * @ring_number: SLI ring number to issue iocb on.
8028  * @piocb: Pointer to command iocb.
8029  * @flag: Flag indicating if this command can be put into txq.
8030  *
8031  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
8032  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
8033  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
8034  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
8035  * this function allows only iocbs for posting buffers. This function finds
8036  * next available slot in the command ring and posts the command to the
8037  * available slot and writes the port attention register to request HBA start
8038  * processing new iocb. If there is no slot available in the ring and
8039  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
8040  * the function returns IOCB_BUSY.
8041  *
8042  * This function is called with hbalock held. The function will return success
8043  * after it successfully submit the iocb to firmware or after adding to the
8044  * txq.
8045  **/
8046 static int
8047 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
8048 		    struct lpfc_iocbq *piocb, uint32_t flag)
8049 {
8050 	struct lpfc_iocbq *nextiocb;
8051 	IOCB_t *iocb;
8052 	struct lpfc_sli_ring *pring = &phba->sli.ring[ring_number];
8053 
8054 	lockdep_assert_held(&phba->hbalock);
8055 
8056 	if (piocb->iocb_cmpl && (!piocb->vport) &&
8057 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
8058 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
8059 		lpfc_printf_log(phba, KERN_ERR,
8060 				LOG_SLI | LOG_VPORT,
8061 				"1807 IOCB x%x failed. No vport\n",
8062 				piocb->iocb.ulpCommand);
8063 		dump_stack();
8064 		return IOCB_ERROR;
8065 	}
8066 
8067 
8068 	/* If the PCI channel is in offline state, do not post iocbs. */
8069 	if (unlikely(pci_channel_offline(phba->pcidev)))
8070 		return IOCB_ERROR;
8071 
8072 	/* If HBA has a deferred error attention, fail the iocb. */
8073 	if (unlikely(phba->hba_flag & DEFER_ERATT))
8074 		return IOCB_ERROR;
8075 
8076 	/*
8077 	 * We should never get an IOCB if we are in a < LINK_DOWN state
8078 	 */
8079 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
8080 		return IOCB_ERROR;
8081 
8082 	/*
8083 	 * Check to see if we are blocking IOCB processing because of a
8084 	 * outstanding event.
8085 	 */
8086 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
8087 		goto iocb_busy;
8088 
8089 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
8090 		/*
8091 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
8092 		 * can be issued if the link is not up.
8093 		 */
8094 		switch (piocb->iocb.ulpCommand) {
8095 		case CMD_GEN_REQUEST64_CR:
8096 		case CMD_GEN_REQUEST64_CX:
8097 			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
8098 				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
8099 					FC_RCTL_DD_UNSOL_CMD) ||
8100 				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
8101 					MENLO_TRANSPORT_TYPE))
8102 
8103 				goto iocb_busy;
8104 			break;
8105 		case CMD_QUE_RING_BUF_CN:
8106 		case CMD_QUE_RING_BUF64_CN:
8107 			/*
8108 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
8109 			 * completion, iocb_cmpl MUST be 0.
8110 			 */
8111 			if (piocb->iocb_cmpl)
8112 				piocb->iocb_cmpl = NULL;
8113 			/*FALLTHROUGH*/
8114 		case CMD_CREATE_XRI_CR:
8115 		case CMD_CLOSE_XRI_CN:
8116 		case CMD_CLOSE_XRI_CX:
8117 			break;
8118 		default:
8119 			goto iocb_busy;
8120 		}
8121 
8122 	/*
8123 	 * For FCP commands, we must be in a state where we can process link
8124 	 * attention events.
8125 	 */
8126 	} else if (unlikely(pring->ringno == phba->sli.fcp_ring &&
8127 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
8128 		goto iocb_busy;
8129 	}
8130 
8131 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
8132 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
8133 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
8134 
8135 	if (iocb)
8136 		lpfc_sli_update_ring(phba, pring);
8137 	else
8138 		lpfc_sli_update_full_ring(phba, pring);
8139 
8140 	if (!piocb)
8141 		return IOCB_SUCCESS;
8142 
8143 	goto out_busy;
8144 
8145  iocb_busy:
8146 	pring->stats.iocb_cmd_delay++;
8147 
8148  out_busy:
8149 
8150 	if (!(flag & SLI_IOCB_RET_IOCB)) {
8151 		__lpfc_sli_ringtx_put(phba, pring, piocb);
8152 		return IOCB_SUCCESS;
8153 	}
8154 
8155 	return IOCB_BUSY;
8156 }
8157 
8158 /**
8159  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
8160  * @phba: Pointer to HBA context object.
8161  * @piocb: Pointer to command iocb.
8162  * @sglq: Pointer to the scatter gather queue object.
8163  *
8164  * This routine converts the bpl or bde that is in the IOCB
8165  * to a sgl list for the sli4 hardware. The physical address
8166  * of the bpl/bde is converted back to a virtual address.
8167  * If the IOCB contains a BPL then the list of BDE's is
8168  * converted to sli4_sge's. If the IOCB contains a single
8169  * BDE then it is converted to a single sli_sge.
8170  * The IOCB is still in cpu endianess so the contents of
8171  * the bpl can be used without byte swapping.
8172  *
8173  * Returns valid XRI = Success, NO_XRI = Failure.
8174 **/
8175 static uint16_t
8176 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
8177 		struct lpfc_sglq *sglq)
8178 {
8179 	uint16_t xritag = NO_XRI;
8180 	struct ulp_bde64 *bpl = NULL;
8181 	struct ulp_bde64 bde;
8182 	struct sli4_sge *sgl  = NULL;
8183 	struct lpfc_dmabuf *dmabuf;
8184 	IOCB_t *icmd;
8185 	int numBdes = 0;
8186 	int i = 0;
8187 	uint32_t offset = 0; /* accumulated offset in the sg request list */
8188 	int inbound = 0; /* number of sg reply entries inbound from firmware */
8189 
8190 	if (!piocbq || !sglq)
8191 		return xritag;
8192 
8193 	sgl  = (struct sli4_sge *)sglq->sgl;
8194 	icmd = &piocbq->iocb;
8195 	if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
8196 		return sglq->sli4_xritag;
8197 	if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
8198 		numBdes = icmd->un.genreq64.bdl.bdeSize /
8199 				sizeof(struct ulp_bde64);
8200 		/* The addrHigh and addrLow fields within the IOCB
8201 		 * have not been byteswapped yet so there is no
8202 		 * need to swap them back.
8203 		 */
8204 		if (piocbq->context3)
8205 			dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
8206 		else
8207 			return xritag;
8208 
8209 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
8210 		if (!bpl)
8211 			return xritag;
8212 
8213 		for (i = 0; i < numBdes; i++) {
8214 			/* Should already be byte swapped. */
8215 			sgl->addr_hi = bpl->addrHigh;
8216 			sgl->addr_lo = bpl->addrLow;
8217 
8218 			sgl->word2 = le32_to_cpu(sgl->word2);
8219 			if ((i+1) == numBdes)
8220 				bf_set(lpfc_sli4_sge_last, sgl, 1);
8221 			else
8222 				bf_set(lpfc_sli4_sge_last, sgl, 0);
8223 			/* swap the size field back to the cpu so we
8224 			 * can assign it to the sgl.
8225 			 */
8226 			bde.tus.w = le32_to_cpu(bpl->tus.w);
8227 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
8228 			/* The offsets in the sgl need to be accumulated
8229 			 * separately for the request and reply lists.
8230 			 * The request is always first, the reply follows.
8231 			 */
8232 			if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
8233 				/* add up the reply sg entries */
8234 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
8235 					inbound++;
8236 				/* first inbound? reset the offset */
8237 				if (inbound == 1)
8238 					offset = 0;
8239 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
8240 				bf_set(lpfc_sli4_sge_type, sgl,
8241 					LPFC_SGE_TYPE_DATA);
8242 				offset += bde.tus.f.bdeSize;
8243 			}
8244 			sgl->word2 = cpu_to_le32(sgl->word2);
8245 			bpl++;
8246 			sgl++;
8247 		}
8248 	} else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
8249 			/* The addrHigh and addrLow fields of the BDE have not
8250 			 * been byteswapped yet so they need to be swapped
8251 			 * before putting them in the sgl.
8252 			 */
8253 			sgl->addr_hi =
8254 				cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
8255 			sgl->addr_lo =
8256 				cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
8257 			sgl->word2 = le32_to_cpu(sgl->word2);
8258 			bf_set(lpfc_sli4_sge_last, sgl, 1);
8259 			sgl->word2 = cpu_to_le32(sgl->word2);
8260 			sgl->sge_len =
8261 				cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
8262 	}
8263 	return sglq->sli4_xritag;
8264 }
8265 
8266 /**
8267  * lpfc_sli_iocb2wqe - Convert the IOCB to a work queue entry.
8268  * @phba: Pointer to HBA context object.
8269  * @piocb: Pointer to command iocb.
8270  * @wqe: Pointer to the work queue entry.
8271  *
8272  * This routine converts the iocb command to its Work Queue Entry
8273  * equivalent. The wqe pointer should not have any fields set when
8274  * this routine is called because it will memcpy over them.
8275  * This routine does not set the CQ_ID or the WQEC bits in the
8276  * wqe.
8277  *
8278  * Returns: 0 = Success, IOCB_ERROR = Failure.
8279  **/
8280 static int
8281 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
8282 		union lpfc_wqe *wqe)
8283 {
8284 	uint32_t xmit_len = 0, total_len = 0;
8285 	uint8_t ct = 0;
8286 	uint32_t fip;
8287 	uint32_t abort_tag;
8288 	uint8_t command_type = ELS_COMMAND_NON_FIP;
8289 	uint8_t cmnd;
8290 	uint16_t xritag;
8291 	uint16_t abrt_iotag;
8292 	struct lpfc_iocbq *abrtiocbq;
8293 	struct ulp_bde64 *bpl = NULL;
8294 	uint32_t els_id = LPFC_ELS_ID_DEFAULT;
8295 	int numBdes, i;
8296 	struct ulp_bde64 bde;
8297 	struct lpfc_nodelist *ndlp;
8298 	uint32_t *pcmd;
8299 	uint32_t if_type;
8300 
8301 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
8302 	/* The fcp commands will set command type */
8303 	if (iocbq->iocb_flag &  LPFC_IO_FCP)
8304 		command_type = FCP_COMMAND;
8305 	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
8306 		command_type = ELS_COMMAND_FIP;
8307 	else
8308 		command_type = ELS_COMMAND_NON_FIP;
8309 
8310 	if (phba->fcp_embed_io)
8311 		memset(wqe, 0, sizeof(union lpfc_wqe128));
8312 	/* Some of the fields are in the right position already */
8313 	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
8314 	wqe->generic.wqe_com.word7 = 0; /* The ct field has moved so reset */
8315 	wqe->generic.wqe_com.word10 = 0;
8316 
8317 	abort_tag = (uint32_t) iocbq->iotag;
8318 	xritag = iocbq->sli4_xritag;
8319 	/* words0-2 bpl convert bde */
8320 	if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
8321 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
8322 				sizeof(struct ulp_bde64);
8323 		bpl  = (struct ulp_bde64 *)
8324 			((struct lpfc_dmabuf *)iocbq->context3)->virt;
8325 		if (!bpl)
8326 			return IOCB_ERROR;
8327 
8328 		/* Should already be byte swapped. */
8329 		wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
8330 		wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
8331 		/* swap the size field back to the cpu so we
8332 		 * can assign it to the sgl.
8333 		 */
8334 		wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
8335 		xmit_len = wqe->generic.bde.tus.f.bdeSize;
8336 		total_len = 0;
8337 		for (i = 0; i < numBdes; i++) {
8338 			bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
8339 			total_len += bde.tus.f.bdeSize;
8340 		}
8341 	} else
8342 		xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
8343 
8344 	iocbq->iocb.ulpIoTag = iocbq->iotag;
8345 	cmnd = iocbq->iocb.ulpCommand;
8346 
8347 	switch (iocbq->iocb.ulpCommand) {
8348 	case CMD_ELS_REQUEST64_CR:
8349 		if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
8350 			ndlp = iocbq->context_un.ndlp;
8351 		else
8352 			ndlp = (struct lpfc_nodelist *)iocbq->context1;
8353 		if (!iocbq->iocb.ulpLe) {
8354 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8355 				"2007 Only Limited Edition cmd Format"
8356 				" supported 0x%x\n",
8357 				iocbq->iocb.ulpCommand);
8358 			return IOCB_ERROR;
8359 		}
8360 
8361 		wqe->els_req.payload_len = xmit_len;
8362 		/* Els_reguest64 has a TMO */
8363 		bf_set(wqe_tmo, &wqe->els_req.wqe_com,
8364 			iocbq->iocb.ulpTimeout);
8365 		/* Need a VF for word 4 set the vf bit*/
8366 		bf_set(els_req64_vf, &wqe->els_req, 0);
8367 		/* And a VFID for word 12 */
8368 		bf_set(els_req64_vfid, &wqe->els_req, 0);
8369 		ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
8370 		bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8371 		       iocbq->iocb.ulpContext);
8372 		bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
8373 		bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
8374 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
8375 		if (command_type == ELS_COMMAND_FIP)
8376 			els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
8377 					>> LPFC_FIP_ELS_ID_SHIFT);
8378 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
8379 					iocbq->context2)->virt);
8380 		if_type = bf_get(lpfc_sli_intf_if_type,
8381 					&phba->sli4_hba.sli_intf);
8382 		if (if_type == LPFC_SLI_INTF_IF_TYPE_2) {
8383 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
8384 				*pcmd == ELS_CMD_SCR ||
8385 				*pcmd == ELS_CMD_FDISC ||
8386 				*pcmd == ELS_CMD_LOGO ||
8387 				*pcmd == ELS_CMD_PLOGI)) {
8388 				bf_set(els_req64_sp, &wqe->els_req, 1);
8389 				bf_set(els_req64_sid, &wqe->els_req,
8390 					iocbq->vport->fc_myDID);
8391 				if ((*pcmd == ELS_CMD_FLOGI) &&
8392 					!(phba->fc_topology ==
8393 						LPFC_TOPOLOGY_LOOP))
8394 					bf_set(els_req64_sid, &wqe->els_req, 0);
8395 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
8396 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8397 					phba->vpi_ids[iocbq->vport->vpi]);
8398 			} else if (pcmd && iocbq->context1) {
8399 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
8400 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
8401 					phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
8402 			}
8403 		}
8404 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
8405 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
8406 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
8407 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
8408 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
8409 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
8410 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
8411 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
8412 		wqe->els_req.max_response_payload_len = total_len - xmit_len;
8413 		break;
8414 	case CMD_XMIT_SEQUENCE64_CX:
8415 		bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
8416 		       iocbq->iocb.un.ulpWord[3]);
8417 		bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
8418 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
8419 		/* The entire sequence is transmitted for this IOCB */
8420 		xmit_len = total_len;
8421 		cmnd = CMD_XMIT_SEQUENCE64_CR;
8422 		if (phba->link_flag & LS_LOOPBACK_MODE)
8423 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
8424 	case CMD_XMIT_SEQUENCE64_CR:
8425 		/* word3 iocb=io_tag32 wqe=reserved */
8426 		wqe->xmit_sequence.rsvd3 = 0;
8427 		/* word4 relative_offset memcpy */
8428 		/* word5 r_ctl/df_ctl memcpy */
8429 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
8430 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
8431 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
8432 		       LPFC_WQE_IOD_WRITE);
8433 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
8434 		       LPFC_WQE_LENLOC_WORD12);
8435 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
8436 		wqe->xmit_sequence.xmit_len = xmit_len;
8437 		command_type = OTHER_COMMAND;
8438 		break;
8439 	case CMD_XMIT_BCAST64_CN:
8440 		/* word3 iocb=iotag32 wqe=seq_payload_len */
8441 		wqe->xmit_bcast64.seq_payload_len = xmit_len;
8442 		/* word4 iocb=rsvd wqe=rsvd */
8443 		/* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
8444 		/* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
8445 		bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
8446 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
8447 		bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
8448 		bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
8449 		bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
8450 		       LPFC_WQE_LENLOC_WORD3);
8451 		bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
8452 		break;
8453 	case CMD_FCP_IWRITE64_CR:
8454 		command_type = FCP_COMMAND_DATA_OUT;
8455 		/* word3 iocb=iotag wqe=payload_offset_len */
8456 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8457 		bf_set(payload_offset_len, &wqe->fcp_iwrite,
8458 		       xmit_len + sizeof(struct fcp_rsp));
8459 		bf_set(cmd_buff_len, &wqe->fcp_iwrite,
8460 		       0);
8461 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
8462 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
8463 		bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
8464 		       iocbq->iocb.ulpFCP2Rcvy);
8465 		bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
8466 		/* Always open the exchange */
8467 		bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
8468 		bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
8469 		       LPFC_WQE_LENLOC_WORD4);
8470 		bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
8471 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
8472 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8473 			bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
8474 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
8475 			if (iocbq->priority) {
8476 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
8477 				       (iocbq->priority << 1));
8478 			} else {
8479 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
8480 				       (phba->cfg_XLanePriority << 1));
8481 			}
8482 		}
8483 		/* Note, word 10 is already initialized to 0 */
8484 
8485 		if (phba->fcp_embed_io) {
8486 			struct lpfc_scsi_buf *lpfc_cmd;
8487 			struct sli4_sge *sgl;
8488 			union lpfc_wqe128 *wqe128;
8489 			struct fcp_cmnd *fcp_cmnd;
8490 			uint32_t *ptr;
8491 
8492 			/* 128 byte wqe support here */
8493 			wqe128 = (union lpfc_wqe128 *)wqe;
8494 
8495 			lpfc_cmd = iocbq->context1;
8496 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
8497 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
8498 
8499 			/* Word 0-2 - FCP_CMND */
8500 			wqe128->generic.bde.tus.f.bdeFlags =
8501 				BUFF_TYPE_BDE_IMMED;
8502 			wqe128->generic.bde.tus.f.bdeSize = sgl->sge_len;
8503 			wqe128->generic.bde.addrHigh = 0;
8504 			wqe128->generic.bde.addrLow =  88;  /* Word 22 */
8505 
8506 			bf_set(wqe_wqes, &wqe128->fcp_iwrite.wqe_com, 1);
8507 
8508 			/* Word 22-29  FCP CMND Payload */
8509 			ptr = &wqe128->words[22];
8510 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
8511 		}
8512 		break;
8513 	case CMD_FCP_IREAD64_CR:
8514 		/* word3 iocb=iotag wqe=payload_offset_len */
8515 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8516 		bf_set(payload_offset_len, &wqe->fcp_iread,
8517 		       xmit_len + sizeof(struct fcp_rsp));
8518 		bf_set(cmd_buff_len, &wqe->fcp_iread,
8519 		       0);
8520 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
8521 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
8522 		bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
8523 		       iocbq->iocb.ulpFCP2Rcvy);
8524 		bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
8525 		/* Always open the exchange */
8526 		bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
8527 		bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
8528 		       LPFC_WQE_LENLOC_WORD4);
8529 		bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
8530 		bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
8531 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8532 			bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
8533 			bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
8534 			if (iocbq->priority) {
8535 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
8536 				       (iocbq->priority << 1));
8537 			} else {
8538 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
8539 				       (phba->cfg_XLanePriority << 1));
8540 			}
8541 		}
8542 		/* Note, word 10 is already initialized to 0 */
8543 
8544 		if (phba->fcp_embed_io) {
8545 			struct lpfc_scsi_buf *lpfc_cmd;
8546 			struct sli4_sge *sgl;
8547 			union lpfc_wqe128 *wqe128;
8548 			struct fcp_cmnd *fcp_cmnd;
8549 			uint32_t *ptr;
8550 
8551 			/* 128 byte wqe support here */
8552 			wqe128 = (union lpfc_wqe128 *)wqe;
8553 
8554 			lpfc_cmd = iocbq->context1;
8555 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
8556 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
8557 
8558 			/* Word 0-2 - FCP_CMND */
8559 			wqe128->generic.bde.tus.f.bdeFlags =
8560 				BUFF_TYPE_BDE_IMMED;
8561 			wqe128->generic.bde.tus.f.bdeSize = sgl->sge_len;
8562 			wqe128->generic.bde.addrHigh = 0;
8563 			wqe128->generic.bde.addrLow =  88;  /* Word 22 */
8564 
8565 			bf_set(wqe_wqes, &wqe128->fcp_iread.wqe_com, 1);
8566 
8567 			/* Word 22-29  FCP CMND Payload */
8568 			ptr = &wqe128->words[22];
8569 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
8570 		}
8571 		break;
8572 	case CMD_FCP_ICMND64_CR:
8573 		/* word3 iocb=iotag wqe=payload_offset_len */
8574 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
8575 		bf_set(payload_offset_len, &wqe->fcp_icmd,
8576 		       xmit_len + sizeof(struct fcp_rsp));
8577 		bf_set(cmd_buff_len, &wqe->fcp_icmd,
8578 		       0);
8579 		/* word3 iocb=IO_TAG wqe=reserved */
8580 		bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
8581 		/* Always open the exchange */
8582 		bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
8583 		bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
8584 		bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
8585 		bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
8586 		       LPFC_WQE_LENLOC_NONE);
8587 		bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
8588 		       iocbq->iocb.ulpFCP2Rcvy);
8589 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
8590 			bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
8591 			bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
8592 			if (iocbq->priority) {
8593 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
8594 				       (iocbq->priority << 1));
8595 			} else {
8596 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
8597 				       (phba->cfg_XLanePriority << 1));
8598 			}
8599 		}
8600 		/* Note, word 10 is already initialized to 0 */
8601 
8602 		if (phba->fcp_embed_io) {
8603 			struct lpfc_scsi_buf *lpfc_cmd;
8604 			struct sli4_sge *sgl;
8605 			union lpfc_wqe128 *wqe128;
8606 			struct fcp_cmnd *fcp_cmnd;
8607 			uint32_t *ptr;
8608 
8609 			/* 128 byte wqe support here */
8610 			wqe128 = (union lpfc_wqe128 *)wqe;
8611 
8612 			lpfc_cmd = iocbq->context1;
8613 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
8614 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
8615 
8616 			/* Word 0-2 - FCP_CMND */
8617 			wqe128->generic.bde.tus.f.bdeFlags =
8618 				BUFF_TYPE_BDE_IMMED;
8619 			wqe128->generic.bde.tus.f.bdeSize = sgl->sge_len;
8620 			wqe128->generic.bde.addrHigh = 0;
8621 			wqe128->generic.bde.addrLow =  88;  /* Word 22 */
8622 
8623 			bf_set(wqe_wqes, &wqe128->fcp_icmd.wqe_com, 1);
8624 
8625 			/* Word 22-29  FCP CMND Payload */
8626 			ptr = &wqe128->words[22];
8627 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
8628 		}
8629 		break;
8630 	case CMD_GEN_REQUEST64_CR:
8631 		/* For this command calculate the xmit length of the
8632 		 * request bde.
8633 		 */
8634 		xmit_len = 0;
8635 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
8636 			sizeof(struct ulp_bde64);
8637 		for (i = 0; i < numBdes; i++) {
8638 			bde.tus.w = le32_to_cpu(bpl[i].tus.w);
8639 			if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
8640 				break;
8641 			xmit_len += bde.tus.f.bdeSize;
8642 		}
8643 		/* word3 iocb=IO_TAG wqe=request_payload_len */
8644 		wqe->gen_req.request_payload_len = xmit_len;
8645 		/* word4 iocb=parameter wqe=relative_offset memcpy */
8646 		/* word5 [rctl, type, df_ctl, la] copied in memcpy */
8647 		/* word6 context tag copied in memcpy */
8648 		if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
8649 			ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
8650 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8651 				"2015 Invalid CT %x command 0x%x\n",
8652 				ct, iocbq->iocb.ulpCommand);
8653 			return IOCB_ERROR;
8654 		}
8655 		bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
8656 		bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
8657 		bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
8658 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
8659 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
8660 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
8661 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
8662 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
8663 		wqe->gen_req.max_response_payload_len = total_len - xmit_len;
8664 		command_type = OTHER_COMMAND;
8665 		break;
8666 	case CMD_XMIT_ELS_RSP64_CX:
8667 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
8668 		/* words0-2 BDE memcpy */
8669 		/* word3 iocb=iotag32 wqe=response_payload_len */
8670 		wqe->xmit_els_rsp.response_payload_len = xmit_len;
8671 		/* word4 */
8672 		wqe->xmit_els_rsp.word4 = 0;
8673 		/* word5 iocb=rsvd wge=did */
8674 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
8675 			 iocbq->iocb.un.xseq64.xmit_els_remoteID);
8676 
8677 		if_type = bf_get(lpfc_sli_intf_if_type,
8678 					&phba->sli4_hba.sli_intf);
8679 		if (if_type == LPFC_SLI_INTF_IF_TYPE_2) {
8680 			if (iocbq->vport->fc_flag & FC_PT2PT) {
8681 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
8682 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
8683 					iocbq->vport->fc_myDID);
8684 				if (iocbq->vport->fc_myDID == Fabric_DID) {
8685 					bf_set(wqe_els_did,
8686 						&wqe->xmit_els_rsp.wqe_dest, 0);
8687 				}
8688 			}
8689 		}
8690 		bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
8691 		       ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
8692 		bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
8693 		bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
8694 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
8695 		if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
8696 			bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
8697 			       phba->vpi_ids[iocbq->vport->vpi]);
8698 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
8699 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
8700 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
8701 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
8702 		       LPFC_WQE_LENLOC_WORD3);
8703 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
8704 		bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
8705 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
8706 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
8707 					iocbq->context2)->virt);
8708 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
8709 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
8710 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
8711 					iocbq->vport->fc_myDID);
8712 				bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
8713 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
8714 					phba->vpi_ids[phba->pport->vpi]);
8715 		}
8716 		command_type = OTHER_COMMAND;
8717 		break;
8718 	case CMD_CLOSE_XRI_CN:
8719 	case CMD_ABORT_XRI_CN:
8720 	case CMD_ABORT_XRI_CX:
8721 		/* words 0-2 memcpy should be 0 rserved */
8722 		/* port will send abts */
8723 		abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
8724 		if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
8725 			abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
8726 			fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
8727 		} else
8728 			fip = 0;
8729 
8730 		if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
8731 			/*
8732 			 * The link is down, or the command was ELS_FIP
8733 			 * so the fw does not need to send abts
8734 			 * on the wire.
8735 			 */
8736 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
8737 		else
8738 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
8739 		bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
8740 		/* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
8741 		wqe->abort_cmd.rsrvd5 = 0;
8742 		bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
8743 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
8744 		abort_tag = iocbq->iocb.un.acxri.abortIoTag;
8745 		/*
8746 		 * The abort handler will send us CMD_ABORT_XRI_CN or
8747 		 * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
8748 		 */
8749 		bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
8750 		bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
8751 		bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
8752 		       LPFC_WQE_LENLOC_NONE);
8753 		cmnd = CMD_ABORT_XRI_CX;
8754 		command_type = OTHER_COMMAND;
8755 		xritag = 0;
8756 		break;
8757 	case CMD_XMIT_BLS_RSP64_CX:
8758 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
8759 		/* As BLS ABTS RSP WQE is very different from other WQEs,
8760 		 * we re-construct this WQE here based on information in
8761 		 * iocbq from scratch.
8762 		 */
8763 		memset(wqe, 0, sizeof(union lpfc_wqe));
8764 		/* OX_ID is invariable to who sent ABTS to CT exchange */
8765 		bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
8766 		       bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
8767 		if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
8768 		    LPFC_ABTS_UNSOL_INT) {
8769 			/* ABTS sent by initiator to CT exchange, the
8770 			 * RX_ID field will be filled with the newly
8771 			 * allocated responder XRI.
8772 			 */
8773 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
8774 			       iocbq->sli4_xritag);
8775 		} else {
8776 			/* ABTS sent by responder to CT exchange, the
8777 			 * RX_ID field will be filled with the responder
8778 			 * RX_ID from ABTS.
8779 			 */
8780 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
8781 			       bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
8782 		}
8783 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
8784 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
8785 
8786 		/* Use CT=VPI */
8787 		bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
8788 			ndlp->nlp_DID);
8789 		bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
8790 			iocbq->iocb.ulpContext);
8791 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
8792 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
8793 			phba->vpi_ids[phba->pport->vpi]);
8794 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
8795 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
8796 		       LPFC_WQE_LENLOC_NONE);
8797 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
8798 		command_type = OTHER_COMMAND;
8799 		if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
8800 			bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
8801 			       bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
8802 			bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
8803 			       bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
8804 			bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
8805 			       bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
8806 		}
8807 
8808 		break;
8809 	case CMD_XRI_ABORTED_CX:
8810 	case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
8811 	case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
8812 	case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
8813 	case CMD_FCP_TRSP64_CX: /* Target mode rcv */
8814 	case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
8815 	default:
8816 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8817 				"2014 Invalid command 0x%x\n",
8818 				iocbq->iocb.ulpCommand);
8819 		return IOCB_ERROR;
8820 		break;
8821 	}
8822 
8823 	if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
8824 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
8825 	else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
8826 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
8827 	else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
8828 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
8829 	iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
8830 			      LPFC_IO_DIF_INSERT);
8831 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
8832 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
8833 	wqe->generic.wqe_com.abort_tag = abort_tag;
8834 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
8835 	bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
8836 	bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
8837 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
8838 	return 0;
8839 }
8840 
8841 /**
8842  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
8843  * @phba: Pointer to HBA context object.
8844  * @ring_number: SLI ring number to issue iocb on.
8845  * @piocb: Pointer to command iocb.
8846  * @flag: Flag indicating if this command can be put into txq.
8847  *
8848  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
8849  * an iocb command to an HBA with SLI-4 interface spec.
8850  *
8851  * This function is called with hbalock held. The function will return success
8852  * after it successfully submit the iocb to firmware or after adding to the
8853  * txq.
8854  **/
8855 static int
8856 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
8857 			 struct lpfc_iocbq *piocb, uint32_t flag)
8858 {
8859 	struct lpfc_sglq *sglq;
8860 	union lpfc_wqe *wqe;
8861 	union lpfc_wqe128 wqe128;
8862 	struct lpfc_queue *wq;
8863 	struct lpfc_sli_ring *pring = &phba->sli.ring[ring_number];
8864 
8865 	lockdep_assert_held(&phba->hbalock);
8866 
8867 	/*
8868 	 * The WQE can be either 64 or 128 bytes,
8869 	 * so allocate space on the stack assuming the largest.
8870 	 */
8871 	wqe = (union lpfc_wqe *)&wqe128;
8872 
8873 	if (piocb->sli4_xritag == NO_XRI) {
8874 		if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
8875 		    piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
8876 			sglq = NULL;
8877 		else {
8878 			if (!list_empty(&pring->txq)) {
8879 				if (!(flag & SLI_IOCB_RET_IOCB)) {
8880 					__lpfc_sli_ringtx_put(phba,
8881 						pring, piocb);
8882 					return IOCB_SUCCESS;
8883 				} else {
8884 					return IOCB_BUSY;
8885 				}
8886 			} else {
8887 				sglq = __lpfc_sli_get_sglq(phba, piocb);
8888 				if (!sglq) {
8889 					if (!(flag & SLI_IOCB_RET_IOCB)) {
8890 						__lpfc_sli_ringtx_put(phba,
8891 								pring,
8892 								piocb);
8893 						return IOCB_SUCCESS;
8894 					} else
8895 						return IOCB_BUSY;
8896 				}
8897 			}
8898 		}
8899 	} else if (piocb->iocb_flag &  LPFC_IO_FCP) {
8900 		/* These IO's already have an XRI and a mapped sgl. */
8901 		sglq = NULL;
8902 	} else {
8903 		/*
8904 		 * This is a continuation of a commandi,(CX) so this
8905 		 * sglq is on the active list
8906 		 */
8907 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
8908 		if (!sglq)
8909 			return IOCB_ERROR;
8910 	}
8911 
8912 	if (sglq) {
8913 		piocb->sli4_lxritag = sglq->sli4_lxritag;
8914 		piocb->sli4_xritag = sglq->sli4_xritag;
8915 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
8916 			return IOCB_ERROR;
8917 	}
8918 
8919 	if (lpfc_sli4_iocb2wqe(phba, piocb, wqe))
8920 		return IOCB_ERROR;
8921 
8922 	if ((piocb->iocb_flag & LPFC_IO_FCP) ||
8923 	    (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
8924 		if (!phba->cfg_fof || (!(piocb->iocb_flag & LPFC_IO_OAS))) {
8925 			wq = phba->sli4_hba.fcp_wq[piocb->fcp_wqidx];
8926 		} else {
8927 			wq = phba->sli4_hba.oas_wq;
8928 		}
8929 		if (lpfc_sli4_wq_put(wq, wqe))
8930 			return IOCB_ERROR;
8931 	} else {
8932 		if (unlikely(!phba->sli4_hba.els_wq))
8933 			return IOCB_ERROR;
8934 		if (lpfc_sli4_wq_put(phba->sli4_hba.els_wq, wqe))
8935 			return IOCB_ERROR;
8936 	}
8937 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
8938 
8939 	return 0;
8940 }
8941 
8942 /**
8943  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
8944  *
8945  * This routine wraps the actual lockless version for issusing IOCB function
8946  * pointer from the lpfc_hba struct.
8947  *
8948  * Return codes:
8949  * IOCB_ERROR - Error
8950  * IOCB_SUCCESS - Success
8951  * IOCB_BUSY - Busy
8952  **/
8953 int
8954 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
8955 		struct lpfc_iocbq *piocb, uint32_t flag)
8956 {
8957 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
8958 }
8959 
8960 /**
8961  * lpfc_sli_api_table_setup - Set up sli api function jump table
8962  * @phba: The hba struct for which this call is being executed.
8963  * @dev_grp: The HBA PCI-Device group number.
8964  *
8965  * This routine sets up the SLI interface API function jump table in @phba
8966  * struct.
8967  * Returns: 0 - success, -ENODEV - failure.
8968  **/
8969 int
8970 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8971 {
8972 
8973 	switch (dev_grp) {
8974 	case LPFC_PCI_DEV_LP:
8975 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
8976 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
8977 		break;
8978 	case LPFC_PCI_DEV_OC:
8979 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
8980 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
8981 		break;
8982 	default:
8983 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8984 				"1419 Invalid HBA PCI-device group: 0x%x\n",
8985 				dev_grp);
8986 		return -ENODEV;
8987 		break;
8988 	}
8989 	phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
8990 	return 0;
8991 }
8992 
8993 /**
8994  * lpfc_sli_calc_ring - Calculates which ring to use
8995  * @phba: Pointer to HBA context object.
8996  * @ring_number: Initial ring
8997  * @piocb: Pointer to command iocb.
8998  *
8999  * For SLI4, FCP IO can deferred to one fo many WQs, based on
9000  * fcp_wqidx, thus we need to calculate the corresponding ring.
9001  * Since ABORTS must go on the same WQ of the command they are
9002  * aborting, we use command's fcp_wqidx.
9003  */
9004 static int
9005 lpfc_sli_calc_ring(struct lpfc_hba *phba, uint32_t ring_number,
9006 		    struct lpfc_iocbq *piocb)
9007 {
9008 	if (phba->sli_rev < LPFC_SLI_REV4)
9009 		return ring_number;
9010 
9011 	if (piocb->iocb_flag &  (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
9012 		if (!(phba->cfg_fof) ||
9013 				(!(piocb->iocb_flag & LPFC_IO_FOF))) {
9014 			if (unlikely(!phba->sli4_hba.fcp_wq))
9015 				return LPFC_HBA_ERROR;
9016 			/*
9017 			 * for abort iocb fcp_wqidx should already
9018 			 * be setup based on what work queue we used.
9019 			 */
9020 			if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX))
9021 				piocb->fcp_wqidx =
9022 					lpfc_sli4_scmd_to_wqidx_distr(phba,
9023 							      piocb->context1);
9024 			ring_number = MAX_SLI3_CONFIGURED_RINGS +
9025 				piocb->fcp_wqidx;
9026 		} else {
9027 			if (unlikely(!phba->sli4_hba.oas_wq))
9028 				return LPFC_HBA_ERROR;
9029 			piocb->fcp_wqidx = 0;
9030 			ring_number =  LPFC_FCP_OAS_RING;
9031 		}
9032 	}
9033 	return ring_number;
9034 }
9035 
9036 /**
9037  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
9038  * @phba: Pointer to HBA context object.
9039  * @pring: Pointer to driver SLI ring object.
9040  * @piocb: Pointer to command iocb.
9041  * @flag: Flag indicating if this command can be put into txq.
9042  *
9043  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
9044  * function. This function gets the hbalock and calls
9045  * __lpfc_sli_issue_iocb function and will return the error returned
9046  * by __lpfc_sli_issue_iocb function. This wrapper is used by
9047  * functions which do not hold hbalock.
9048  **/
9049 int
9050 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
9051 		    struct lpfc_iocbq *piocb, uint32_t flag)
9052 {
9053 	struct lpfc_fcp_eq_hdl *fcp_eq_hdl;
9054 	struct lpfc_sli_ring *pring;
9055 	struct lpfc_queue *fpeq;
9056 	struct lpfc_eqe *eqe;
9057 	unsigned long iflags;
9058 	int rc, idx;
9059 
9060 	if (phba->sli_rev == LPFC_SLI_REV4) {
9061 		ring_number = lpfc_sli_calc_ring(phba, ring_number, piocb);
9062 		if (unlikely(ring_number == LPFC_HBA_ERROR))
9063 			return IOCB_ERROR;
9064 		idx = piocb->fcp_wqidx;
9065 
9066 		pring = &phba->sli.ring[ring_number];
9067 		spin_lock_irqsave(&pring->ring_lock, iflags);
9068 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
9069 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
9070 
9071 		if (lpfc_fcp_look_ahead && (piocb->iocb_flag &  LPFC_IO_FCP)) {
9072 			fcp_eq_hdl = &phba->sli4_hba.fcp_eq_hdl[idx];
9073 
9074 			if (atomic_dec_and_test(&fcp_eq_hdl->
9075 				fcp_eq_in_use)) {
9076 
9077 				/* Get associated EQ with this index */
9078 				fpeq = phba->sli4_hba.hba_eq[idx];
9079 
9080 				/* Turn off interrupts from this EQ */
9081 				lpfc_sli4_eq_clr_intr(fpeq);
9082 
9083 				/*
9084 				 * Process all the events on FCP EQ
9085 				 */
9086 				while ((eqe = lpfc_sli4_eq_get(fpeq))) {
9087 					lpfc_sli4_hba_handle_eqe(phba,
9088 						eqe, idx);
9089 					fpeq->EQ_processed++;
9090 				}
9091 
9092 				/* Always clear and re-arm the EQ */
9093 				lpfc_sli4_eq_release(fpeq,
9094 					LPFC_QUEUE_REARM);
9095 			}
9096 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
9097 		}
9098 	} else {
9099 		/* For now, SLI2/3 will still use hbalock */
9100 		spin_lock_irqsave(&phba->hbalock, iflags);
9101 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
9102 		spin_unlock_irqrestore(&phba->hbalock, iflags);
9103 	}
9104 	return rc;
9105 }
9106 
9107 /**
9108  * lpfc_extra_ring_setup - Extra ring setup function
9109  * @phba: Pointer to HBA context object.
9110  *
9111  * This function is called while driver attaches with the
9112  * HBA to setup the extra ring. The extra ring is used
9113  * only when driver needs to support target mode functionality
9114  * or IP over FC functionalities.
9115  *
9116  * This function is called with no lock held.
9117  **/
9118 static int
9119 lpfc_extra_ring_setup( struct lpfc_hba *phba)
9120 {
9121 	struct lpfc_sli *psli;
9122 	struct lpfc_sli_ring *pring;
9123 
9124 	psli = &phba->sli;
9125 
9126 	/* Adjust cmd/rsp ring iocb entries more evenly */
9127 
9128 	/* Take some away from the FCP ring */
9129 	pring = &psli->ring[psli->fcp_ring];
9130 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
9131 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
9132 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
9133 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
9134 
9135 	/* and give them to the extra ring */
9136 	pring = &psli->ring[psli->extra_ring];
9137 
9138 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
9139 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
9140 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
9141 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
9142 
9143 	/* Setup default profile for this ring */
9144 	pring->iotag_max = 4096;
9145 	pring->num_mask = 1;
9146 	pring->prt[0].profile = 0;      /* Mask 0 */
9147 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
9148 	pring->prt[0].type = phba->cfg_multi_ring_type;
9149 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
9150 	return 0;
9151 }
9152 
9153 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
9154  * @phba: Pointer to HBA context object.
9155  * @iocbq: Pointer to iocb object.
9156  *
9157  * The async_event handler calls this routine when it receives
9158  * an ASYNC_STATUS_CN event from the port.  The port generates
9159  * this event when an Abort Sequence request to an rport fails
9160  * twice in succession.  The abort could be originated by the
9161  * driver or by the port.  The ABTS could have been for an ELS
9162  * or FCP IO.  The port only generates this event when an ABTS
9163  * fails to complete after one retry.
9164  */
9165 static void
9166 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
9167 			  struct lpfc_iocbq *iocbq)
9168 {
9169 	struct lpfc_nodelist *ndlp = NULL;
9170 	uint16_t rpi = 0, vpi = 0;
9171 	struct lpfc_vport *vport = NULL;
9172 
9173 	/* The rpi in the ulpContext is vport-sensitive. */
9174 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
9175 	rpi = iocbq->iocb.ulpContext;
9176 
9177 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9178 			"3092 Port generated ABTS async event "
9179 			"on vpi %d rpi %d status 0x%x\n",
9180 			vpi, rpi, iocbq->iocb.ulpStatus);
9181 
9182 	vport = lpfc_find_vport_by_vpid(phba, vpi);
9183 	if (!vport)
9184 		goto err_exit;
9185 	ndlp = lpfc_findnode_rpi(vport, rpi);
9186 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp))
9187 		goto err_exit;
9188 
9189 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
9190 		lpfc_sli_abts_recover_port(vport, ndlp);
9191 	return;
9192 
9193  err_exit:
9194 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9195 			"3095 Event Context not found, no "
9196 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
9197 			iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
9198 			vpi, rpi);
9199 }
9200 
9201 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
9202  * @phba: pointer to HBA context object.
9203  * @ndlp: nodelist pointer for the impacted rport.
9204  * @axri: pointer to the wcqe containing the failed exchange.
9205  *
9206  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
9207  * port.  The port generates this event when an abort exchange request to an
9208  * rport fails twice in succession with no reply.  The abort could be originated
9209  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
9210  */
9211 void
9212 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
9213 			   struct lpfc_nodelist *ndlp,
9214 			   struct sli4_wcqe_xri_aborted *axri)
9215 {
9216 	struct lpfc_vport *vport;
9217 	uint32_t ext_status = 0;
9218 
9219 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)) {
9220 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
9221 				"3115 Node Context not found, driver "
9222 				"ignoring abts err event\n");
9223 		return;
9224 	}
9225 
9226 	vport = ndlp->vport;
9227 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9228 			"3116 Port generated FCP XRI ABORT event on "
9229 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
9230 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
9231 			bf_get(lpfc_wcqe_xa_xri, axri),
9232 			bf_get(lpfc_wcqe_xa_status, axri),
9233 			axri->parameter);
9234 
9235 	/*
9236 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
9237 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
9238 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
9239 	 */
9240 	ext_status = axri->parameter & IOERR_PARAM_MASK;
9241 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
9242 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
9243 		lpfc_sli_abts_recover_port(vport, ndlp);
9244 }
9245 
9246 /**
9247  * lpfc_sli_async_event_handler - ASYNC iocb handler function
9248  * @phba: Pointer to HBA context object.
9249  * @pring: Pointer to driver SLI ring object.
9250  * @iocbq: Pointer to iocb object.
9251  *
9252  * This function is called by the slow ring event handler
9253  * function when there is an ASYNC event iocb in the ring.
9254  * This function is called with no lock held.
9255  * Currently this function handles only temperature related
9256  * ASYNC events. The function decodes the temperature sensor
9257  * event message and posts events for the management applications.
9258  **/
9259 static void
9260 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
9261 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
9262 {
9263 	IOCB_t *icmd;
9264 	uint16_t evt_code;
9265 	struct temp_event temp_event_data;
9266 	struct Scsi_Host *shost;
9267 	uint32_t *iocb_w;
9268 
9269 	icmd = &iocbq->iocb;
9270 	evt_code = icmd->un.asyncstat.evt_code;
9271 
9272 	switch (evt_code) {
9273 	case ASYNC_TEMP_WARN:
9274 	case ASYNC_TEMP_SAFE:
9275 		temp_event_data.data = (uint32_t) icmd->ulpContext;
9276 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
9277 		if (evt_code == ASYNC_TEMP_WARN) {
9278 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
9279 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
9280 				"0347 Adapter is very hot, please take "
9281 				"corrective action. temperature : %d Celsius\n",
9282 				(uint32_t) icmd->ulpContext);
9283 		} else {
9284 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
9285 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
9286 				"0340 Adapter temperature is OK now. "
9287 				"temperature : %d Celsius\n",
9288 				(uint32_t) icmd->ulpContext);
9289 		}
9290 
9291 		/* Send temperature change event to applications */
9292 		shost = lpfc_shost_from_vport(phba->pport);
9293 		fc_host_post_vendor_event(shost, fc_get_event_number(),
9294 			sizeof(temp_event_data), (char *) &temp_event_data,
9295 			LPFC_NL_VENDOR_ID);
9296 		break;
9297 	case ASYNC_STATUS_CN:
9298 		lpfc_sli_abts_err_handler(phba, iocbq);
9299 		break;
9300 	default:
9301 		iocb_w = (uint32_t *) icmd;
9302 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9303 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
9304 			" evt_code 0x%x\n"
9305 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
9306 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
9307 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
9308 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
9309 			pring->ringno, icmd->un.asyncstat.evt_code,
9310 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
9311 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
9312 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
9313 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
9314 
9315 		break;
9316 	}
9317 }
9318 
9319 
9320 /**
9321  * lpfc_sli_setup - SLI ring setup function
9322  * @phba: Pointer to HBA context object.
9323  *
9324  * lpfc_sli_setup sets up rings of the SLI interface with
9325  * number of iocbs per ring and iotags. This function is
9326  * called while driver attach to the HBA and before the
9327  * interrupts are enabled. So there is no need for locking.
9328  *
9329  * This function always returns 0.
9330  **/
9331 int
9332 lpfc_sli_setup(struct lpfc_hba *phba)
9333 {
9334 	int i, totiocbsize = 0;
9335 	struct lpfc_sli *psli = &phba->sli;
9336 	struct lpfc_sli_ring *pring;
9337 
9338 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
9339 	if (phba->sli_rev == LPFC_SLI_REV4)
9340 		psli->num_rings += phba->cfg_fcp_io_channel;
9341 	psli->sli_flag = 0;
9342 	psli->fcp_ring = LPFC_FCP_RING;
9343 	psli->next_ring = LPFC_FCP_NEXT_RING;
9344 	psli->extra_ring = LPFC_EXTRA_RING;
9345 
9346 	psli->iocbq_lookup = NULL;
9347 	psli->iocbq_lookup_len = 0;
9348 	psli->last_iotag = 0;
9349 
9350 	for (i = 0; i < psli->num_rings; i++) {
9351 		pring = &psli->ring[i];
9352 		switch (i) {
9353 		case LPFC_FCP_RING:	/* ring 0 - FCP */
9354 			/* numCiocb and numRiocb are used in config_port */
9355 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
9356 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
9357 			pring->sli.sli3.numCiocb +=
9358 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
9359 			pring->sli.sli3.numRiocb +=
9360 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
9361 			pring->sli.sli3.numCiocb +=
9362 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
9363 			pring->sli.sli3.numRiocb +=
9364 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
9365 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9366 							SLI3_IOCB_CMD_SIZE :
9367 							SLI2_IOCB_CMD_SIZE;
9368 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9369 							SLI3_IOCB_RSP_SIZE :
9370 							SLI2_IOCB_RSP_SIZE;
9371 			pring->iotag_ctr = 0;
9372 			pring->iotag_max =
9373 			    (phba->cfg_hba_queue_depth * 2);
9374 			pring->fast_iotag = pring->iotag_max;
9375 			pring->num_mask = 0;
9376 			break;
9377 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
9378 			/* numCiocb and numRiocb are used in config_port */
9379 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
9380 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
9381 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9382 							SLI3_IOCB_CMD_SIZE :
9383 							SLI2_IOCB_CMD_SIZE;
9384 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9385 							SLI3_IOCB_RSP_SIZE :
9386 							SLI2_IOCB_RSP_SIZE;
9387 			pring->iotag_max = phba->cfg_hba_queue_depth;
9388 			pring->num_mask = 0;
9389 			break;
9390 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
9391 			/* numCiocb and numRiocb are used in config_port */
9392 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
9393 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
9394 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
9395 							SLI3_IOCB_CMD_SIZE :
9396 							SLI2_IOCB_CMD_SIZE;
9397 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
9398 							SLI3_IOCB_RSP_SIZE :
9399 							SLI2_IOCB_RSP_SIZE;
9400 			pring->fast_iotag = 0;
9401 			pring->iotag_ctr = 0;
9402 			pring->iotag_max = 4096;
9403 			pring->lpfc_sli_rcv_async_status =
9404 				lpfc_sli_async_event_handler;
9405 			pring->num_mask = LPFC_MAX_RING_MASK;
9406 			pring->prt[0].profile = 0;	/* Mask 0 */
9407 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
9408 			pring->prt[0].type = FC_TYPE_ELS;
9409 			pring->prt[0].lpfc_sli_rcv_unsol_event =
9410 			    lpfc_els_unsol_event;
9411 			pring->prt[1].profile = 0;	/* Mask 1 */
9412 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
9413 			pring->prt[1].type = FC_TYPE_ELS;
9414 			pring->prt[1].lpfc_sli_rcv_unsol_event =
9415 			    lpfc_els_unsol_event;
9416 			pring->prt[2].profile = 0;	/* Mask 2 */
9417 			/* NameServer Inquiry */
9418 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
9419 			/* NameServer */
9420 			pring->prt[2].type = FC_TYPE_CT;
9421 			pring->prt[2].lpfc_sli_rcv_unsol_event =
9422 			    lpfc_ct_unsol_event;
9423 			pring->prt[3].profile = 0;	/* Mask 3 */
9424 			/* NameServer response */
9425 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
9426 			/* NameServer */
9427 			pring->prt[3].type = FC_TYPE_CT;
9428 			pring->prt[3].lpfc_sli_rcv_unsol_event =
9429 			    lpfc_ct_unsol_event;
9430 			break;
9431 		}
9432 		totiocbsize += (pring->sli.sli3.numCiocb *
9433 			pring->sli.sli3.sizeCiocb) +
9434 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
9435 	}
9436 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
9437 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
9438 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
9439 		       "SLI2 SLIM Data: x%x x%lx\n",
9440 		       phba->brd_no, totiocbsize,
9441 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
9442 	}
9443 	if (phba->cfg_multi_ring_support == 2)
9444 		lpfc_extra_ring_setup(phba);
9445 
9446 	return 0;
9447 }
9448 
9449 /**
9450  * lpfc_sli_queue_setup - Queue initialization function
9451  * @phba: Pointer to HBA context object.
9452  *
9453  * lpfc_sli_queue_setup sets up mailbox queues and iocb queues for each
9454  * ring. This function also initializes ring indices of each ring.
9455  * This function is called during the initialization of the SLI
9456  * interface of an HBA.
9457  * This function is called with no lock held and always returns
9458  * 1.
9459  **/
9460 int
9461 lpfc_sli_queue_setup(struct lpfc_hba *phba)
9462 {
9463 	struct lpfc_sli *psli;
9464 	struct lpfc_sli_ring *pring;
9465 	int i;
9466 
9467 	psli = &phba->sli;
9468 	spin_lock_irq(&phba->hbalock);
9469 	INIT_LIST_HEAD(&psli->mboxq);
9470 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
9471 	/* Initialize list headers for txq and txcmplq as double linked lists */
9472 	for (i = 0; i < psli->num_rings; i++) {
9473 		pring = &psli->ring[i];
9474 		pring->ringno = i;
9475 		pring->sli.sli3.next_cmdidx  = 0;
9476 		pring->sli.sli3.local_getidx = 0;
9477 		pring->sli.sli3.cmdidx = 0;
9478 		pring->flag = 0;
9479 		INIT_LIST_HEAD(&pring->txq);
9480 		INIT_LIST_HEAD(&pring->txcmplq);
9481 		INIT_LIST_HEAD(&pring->iocb_continueq);
9482 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
9483 		INIT_LIST_HEAD(&pring->postbufq);
9484 		spin_lock_init(&pring->ring_lock);
9485 	}
9486 	spin_unlock_irq(&phba->hbalock);
9487 	return 1;
9488 }
9489 
9490 /**
9491  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
9492  * @phba: Pointer to HBA context object.
9493  *
9494  * This routine flushes the mailbox command subsystem. It will unconditionally
9495  * flush all the mailbox commands in the three possible stages in the mailbox
9496  * command sub-system: pending mailbox command queue; the outstanding mailbox
9497  * command; and completed mailbox command queue. It is caller's responsibility
9498  * to make sure that the driver is in the proper state to flush the mailbox
9499  * command sub-system. Namely, the posting of mailbox commands into the
9500  * pending mailbox command queue from the various clients must be stopped;
9501  * either the HBA is in a state that it will never works on the outstanding
9502  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
9503  * mailbox command has been completed.
9504  **/
9505 static void
9506 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
9507 {
9508 	LIST_HEAD(completions);
9509 	struct lpfc_sli *psli = &phba->sli;
9510 	LPFC_MBOXQ_t *pmb;
9511 	unsigned long iflag;
9512 
9513 	/* Flush all the mailbox commands in the mbox system */
9514 	spin_lock_irqsave(&phba->hbalock, iflag);
9515 	/* The pending mailbox command queue */
9516 	list_splice_init(&phba->sli.mboxq, &completions);
9517 	/* The outstanding active mailbox command */
9518 	if (psli->mbox_active) {
9519 		list_add_tail(&psli->mbox_active->list, &completions);
9520 		psli->mbox_active = NULL;
9521 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9522 	}
9523 	/* The completed mailbox command queue */
9524 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
9525 	spin_unlock_irqrestore(&phba->hbalock, iflag);
9526 
9527 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
9528 	while (!list_empty(&completions)) {
9529 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
9530 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
9531 		if (pmb->mbox_cmpl)
9532 			pmb->mbox_cmpl(phba, pmb);
9533 	}
9534 }
9535 
9536 /**
9537  * lpfc_sli_host_down - Vport cleanup function
9538  * @vport: Pointer to virtual port object.
9539  *
9540  * lpfc_sli_host_down is called to clean up the resources
9541  * associated with a vport before destroying virtual
9542  * port data structures.
9543  * This function does following operations:
9544  * - Free discovery resources associated with this virtual
9545  *   port.
9546  * - Free iocbs associated with this virtual port in
9547  *   the txq.
9548  * - Send abort for all iocb commands associated with this
9549  *   vport in txcmplq.
9550  *
9551  * This function is called with no lock held and always returns 1.
9552  **/
9553 int
9554 lpfc_sli_host_down(struct lpfc_vport *vport)
9555 {
9556 	LIST_HEAD(completions);
9557 	struct lpfc_hba *phba = vport->phba;
9558 	struct lpfc_sli *psli = &phba->sli;
9559 	struct lpfc_sli_ring *pring;
9560 	struct lpfc_iocbq *iocb, *next_iocb;
9561 	int i;
9562 	unsigned long flags = 0;
9563 	uint16_t prev_pring_flag;
9564 
9565 	lpfc_cleanup_discovery_resources(vport);
9566 
9567 	spin_lock_irqsave(&phba->hbalock, flags);
9568 	for (i = 0; i < psli->num_rings; i++) {
9569 		pring = &psli->ring[i];
9570 		prev_pring_flag = pring->flag;
9571 		/* Only slow rings */
9572 		if (pring->ringno == LPFC_ELS_RING) {
9573 			pring->flag |= LPFC_DEFERRED_RING_EVENT;
9574 			/* Set the lpfc data pending flag */
9575 			set_bit(LPFC_DATA_READY, &phba->data_flags);
9576 		}
9577 		/*
9578 		 * Error everything on the txq since these iocbs have not been
9579 		 * given to the FW yet.
9580 		 */
9581 		list_for_each_entry_safe(iocb, next_iocb, &pring->txq, list) {
9582 			if (iocb->vport != vport)
9583 				continue;
9584 			list_move_tail(&iocb->list, &completions);
9585 		}
9586 
9587 		/* Next issue ABTS for everything on the txcmplq */
9588 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq,
9589 									list) {
9590 			if (iocb->vport != vport)
9591 				continue;
9592 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
9593 		}
9594 
9595 		pring->flag = prev_pring_flag;
9596 	}
9597 
9598 	spin_unlock_irqrestore(&phba->hbalock, flags);
9599 
9600 	/* Cancel all the IOCBs from the completions list */
9601 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
9602 			      IOERR_SLI_DOWN);
9603 	return 1;
9604 }
9605 
9606 /**
9607  * lpfc_sli_hba_down - Resource cleanup function for the HBA
9608  * @phba: Pointer to HBA context object.
9609  *
9610  * This function cleans up all iocb, buffers, mailbox commands
9611  * while shutting down the HBA. This function is called with no
9612  * lock held and always returns 1.
9613  * This function does the following to cleanup driver resources:
9614  * - Free discovery resources for each virtual port
9615  * - Cleanup any pending fabric iocbs
9616  * - Iterate through the iocb txq and free each entry
9617  *   in the list.
9618  * - Free up any buffer posted to the HBA
9619  * - Free mailbox commands in the mailbox queue.
9620  **/
9621 int
9622 lpfc_sli_hba_down(struct lpfc_hba *phba)
9623 {
9624 	LIST_HEAD(completions);
9625 	struct lpfc_sli *psli = &phba->sli;
9626 	struct lpfc_sli_ring *pring;
9627 	struct lpfc_dmabuf *buf_ptr;
9628 	unsigned long flags = 0;
9629 	int i;
9630 
9631 	/* Shutdown the mailbox command sub-system */
9632 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
9633 
9634 	lpfc_hba_down_prep(phba);
9635 
9636 	lpfc_fabric_abort_hba(phba);
9637 
9638 	spin_lock_irqsave(&phba->hbalock, flags);
9639 	for (i = 0; i < psli->num_rings; i++) {
9640 		pring = &psli->ring[i];
9641 		/* Only slow rings */
9642 		if (pring->ringno == LPFC_ELS_RING) {
9643 			pring->flag |= LPFC_DEFERRED_RING_EVENT;
9644 			/* Set the lpfc data pending flag */
9645 			set_bit(LPFC_DATA_READY, &phba->data_flags);
9646 		}
9647 
9648 		/*
9649 		 * Error everything on the txq since these iocbs have not been
9650 		 * given to the FW yet.
9651 		 */
9652 		list_splice_init(&pring->txq, &completions);
9653 	}
9654 	spin_unlock_irqrestore(&phba->hbalock, flags);
9655 
9656 	/* Cancel all the IOCBs from the completions list */
9657 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
9658 			      IOERR_SLI_DOWN);
9659 
9660 	spin_lock_irqsave(&phba->hbalock, flags);
9661 	list_splice_init(&phba->elsbuf, &completions);
9662 	phba->elsbuf_cnt = 0;
9663 	phba->elsbuf_prev_cnt = 0;
9664 	spin_unlock_irqrestore(&phba->hbalock, flags);
9665 
9666 	while (!list_empty(&completions)) {
9667 		list_remove_head(&completions, buf_ptr,
9668 			struct lpfc_dmabuf, list);
9669 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
9670 		kfree(buf_ptr);
9671 	}
9672 
9673 	/* Return any active mbox cmds */
9674 	del_timer_sync(&psli->mbox_tmo);
9675 
9676 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
9677 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
9678 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
9679 
9680 	return 1;
9681 }
9682 
9683 /**
9684  * lpfc_sli_pcimem_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 driver memory
9690  * and the SLI memory. This function also changes the endianness
9691  * of each word if native endianness is different from SLI
9692  * endianness. This function can be called with or without
9693  * lock.
9694  **/
9695 void
9696 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
9697 {
9698 	uint32_t *src = srcp;
9699 	uint32_t *dest = destp;
9700 	uint32_t ldata;
9701 	int i;
9702 
9703 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
9704 		ldata = *src;
9705 		ldata = le32_to_cpu(ldata);
9706 		*dest = ldata;
9707 		src++;
9708 		dest++;
9709 	}
9710 }
9711 
9712 
9713 /**
9714  * lpfc_sli_bemem_bcopy - SLI memory copy function
9715  * @srcp: Source memory pointer.
9716  * @destp: Destination memory pointer.
9717  * @cnt: Number of words required to be copied.
9718  *
9719  * This function is used for copying data between a data structure
9720  * with big endian representation to local endianness.
9721  * This function can be called with or without lock.
9722  **/
9723 void
9724 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
9725 {
9726 	uint32_t *src = srcp;
9727 	uint32_t *dest = destp;
9728 	uint32_t ldata;
9729 	int i;
9730 
9731 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
9732 		ldata = *src;
9733 		ldata = be32_to_cpu(ldata);
9734 		*dest = ldata;
9735 		src++;
9736 		dest++;
9737 	}
9738 }
9739 
9740 /**
9741  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
9742  * @phba: Pointer to HBA context object.
9743  * @pring: Pointer to driver SLI ring object.
9744  * @mp: Pointer to driver buffer object.
9745  *
9746  * This function is called with no lock held.
9747  * It always return zero after adding the buffer to the postbufq
9748  * buffer list.
9749  **/
9750 int
9751 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9752 			 struct lpfc_dmabuf *mp)
9753 {
9754 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
9755 	   later */
9756 	spin_lock_irq(&phba->hbalock);
9757 	list_add_tail(&mp->list, &pring->postbufq);
9758 	pring->postbufq_cnt++;
9759 	spin_unlock_irq(&phba->hbalock);
9760 	return 0;
9761 }
9762 
9763 /**
9764  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
9765  * @phba: Pointer to HBA context object.
9766  *
9767  * When HBQ is enabled, buffers are searched based on tags. This function
9768  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
9769  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
9770  * does not conflict with tags of buffer posted for unsolicited events.
9771  * The function returns the allocated tag. The function is called with
9772  * no locks held.
9773  **/
9774 uint32_t
9775 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
9776 {
9777 	spin_lock_irq(&phba->hbalock);
9778 	phba->buffer_tag_count++;
9779 	/*
9780 	 * Always set the QUE_BUFTAG_BIT to distiguish between
9781 	 * a tag assigned by HBQ.
9782 	 */
9783 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
9784 	spin_unlock_irq(&phba->hbalock);
9785 	return phba->buffer_tag_count;
9786 }
9787 
9788 /**
9789  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
9790  * @phba: Pointer to HBA context object.
9791  * @pring: Pointer to driver SLI ring object.
9792  * @tag: Buffer tag.
9793  *
9794  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
9795  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
9796  * iocb is posted to the response ring with the tag of the buffer.
9797  * This function searches the pring->postbufq list using the tag
9798  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
9799  * iocb. If the buffer is found then lpfc_dmabuf object of the
9800  * buffer is returned to the caller else NULL is returned.
9801  * This function is called with no lock held.
9802  **/
9803 struct lpfc_dmabuf *
9804 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9805 			uint32_t tag)
9806 {
9807 	struct lpfc_dmabuf *mp, *next_mp;
9808 	struct list_head *slp = &pring->postbufq;
9809 
9810 	/* Search postbufq, from the beginning, looking for a match on tag */
9811 	spin_lock_irq(&phba->hbalock);
9812 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
9813 		if (mp->buffer_tag == tag) {
9814 			list_del_init(&mp->list);
9815 			pring->postbufq_cnt--;
9816 			spin_unlock_irq(&phba->hbalock);
9817 			return mp;
9818 		}
9819 	}
9820 
9821 	spin_unlock_irq(&phba->hbalock);
9822 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9823 			"0402 Cannot find virtual addr for buffer tag on "
9824 			"ring %d Data x%lx x%p x%p x%x\n",
9825 			pring->ringno, (unsigned long) tag,
9826 			slp->next, slp->prev, pring->postbufq_cnt);
9827 
9828 	return NULL;
9829 }
9830 
9831 /**
9832  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
9833  * @phba: Pointer to HBA context object.
9834  * @pring: Pointer to driver SLI ring object.
9835  * @phys: DMA address of the buffer.
9836  *
9837  * This function searches the buffer list using the dma_address
9838  * of unsolicited event to find the driver's lpfc_dmabuf object
9839  * corresponding to the dma_address. The function returns the
9840  * lpfc_dmabuf object if a buffer is found else it returns NULL.
9841  * This function is called by the ct and els unsolicited event
9842  * handlers to get the buffer associated with the unsolicited
9843  * event.
9844  *
9845  * This function is called with no lock held.
9846  **/
9847 struct lpfc_dmabuf *
9848 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9849 			 dma_addr_t phys)
9850 {
9851 	struct lpfc_dmabuf *mp, *next_mp;
9852 	struct list_head *slp = &pring->postbufq;
9853 
9854 	/* Search postbufq, from the beginning, looking for a match on phys */
9855 	spin_lock_irq(&phba->hbalock);
9856 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
9857 		if (mp->phys == phys) {
9858 			list_del_init(&mp->list);
9859 			pring->postbufq_cnt--;
9860 			spin_unlock_irq(&phba->hbalock);
9861 			return mp;
9862 		}
9863 	}
9864 
9865 	spin_unlock_irq(&phba->hbalock);
9866 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9867 			"0410 Cannot find virtual addr for mapped buf on "
9868 			"ring %d Data x%llx x%p x%p x%x\n",
9869 			pring->ringno, (unsigned long long)phys,
9870 			slp->next, slp->prev, pring->postbufq_cnt);
9871 	return NULL;
9872 }
9873 
9874 /**
9875  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
9876  * @phba: Pointer to HBA context object.
9877  * @cmdiocb: Pointer to driver command iocb object.
9878  * @rspiocb: Pointer to driver response iocb object.
9879  *
9880  * This function is the completion handler for the abort iocbs for
9881  * ELS commands. This function is called from the ELS ring event
9882  * handler with no lock held. This function frees memory resources
9883  * associated with the abort iocb.
9884  **/
9885 static void
9886 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
9887 			struct lpfc_iocbq *rspiocb)
9888 {
9889 	IOCB_t *irsp = &rspiocb->iocb;
9890 	uint16_t abort_iotag, abort_context;
9891 	struct lpfc_iocbq *abort_iocb = NULL;
9892 
9893 	if (irsp->ulpStatus) {
9894 
9895 		/*
9896 		 * Assume that the port already completed and returned, or
9897 		 * will return the iocb. Just Log the message.
9898 		 */
9899 		abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
9900 		abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
9901 
9902 		spin_lock_irq(&phba->hbalock);
9903 		if (phba->sli_rev < LPFC_SLI_REV4) {
9904 			if (abort_iotag != 0 &&
9905 				abort_iotag <= phba->sli.last_iotag)
9906 				abort_iocb =
9907 					phba->sli.iocbq_lookup[abort_iotag];
9908 		} else
9909 			/* For sli4 the abort_tag is the XRI,
9910 			 * so the abort routine puts the iotag  of the iocb
9911 			 * being aborted in the context field of the abort
9912 			 * IOCB.
9913 			 */
9914 			abort_iocb = phba->sli.iocbq_lookup[abort_context];
9915 
9916 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
9917 				"0327 Cannot abort els iocb %p "
9918 				"with tag %x context %x, abort status %x, "
9919 				"abort code %x\n",
9920 				abort_iocb, abort_iotag, abort_context,
9921 				irsp->ulpStatus, irsp->un.ulpWord[4]);
9922 
9923 		spin_unlock_irq(&phba->hbalock);
9924 	}
9925 	lpfc_sli_release_iocbq(phba, cmdiocb);
9926 	return;
9927 }
9928 
9929 /**
9930  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
9931  * @phba: Pointer to HBA context object.
9932  * @cmdiocb: Pointer to driver command iocb object.
9933  * @rspiocb: Pointer to driver response iocb object.
9934  *
9935  * The function is called from SLI ring event handler with no
9936  * lock held. This function is the completion handler for ELS commands
9937  * which are aborted. The function frees memory resources used for
9938  * the aborted ELS commands.
9939  **/
9940 static void
9941 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
9942 		     struct lpfc_iocbq *rspiocb)
9943 {
9944 	IOCB_t *irsp = &rspiocb->iocb;
9945 
9946 	/* ELS cmd tag <ulpIoTag> completes */
9947 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
9948 			"0139 Ignoring ELS cmd tag x%x completion Data: "
9949 			"x%x x%x x%x\n",
9950 			irsp->ulpIoTag, irsp->ulpStatus,
9951 			irsp->un.ulpWord[4], irsp->ulpTimeout);
9952 	if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
9953 		lpfc_ct_free_iocb(phba, cmdiocb);
9954 	else
9955 		lpfc_els_free_iocb(phba, cmdiocb);
9956 	return;
9957 }
9958 
9959 /**
9960  * lpfc_sli_abort_iotag_issue - Issue abort for a command iocb
9961  * @phba: Pointer to HBA context object.
9962  * @pring: Pointer to driver SLI ring object.
9963  * @cmdiocb: Pointer to driver command iocb object.
9964  *
9965  * This function issues an abort iocb for the provided command iocb down to
9966  * the port. Other than the case the outstanding command iocb is an abort
9967  * request, this function issues abort out unconditionally. This function is
9968  * called with hbalock held. The function returns 0 when it fails due to
9969  * memory allocation failure or when the command iocb is an abort request.
9970  **/
9971 static int
9972 lpfc_sli_abort_iotag_issue(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9973 			   struct lpfc_iocbq *cmdiocb)
9974 {
9975 	struct lpfc_vport *vport = cmdiocb->vport;
9976 	struct lpfc_iocbq *abtsiocbp;
9977 	IOCB_t *icmd = NULL;
9978 	IOCB_t *iabt = NULL;
9979 	int ring_number;
9980 	int retval;
9981 	unsigned long iflags;
9982 
9983 	lockdep_assert_held(&phba->hbalock);
9984 
9985 	/*
9986 	 * There are certain command types we don't want to abort.  And we
9987 	 * don't want to abort commands that are already in the process of
9988 	 * being aborted.
9989 	 */
9990 	icmd = &cmdiocb->iocb;
9991 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
9992 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
9993 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
9994 		return 0;
9995 
9996 	/* issue ABTS for this IOCB based on iotag */
9997 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
9998 	if (abtsiocbp == NULL)
9999 		return 0;
10000 
10001 	/* This signals the response to set the correct status
10002 	 * before calling the completion handler
10003 	 */
10004 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
10005 
10006 	iabt = &abtsiocbp->iocb;
10007 	iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
10008 	iabt->un.acxri.abortContextTag = icmd->ulpContext;
10009 	if (phba->sli_rev == LPFC_SLI_REV4) {
10010 		iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
10011 		iabt->un.acxri.abortContextTag = cmdiocb->iotag;
10012 	}
10013 	else
10014 		iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
10015 	iabt->ulpLe = 1;
10016 	iabt->ulpClass = icmd->ulpClass;
10017 
10018 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
10019 	abtsiocbp->fcp_wqidx = cmdiocb->fcp_wqidx;
10020 	if (cmdiocb->iocb_flag & LPFC_IO_FCP)
10021 		abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
10022 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
10023 		abtsiocbp->iocb_flag |= LPFC_IO_FOF;
10024 
10025 	if (phba->link_state >= LPFC_LINK_UP)
10026 		iabt->ulpCommand = CMD_ABORT_XRI_CN;
10027 	else
10028 		iabt->ulpCommand = CMD_CLOSE_XRI_CN;
10029 
10030 	abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
10031 
10032 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
10033 			 "0339 Abort xri x%x, original iotag x%x, "
10034 			 "abort cmd iotag x%x\n",
10035 			 iabt->un.acxri.abortIoTag,
10036 			 iabt->un.acxri.abortContextTag,
10037 			 abtsiocbp->iotag);
10038 
10039 	if (phba->sli_rev == LPFC_SLI_REV4) {
10040 		ring_number =
10041 			lpfc_sli_calc_ring(phba, pring->ringno, abtsiocbp);
10042 		if (unlikely(ring_number == LPFC_HBA_ERROR))
10043 			return 0;
10044 		pring = &phba->sli.ring[ring_number];
10045 		/* Note: both hbalock and ring_lock need to be set here */
10046 		spin_lock_irqsave(&pring->ring_lock, iflags);
10047 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
10048 			abtsiocbp, 0);
10049 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
10050 	} else {
10051 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
10052 			abtsiocbp, 0);
10053 	}
10054 
10055 	if (retval)
10056 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
10057 
10058 	/*
10059 	 * Caller to this routine should check for IOCB_ERROR
10060 	 * and handle it properly.  This routine no longer removes
10061 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
10062 	 */
10063 	return retval;
10064 }
10065 
10066 /**
10067  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
10068  * @phba: Pointer to HBA context object.
10069  * @pring: Pointer to driver SLI ring object.
10070  * @cmdiocb: Pointer to driver command iocb object.
10071  *
10072  * This function issues an abort iocb for the provided command iocb. In case
10073  * of unloading, the abort iocb will not be issued to commands on the ELS
10074  * ring. Instead, the callback function shall be changed to those commands
10075  * so that nothing happens when them finishes. This function is called with
10076  * hbalock held. The function returns 0 when the command iocb is an abort
10077  * request.
10078  **/
10079 int
10080 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10081 			   struct lpfc_iocbq *cmdiocb)
10082 {
10083 	struct lpfc_vport *vport = cmdiocb->vport;
10084 	int retval = IOCB_ERROR;
10085 	IOCB_t *icmd = NULL;
10086 
10087 	lockdep_assert_held(&phba->hbalock);
10088 
10089 	/*
10090 	 * There are certain command types we don't want to abort.  And we
10091 	 * don't want to abort commands that are already in the process of
10092 	 * being aborted.
10093 	 */
10094 	icmd = &cmdiocb->iocb;
10095 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
10096 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
10097 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
10098 		return 0;
10099 
10100 	/*
10101 	 * If we're unloading, don't abort iocb on the ELS ring, but change
10102 	 * the callback so that nothing happens when it finishes.
10103 	 */
10104 	if ((vport->load_flag & FC_UNLOADING) &&
10105 	    (pring->ringno == LPFC_ELS_RING)) {
10106 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
10107 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
10108 		else
10109 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
10110 		goto abort_iotag_exit;
10111 	}
10112 
10113 	/* Now, we try to issue the abort to the cmdiocb out */
10114 	retval = lpfc_sli_abort_iotag_issue(phba, pring, cmdiocb);
10115 
10116 abort_iotag_exit:
10117 	/*
10118 	 * Caller to this routine should check for IOCB_ERROR
10119 	 * and handle it properly.  This routine no longer removes
10120 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
10121 	 */
10122 	return retval;
10123 }
10124 
10125 /**
10126  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
10127  * @phba: pointer to lpfc HBA data structure.
10128  *
10129  * This routine will abort all pending and outstanding iocbs to an HBA.
10130  **/
10131 void
10132 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
10133 {
10134 	struct lpfc_sli *psli = &phba->sli;
10135 	struct lpfc_sli_ring *pring;
10136 	int i;
10137 
10138 	for (i = 0; i < psli->num_rings; i++) {
10139 		pring = &psli->ring[i];
10140 		lpfc_sli_abort_iocb_ring(phba, pring);
10141 	}
10142 }
10143 
10144 /**
10145  * lpfc_sli_validate_fcp_iocb - find commands associated with a vport or LUN
10146  * @iocbq: Pointer to driver iocb object.
10147  * @vport: Pointer to driver virtual port object.
10148  * @tgt_id: SCSI ID of the target.
10149  * @lun_id: LUN ID of the scsi device.
10150  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
10151  *
10152  * This function acts as an iocb filter for functions which abort or count
10153  * all FCP iocbs pending on a lun/SCSI target/SCSI host. It will return
10154  * 0 if the filtering criteria is met for the given iocb and will return
10155  * 1 if the filtering criteria is not met.
10156  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
10157  * given iocb is for the SCSI device specified by vport, tgt_id and
10158  * lun_id parameter.
10159  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
10160  * given iocb is for the SCSI target specified by vport and tgt_id
10161  * parameters.
10162  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
10163  * given iocb is for the SCSI host associated with the given vport.
10164  * This function is called with no locks held.
10165  **/
10166 static int
10167 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
10168 			   uint16_t tgt_id, uint64_t lun_id,
10169 			   lpfc_ctx_cmd ctx_cmd)
10170 {
10171 	struct lpfc_scsi_buf *lpfc_cmd;
10172 	int rc = 1;
10173 
10174 	if (!(iocbq->iocb_flag &  LPFC_IO_FCP))
10175 		return rc;
10176 
10177 	if (iocbq->vport != vport)
10178 		return rc;
10179 
10180 	lpfc_cmd = container_of(iocbq, struct lpfc_scsi_buf, cur_iocbq);
10181 
10182 	if (lpfc_cmd->pCmd == NULL)
10183 		return rc;
10184 
10185 	switch (ctx_cmd) {
10186 	case LPFC_CTX_LUN:
10187 		if ((lpfc_cmd->rdata->pnode) &&
10188 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
10189 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
10190 			rc = 0;
10191 		break;
10192 	case LPFC_CTX_TGT:
10193 		if ((lpfc_cmd->rdata->pnode) &&
10194 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
10195 			rc = 0;
10196 		break;
10197 	case LPFC_CTX_HOST:
10198 		rc = 0;
10199 		break;
10200 	default:
10201 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
10202 			__func__, ctx_cmd);
10203 		break;
10204 	}
10205 
10206 	return rc;
10207 }
10208 
10209 /**
10210  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
10211  * @vport: Pointer to virtual port.
10212  * @tgt_id: SCSI ID of the target.
10213  * @lun_id: LUN ID of the scsi device.
10214  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
10215  *
10216  * This function returns number of FCP commands pending for the vport.
10217  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
10218  * commands pending on the vport associated with SCSI device specified
10219  * by tgt_id and lun_id parameters.
10220  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
10221  * commands pending on the vport associated with SCSI target specified
10222  * by tgt_id parameter.
10223  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
10224  * commands pending on the vport.
10225  * This function returns the number of iocbs which satisfy the filter.
10226  * This function is called without any lock held.
10227  **/
10228 int
10229 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
10230 		  lpfc_ctx_cmd ctx_cmd)
10231 {
10232 	struct lpfc_hba *phba = vport->phba;
10233 	struct lpfc_iocbq *iocbq;
10234 	int sum, i;
10235 
10236 	spin_lock_irq(&phba->hbalock);
10237 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
10238 		iocbq = phba->sli.iocbq_lookup[i];
10239 
10240 		if (lpfc_sli_validate_fcp_iocb (iocbq, vport, tgt_id, lun_id,
10241 						ctx_cmd) == 0)
10242 			sum++;
10243 	}
10244 	spin_unlock_irq(&phba->hbalock);
10245 
10246 	return sum;
10247 }
10248 
10249 /**
10250  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
10251  * @phba: Pointer to HBA context object
10252  * @cmdiocb: Pointer to command iocb object.
10253  * @rspiocb: Pointer to response iocb object.
10254  *
10255  * This function is called when an aborted FCP iocb completes. This
10256  * function is called by the ring event handler with no lock held.
10257  * This function frees the iocb.
10258  **/
10259 void
10260 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
10261 			struct lpfc_iocbq *rspiocb)
10262 {
10263 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10264 			"3096 ABORT_XRI_CN completing on rpi x%x "
10265 			"original iotag x%x, abort cmd iotag x%x "
10266 			"status 0x%x, reason 0x%x\n",
10267 			cmdiocb->iocb.un.acxri.abortContextTag,
10268 			cmdiocb->iocb.un.acxri.abortIoTag,
10269 			cmdiocb->iotag, rspiocb->iocb.ulpStatus,
10270 			rspiocb->iocb.un.ulpWord[4]);
10271 	lpfc_sli_release_iocbq(phba, cmdiocb);
10272 	return;
10273 }
10274 
10275 /**
10276  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
10277  * @vport: Pointer to virtual port.
10278  * @pring: Pointer to driver SLI ring object.
10279  * @tgt_id: SCSI ID of the target.
10280  * @lun_id: LUN ID of the scsi device.
10281  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
10282  *
10283  * This function sends an abort command for every SCSI command
10284  * associated with the given virtual port pending on the ring
10285  * filtered by lpfc_sli_validate_fcp_iocb function.
10286  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
10287  * FCP iocbs associated with lun specified by tgt_id and lun_id
10288  * parameters
10289  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
10290  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
10291  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
10292  * FCP iocbs associated with virtual port.
10293  * This function returns number of iocbs it failed to abort.
10294  * This function is called with no locks held.
10295  **/
10296 int
10297 lpfc_sli_abort_iocb(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
10298 		    uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd abort_cmd)
10299 {
10300 	struct lpfc_hba *phba = vport->phba;
10301 	struct lpfc_iocbq *iocbq;
10302 	struct lpfc_iocbq *abtsiocb;
10303 	IOCB_t *cmd = NULL;
10304 	int errcnt = 0, ret_val = 0;
10305 	int i;
10306 
10307 	for (i = 1; i <= phba->sli.last_iotag; i++) {
10308 		iocbq = phba->sli.iocbq_lookup[i];
10309 
10310 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
10311 					       abort_cmd) != 0)
10312 			continue;
10313 
10314 		/*
10315 		 * If the iocbq is already being aborted, don't take a second
10316 		 * action, but do count it.
10317 		 */
10318 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
10319 			continue;
10320 
10321 		/* issue ABTS for this IOCB based on iotag */
10322 		abtsiocb = lpfc_sli_get_iocbq(phba);
10323 		if (abtsiocb == NULL) {
10324 			errcnt++;
10325 			continue;
10326 		}
10327 
10328 		/* indicate the IO is being aborted by the driver. */
10329 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
10330 
10331 		cmd = &iocbq->iocb;
10332 		abtsiocb->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
10333 		abtsiocb->iocb.un.acxri.abortContextTag = cmd->ulpContext;
10334 		if (phba->sli_rev == LPFC_SLI_REV4)
10335 			abtsiocb->iocb.un.acxri.abortIoTag = iocbq->sli4_xritag;
10336 		else
10337 			abtsiocb->iocb.un.acxri.abortIoTag = cmd->ulpIoTag;
10338 		abtsiocb->iocb.ulpLe = 1;
10339 		abtsiocb->iocb.ulpClass = cmd->ulpClass;
10340 		abtsiocb->vport = vport;
10341 
10342 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
10343 		abtsiocb->fcp_wqidx = iocbq->fcp_wqidx;
10344 		if (iocbq->iocb_flag & LPFC_IO_FCP)
10345 			abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
10346 		if (iocbq->iocb_flag & LPFC_IO_FOF)
10347 			abtsiocb->iocb_flag |= LPFC_IO_FOF;
10348 
10349 		if (lpfc_is_link_up(phba))
10350 			abtsiocb->iocb.ulpCommand = CMD_ABORT_XRI_CN;
10351 		else
10352 			abtsiocb->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
10353 
10354 		/* Setup callback routine and issue the command. */
10355 		abtsiocb->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
10356 		ret_val = lpfc_sli_issue_iocb(phba, pring->ringno,
10357 					      abtsiocb, 0);
10358 		if (ret_val == IOCB_ERROR) {
10359 			lpfc_sli_release_iocbq(phba, abtsiocb);
10360 			errcnt++;
10361 			continue;
10362 		}
10363 	}
10364 
10365 	return errcnt;
10366 }
10367 
10368 /**
10369  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
10370  * @vport: Pointer to virtual port.
10371  * @pring: Pointer to driver SLI ring object.
10372  * @tgt_id: SCSI ID of the target.
10373  * @lun_id: LUN ID of the scsi device.
10374  * @taskmgmt_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
10375  *
10376  * This function sends an abort command for every SCSI command
10377  * associated with the given virtual port pending on the ring
10378  * filtered by lpfc_sli_validate_fcp_iocb function.
10379  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
10380  * FCP iocbs associated with lun specified by tgt_id and lun_id
10381  * parameters
10382  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
10383  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
10384  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
10385  * FCP iocbs associated with virtual port.
10386  * This function returns number of iocbs it aborted .
10387  * This function is called with no locks held right after a taskmgmt
10388  * command is sent.
10389  **/
10390 int
10391 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
10392 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
10393 {
10394 	struct lpfc_hba *phba = vport->phba;
10395 	struct lpfc_scsi_buf *lpfc_cmd;
10396 	struct lpfc_iocbq *abtsiocbq;
10397 	struct lpfc_nodelist *ndlp;
10398 	struct lpfc_iocbq *iocbq;
10399 	IOCB_t *icmd;
10400 	int sum, i, ret_val;
10401 	unsigned long iflags;
10402 	struct lpfc_sli_ring *pring_s4;
10403 	uint32_t ring_number;
10404 
10405 	spin_lock_irq(&phba->hbalock);
10406 
10407 	/* all I/Os are in process of being flushed */
10408 	if (phba->hba_flag & HBA_FCP_IOQ_FLUSH) {
10409 		spin_unlock_irq(&phba->hbalock);
10410 		return 0;
10411 	}
10412 	sum = 0;
10413 
10414 	for (i = 1; i <= phba->sli.last_iotag; i++) {
10415 		iocbq = phba->sli.iocbq_lookup[i];
10416 
10417 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
10418 					       cmd) != 0)
10419 			continue;
10420 
10421 		/*
10422 		 * If the iocbq is already being aborted, don't take a second
10423 		 * action, but do count it.
10424 		 */
10425 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
10426 			continue;
10427 
10428 		/* issue ABTS for this IOCB based on iotag */
10429 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
10430 		if (abtsiocbq == NULL)
10431 			continue;
10432 
10433 		icmd = &iocbq->iocb;
10434 		abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
10435 		abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
10436 		if (phba->sli_rev == LPFC_SLI_REV4)
10437 			abtsiocbq->iocb.un.acxri.abortIoTag =
10438 							 iocbq->sli4_xritag;
10439 		else
10440 			abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
10441 		abtsiocbq->iocb.ulpLe = 1;
10442 		abtsiocbq->iocb.ulpClass = icmd->ulpClass;
10443 		abtsiocbq->vport = vport;
10444 
10445 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
10446 		abtsiocbq->fcp_wqidx = iocbq->fcp_wqidx;
10447 		if (iocbq->iocb_flag & LPFC_IO_FCP)
10448 			abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
10449 		if (iocbq->iocb_flag & LPFC_IO_FOF)
10450 			abtsiocbq->iocb_flag |= LPFC_IO_FOF;
10451 
10452 		lpfc_cmd = container_of(iocbq, struct lpfc_scsi_buf, cur_iocbq);
10453 		ndlp = lpfc_cmd->rdata->pnode;
10454 
10455 		if (lpfc_is_link_up(phba) &&
10456 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
10457 			abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
10458 		else
10459 			abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
10460 
10461 		/* Setup callback routine and issue the command. */
10462 		abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
10463 
10464 		/*
10465 		 * Indicate the IO is being aborted by the driver and set
10466 		 * the caller's flag into the aborted IO.
10467 		 */
10468 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
10469 
10470 		if (phba->sli_rev == LPFC_SLI_REV4) {
10471 			ring_number = MAX_SLI3_CONFIGURED_RINGS +
10472 					 iocbq->fcp_wqidx;
10473 			pring_s4 = &phba->sli.ring[ring_number];
10474 			/* Note: both hbalock and ring_lock must be set here */
10475 			spin_lock_irqsave(&pring_s4->ring_lock, iflags);
10476 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
10477 							abtsiocbq, 0);
10478 			spin_unlock_irqrestore(&pring_s4->ring_lock, iflags);
10479 		} else {
10480 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
10481 							abtsiocbq, 0);
10482 		}
10483 
10484 
10485 		if (ret_val == IOCB_ERROR)
10486 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
10487 		else
10488 			sum++;
10489 	}
10490 	spin_unlock_irq(&phba->hbalock);
10491 	return sum;
10492 }
10493 
10494 /**
10495  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
10496  * @phba: Pointer to HBA context object.
10497  * @cmdiocbq: Pointer to command iocb.
10498  * @rspiocbq: Pointer to response iocb.
10499  *
10500  * This function is the completion handler for iocbs issued using
10501  * lpfc_sli_issue_iocb_wait function. This function is called by the
10502  * ring event handler function without any lock held. This function
10503  * can be called from both worker thread context and interrupt
10504  * context. This function also can be called from other thread which
10505  * cleans up the SLI layer objects.
10506  * This function copy the contents of the response iocb to the
10507  * response iocb memory object provided by the caller of
10508  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
10509  * sleeps for the iocb completion.
10510  **/
10511 static void
10512 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
10513 			struct lpfc_iocbq *cmdiocbq,
10514 			struct lpfc_iocbq *rspiocbq)
10515 {
10516 	wait_queue_head_t *pdone_q;
10517 	unsigned long iflags;
10518 	struct lpfc_scsi_buf *lpfc_cmd;
10519 
10520 	spin_lock_irqsave(&phba->hbalock, iflags);
10521 	if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
10522 
10523 		/*
10524 		 * A time out has occurred for the iocb.  If a time out
10525 		 * completion handler has been supplied, call it.  Otherwise,
10526 		 * just free the iocbq.
10527 		 */
10528 
10529 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10530 		cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
10531 		cmdiocbq->wait_iocb_cmpl = NULL;
10532 		if (cmdiocbq->iocb_cmpl)
10533 			(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
10534 		else
10535 			lpfc_sli_release_iocbq(phba, cmdiocbq);
10536 		return;
10537 	}
10538 
10539 	cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
10540 	if (cmdiocbq->context2 && rspiocbq)
10541 		memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
10542 		       &rspiocbq->iocb, sizeof(IOCB_t));
10543 
10544 	/* Set the exchange busy flag for task management commands */
10545 	if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
10546 		!(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
10547 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_scsi_buf,
10548 			cur_iocbq);
10549 		lpfc_cmd->exch_busy = rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY;
10550 	}
10551 
10552 	pdone_q = cmdiocbq->context_un.wait_queue;
10553 	if (pdone_q)
10554 		wake_up(pdone_q);
10555 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10556 	return;
10557 }
10558 
10559 /**
10560  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
10561  * @phba: Pointer to HBA context object..
10562  * @piocbq: Pointer to command iocb.
10563  * @flag: Flag to test.
10564  *
10565  * This routine grabs the hbalock and then test the iocb_flag to
10566  * see if the passed in flag is set.
10567  * Returns:
10568  * 1 if flag is set.
10569  * 0 if flag is not set.
10570  **/
10571 static int
10572 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
10573 		 struct lpfc_iocbq *piocbq, uint32_t flag)
10574 {
10575 	unsigned long iflags;
10576 	int ret;
10577 
10578 	spin_lock_irqsave(&phba->hbalock, iflags);
10579 	ret = piocbq->iocb_flag & flag;
10580 	spin_unlock_irqrestore(&phba->hbalock, iflags);
10581 	return ret;
10582 
10583 }
10584 
10585 /**
10586  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
10587  * @phba: Pointer to HBA context object..
10588  * @pring: Pointer to sli ring.
10589  * @piocb: Pointer to command iocb.
10590  * @prspiocbq: Pointer to response iocb.
10591  * @timeout: Timeout in number of seconds.
10592  *
10593  * This function issues the iocb to firmware and waits for the
10594  * iocb to complete. The iocb_cmpl field of the shall be used
10595  * to handle iocbs which time out. If the field is NULL, the
10596  * function shall free the iocbq structure.  If more clean up is
10597  * needed, the caller is expected to provide a completion function
10598  * that will provide the needed clean up.  If the iocb command is
10599  * not completed within timeout seconds, the function will either
10600  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
10601  * completion function set in the iocb_cmpl field and then return
10602  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
10603  * resources if this function returns IOCB_TIMEDOUT.
10604  * The function waits for the iocb completion using an
10605  * non-interruptible wait.
10606  * This function will sleep while waiting for iocb completion.
10607  * So, this function should not be called from any context which
10608  * does not allow sleeping. Due to the same reason, this function
10609  * cannot be called with interrupt disabled.
10610  * This function assumes that the iocb completions occur while
10611  * this function sleep. So, this function cannot be called from
10612  * the thread which process iocb completion for this ring.
10613  * This function clears the iocb_flag of the iocb object before
10614  * issuing the iocb and the iocb completion handler sets this
10615  * flag and wakes this thread when the iocb completes.
10616  * The contents of the response iocb will be copied to prspiocbq
10617  * by the completion handler when the command completes.
10618  * This function returns IOCB_SUCCESS when success.
10619  * This function is called with no lock held.
10620  **/
10621 int
10622 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
10623 			 uint32_t ring_number,
10624 			 struct lpfc_iocbq *piocb,
10625 			 struct lpfc_iocbq *prspiocbq,
10626 			 uint32_t timeout)
10627 {
10628 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
10629 	long timeleft, timeout_req = 0;
10630 	int retval = IOCB_SUCCESS;
10631 	uint32_t creg_val;
10632 	struct lpfc_iocbq *iocb;
10633 	int txq_cnt = 0;
10634 	int txcmplq_cnt = 0;
10635 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
10636 	unsigned long iflags;
10637 	bool iocb_completed = true;
10638 
10639 	/*
10640 	 * If the caller has provided a response iocbq buffer, then context2
10641 	 * is NULL or its an error.
10642 	 */
10643 	if (prspiocbq) {
10644 		if (piocb->context2)
10645 			return IOCB_ERROR;
10646 		piocb->context2 = prspiocbq;
10647 	}
10648 
10649 	piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
10650 	piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
10651 	piocb->context_un.wait_queue = &done_q;
10652 	piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
10653 
10654 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
10655 		if (lpfc_readl(phba->HCregaddr, &creg_val))
10656 			return IOCB_ERROR;
10657 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
10658 		writel(creg_val, phba->HCregaddr);
10659 		readl(phba->HCregaddr); /* flush */
10660 	}
10661 
10662 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
10663 				     SLI_IOCB_RET_IOCB);
10664 	if (retval == IOCB_SUCCESS) {
10665 		timeout_req = msecs_to_jiffies(timeout * 1000);
10666 		timeleft = wait_event_timeout(done_q,
10667 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
10668 				timeout_req);
10669 		spin_lock_irqsave(&phba->hbalock, iflags);
10670 		if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
10671 
10672 			/*
10673 			 * IOCB timed out.  Inform the wake iocb wait
10674 			 * completion function and set local status
10675 			 */
10676 
10677 			iocb_completed = false;
10678 			piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
10679 		}
10680 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10681 		if (iocb_completed) {
10682 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10683 					"0331 IOCB wake signaled\n");
10684 			/* Note: we are not indicating if the IOCB has a success
10685 			 * status or not - that's for the caller to check.
10686 			 * IOCB_SUCCESS means just that the command was sent and
10687 			 * completed. Not that it completed successfully.
10688 			 * */
10689 		} else if (timeleft == 0) {
10690 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10691 					"0338 IOCB wait timeout error - no "
10692 					"wake response Data x%x\n", timeout);
10693 			retval = IOCB_TIMEDOUT;
10694 		} else {
10695 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10696 					"0330 IOCB wake NOT set, "
10697 					"Data x%x x%lx\n",
10698 					timeout, (timeleft / jiffies));
10699 			retval = IOCB_TIMEDOUT;
10700 		}
10701 	} else if (retval == IOCB_BUSY) {
10702 		if (phba->cfg_log_verbose & LOG_SLI) {
10703 			list_for_each_entry(iocb, &pring->txq, list) {
10704 				txq_cnt++;
10705 			}
10706 			list_for_each_entry(iocb, &pring->txcmplq, list) {
10707 				txcmplq_cnt++;
10708 			}
10709 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10710 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
10711 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
10712 		}
10713 		return retval;
10714 	} else {
10715 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10716 				"0332 IOCB wait issue failed, Data x%x\n",
10717 				retval);
10718 		retval = IOCB_ERROR;
10719 	}
10720 
10721 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
10722 		if (lpfc_readl(phba->HCregaddr, &creg_val))
10723 			return IOCB_ERROR;
10724 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
10725 		writel(creg_val, phba->HCregaddr);
10726 		readl(phba->HCregaddr); /* flush */
10727 	}
10728 
10729 	if (prspiocbq)
10730 		piocb->context2 = NULL;
10731 
10732 	piocb->context_un.wait_queue = NULL;
10733 	piocb->iocb_cmpl = NULL;
10734 	return retval;
10735 }
10736 
10737 /**
10738  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
10739  * @phba: Pointer to HBA context object.
10740  * @pmboxq: Pointer to driver mailbox object.
10741  * @timeout: Timeout in number of seconds.
10742  *
10743  * This function issues the mailbox to firmware and waits for the
10744  * mailbox command to complete. If the mailbox command is not
10745  * completed within timeout seconds, it returns MBX_TIMEOUT.
10746  * The function waits for the mailbox completion using an
10747  * interruptible wait. If the thread is woken up due to a
10748  * signal, MBX_TIMEOUT error is returned to the caller. Caller
10749  * should not free the mailbox resources, if this function returns
10750  * MBX_TIMEOUT.
10751  * This function will sleep while waiting for mailbox completion.
10752  * So, this function should not be called from any context which
10753  * does not allow sleeping. Due to the same reason, this function
10754  * cannot be called with interrupt disabled.
10755  * This function assumes that the mailbox completion occurs while
10756  * this function sleep. So, this function cannot be called from
10757  * the worker thread which processes mailbox completion.
10758  * This function is called in the context of HBA management
10759  * applications.
10760  * This function returns MBX_SUCCESS when successful.
10761  * This function is called with no lock held.
10762  **/
10763 int
10764 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
10765 			 uint32_t timeout)
10766 {
10767 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
10768 	MAILBOX_t *mb = NULL;
10769 	int retval;
10770 	unsigned long flag;
10771 
10772 	/* The caller might set context1 for extended buffer */
10773 	if (pmboxq->context1)
10774 		mb = (MAILBOX_t *)pmboxq->context1;
10775 
10776 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
10777 	/* setup wake call as IOCB callback */
10778 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
10779 	/* setup context field to pass wait_queue pointer to wake function  */
10780 	pmboxq->context1 = &done_q;
10781 
10782 	/* now issue the command */
10783 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
10784 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
10785 		wait_event_interruptible_timeout(done_q,
10786 				pmboxq->mbox_flag & LPFC_MBX_WAKE,
10787 				msecs_to_jiffies(timeout * 1000));
10788 
10789 		spin_lock_irqsave(&phba->hbalock, flag);
10790 		/* restore the possible extended buffer for free resource */
10791 		pmboxq->context1 = (uint8_t *)mb;
10792 		/*
10793 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
10794 		 * else do not free the resources.
10795 		 */
10796 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
10797 			retval = MBX_SUCCESS;
10798 		} else {
10799 			retval = MBX_TIMEOUT;
10800 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
10801 		}
10802 		spin_unlock_irqrestore(&phba->hbalock, flag);
10803 	} else {
10804 		/* restore the possible extended buffer for free resource */
10805 		pmboxq->context1 = (uint8_t *)mb;
10806 	}
10807 
10808 	return retval;
10809 }
10810 
10811 /**
10812  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
10813  * @phba: Pointer to HBA context.
10814  *
10815  * This function is called to shutdown the driver's mailbox sub-system.
10816  * It first marks the mailbox sub-system is in a block state to prevent
10817  * the asynchronous mailbox command from issued off the pending mailbox
10818  * command queue. If the mailbox command sub-system shutdown is due to
10819  * HBA error conditions such as EEH or ERATT, this routine shall invoke
10820  * the mailbox sub-system flush routine to forcefully bring down the
10821  * mailbox sub-system. Otherwise, if it is due to normal condition (such
10822  * as with offline or HBA function reset), this routine will wait for the
10823  * outstanding mailbox command to complete before invoking the mailbox
10824  * sub-system flush routine to gracefully bring down mailbox sub-system.
10825  **/
10826 void
10827 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
10828 {
10829 	struct lpfc_sli *psli = &phba->sli;
10830 	unsigned long timeout;
10831 
10832 	if (mbx_action == LPFC_MBX_NO_WAIT) {
10833 		/* delay 100ms for port state */
10834 		msleep(100);
10835 		lpfc_sli_mbox_sys_flush(phba);
10836 		return;
10837 	}
10838 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
10839 
10840 	spin_lock_irq(&phba->hbalock);
10841 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
10842 
10843 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
10844 		/* Determine how long we might wait for the active mailbox
10845 		 * command to be gracefully completed by firmware.
10846 		 */
10847 		if (phba->sli.mbox_active)
10848 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
10849 						phba->sli.mbox_active) *
10850 						1000) + jiffies;
10851 		spin_unlock_irq(&phba->hbalock);
10852 
10853 		while (phba->sli.mbox_active) {
10854 			/* Check active mailbox complete status every 2ms */
10855 			msleep(2);
10856 			if (time_after(jiffies, timeout))
10857 				/* Timeout, let the mailbox flush routine to
10858 				 * forcefully release active mailbox command
10859 				 */
10860 				break;
10861 		}
10862 	} else
10863 		spin_unlock_irq(&phba->hbalock);
10864 
10865 	lpfc_sli_mbox_sys_flush(phba);
10866 }
10867 
10868 /**
10869  * lpfc_sli_eratt_read - read sli-3 error attention events
10870  * @phba: Pointer to HBA context.
10871  *
10872  * This function is called to read the SLI3 device error attention registers
10873  * for possible error attention events. The caller must hold the hostlock
10874  * with spin_lock_irq().
10875  *
10876  * This function returns 1 when there is Error Attention in the Host Attention
10877  * Register and returns 0 otherwise.
10878  **/
10879 static int
10880 lpfc_sli_eratt_read(struct lpfc_hba *phba)
10881 {
10882 	uint32_t ha_copy;
10883 
10884 	/* Read chip Host Attention (HA) register */
10885 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
10886 		goto unplug_err;
10887 
10888 	if (ha_copy & HA_ERATT) {
10889 		/* Read host status register to retrieve error event */
10890 		if (lpfc_sli_read_hs(phba))
10891 			goto unplug_err;
10892 
10893 		/* Check if there is a deferred error condition is active */
10894 		if ((HS_FFER1 & phba->work_hs) &&
10895 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
10896 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
10897 			phba->hba_flag |= DEFER_ERATT;
10898 			/* Clear all interrupt enable conditions */
10899 			writel(0, phba->HCregaddr);
10900 			readl(phba->HCregaddr);
10901 		}
10902 
10903 		/* Set the driver HA work bitmap */
10904 		phba->work_ha |= HA_ERATT;
10905 		/* Indicate polling handles this ERATT */
10906 		phba->hba_flag |= HBA_ERATT_HANDLED;
10907 		return 1;
10908 	}
10909 	return 0;
10910 
10911 unplug_err:
10912 	/* Set the driver HS work bitmap */
10913 	phba->work_hs |= UNPLUG_ERR;
10914 	/* Set the driver HA work bitmap */
10915 	phba->work_ha |= HA_ERATT;
10916 	/* Indicate polling handles this ERATT */
10917 	phba->hba_flag |= HBA_ERATT_HANDLED;
10918 	return 1;
10919 }
10920 
10921 /**
10922  * lpfc_sli4_eratt_read - read sli-4 error attention events
10923  * @phba: Pointer to HBA context.
10924  *
10925  * This function is called to read the SLI4 device error attention registers
10926  * for possible error attention events. The caller must hold the hostlock
10927  * with spin_lock_irq().
10928  *
10929  * This function returns 1 when there is Error Attention in the Host Attention
10930  * Register and returns 0 otherwise.
10931  **/
10932 static int
10933 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
10934 {
10935 	uint32_t uerr_sta_hi, uerr_sta_lo;
10936 	uint32_t if_type, portsmphr;
10937 	struct lpfc_register portstat_reg;
10938 
10939 	/*
10940 	 * For now, use the SLI4 device internal unrecoverable error
10941 	 * registers for error attention. This can be changed later.
10942 	 */
10943 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
10944 	switch (if_type) {
10945 	case LPFC_SLI_INTF_IF_TYPE_0:
10946 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
10947 			&uerr_sta_lo) ||
10948 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
10949 			&uerr_sta_hi)) {
10950 			phba->work_hs |= UNPLUG_ERR;
10951 			phba->work_ha |= HA_ERATT;
10952 			phba->hba_flag |= HBA_ERATT_HANDLED;
10953 			return 1;
10954 		}
10955 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
10956 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
10957 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10958 					"1423 HBA Unrecoverable error: "
10959 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
10960 					"ue_mask_lo_reg=0x%x, "
10961 					"ue_mask_hi_reg=0x%x\n",
10962 					uerr_sta_lo, uerr_sta_hi,
10963 					phba->sli4_hba.ue_mask_lo,
10964 					phba->sli4_hba.ue_mask_hi);
10965 			phba->work_status[0] = uerr_sta_lo;
10966 			phba->work_status[1] = uerr_sta_hi;
10967 			phba->work_ha |= HA_ERATT;
10968 			phba->hba_flag |= HBA_ERATT_HANDLED;
10969 			return 1;
10970 		}
10971 		break;
10972 	case LPFC_SLI_INTF_IF_TYPE_2:
10973 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
10974 			&portstat_reg.word0) ||
10975 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
10976 			&portsmphr)){
10977 			phba->work_hs |= UNPLUG_ERR;
10978 			phba->work_ha |= HA_ERATT;
10979 			phba->hba_flag |= HBA_ERATT_HANDLED;
10980 			return 1;
10981 		}
10982 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
10983 			phba->work_status[0] =
10984 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
10985 			phba->work_status[1] =
10986 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
10987 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10988 					"2885 Port Status Event: "
10989 					"port status reg 0x%x, "
10990 					"port smphr reg 0x%x, "
10991 					"error 1=0x%x, error 2=0x%x\n",
10992 					portstat_reg.word0,
10993 					portsmphr,
10994 					phba->work_status[0],
10995 					phba->work_status[1]);
10996 			phba->work_ha |= HA_ERATT;
10997 			phba->hba_flag |= HBA_ERATT_HANDLED;
10998 			return 1;
10999 		}
11000 		break;
11001 	case LPFC_SLI_INTF_IF_TYPE_1:
11002 	default:
11003 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11004 				"2886 HBA Error Attention on unsupported "
11005 				"if type %d.", if_type);
11006 		return 1;
11007 	}
11008 
11009 	return 0;
11010 }
11011 
11012 /**
11013  * lpfc_sli_check_eratt - check error attention events
11014  * @phba: Pointer to HBA context.
11015  *
11016  * This function is called from timer soft interrupt context to check HBA's
11017  * error attention register bit for error attention events.
11018  *
11019  * This function returns 1 when there is Error Attention in the Host Attention
11020  * Register and returns 0 otherwise.
11021  **/
11022 int
11023 lpfc_sli_check_eratt(struct lpfc_hba *phba)
11024 {
11025 	uint32_t ha_copy;
11026 
11027 	/* If somebody is waiting to handle an eratt, don't process it
11028 	 * here. The brdkill function will do this.
11029 	 */
11030 	if (phba->link_flag & LS_IGNORE_ERATT)
11031 		return 0;
11032 
11033 	/* Check if interrupt handler handles this ERATT */
11034 	spin_lock_irq(&phba->hbalock);
11035 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
11036 		/* Interrupt handler has handled ERATT */
11037 		spin_unlock_irq(&phba->hbalock);
11038 		return 0;
11039 	}
11040 
11041 	/*
11042 	 * If there is deferred error attention, do not check for error
11043 	 * attention
11044 	 */
11045 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11046 		spin_unlock_irq(&phba->hbalock);
11047 		return 0;
11048 	}
11049 
11050 	/* If PCI channel is offline, don't process it */
11051 	if (unlikely(pci_channel_offline(phba->pcidev))) {
11052 		spin_unlock_irq(&phba->hbalock);
11053 		return 0;
11054 	}
11055 
11056 	switch (phba->sli_rev) {
11057 	case LPFC_SLI_REV2:
11058 	case LPFC_SLI_REV3:
11059 		/* Read chip Host Attention (HA) register */
11060 		ha_copy = lpfc_sli_eratt_read(phba);
11061 		break;
11062 	case LPFC_SLI_REV4:
11063 		/* Read device Uncoverable Error (UERR) registers */
11064 		ha_copy = lpfc_sli4_eratt_read(phba);
11065 		break;
11066 	default:
11067 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11068 				"0299 Invalid SLI revision (%d)\n",
11069 				phba->sli_rev);
11070 		ha_copy = 0;
11071 		break;
11072 	}
11073 	spin_unlock_irq(&phba->hbalock);
11074 
11075 	return ha_copy;
11076 }
11077 
11078 /**
11079  * lpfc_intr_state_check - Check device state for interrupt handling
11080  * @phba: Pointer to HBA context.
11081  *
11082  * This inline routine checks whether a device or its PCI slot is in a state
11083  * that the interrupt should be handled.
11084  *
11085  * This function returns 0 if the device or the PCI slot is in a state that
11086  * interrupt should be handled, otherwise -EIO.
11087  */
11088 static inline int
11089 lpfc_intr_state_check(struct lpfc_hba *phba)
11090 {
11091 	/* If the pci channel is offline, ignore all the interrupts */
11092 	if (unlikely(pci_channel_offline(phba->pcidev)))
11093 		return -EIO;
11094 
11095 	/* Update device level interrupt statistics */
11096 	phba->sli.slistat.sli_intr++;
11097 
11098 	/* Ignore all interrupts during initialization. */
11099 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
11100 		return -EIO;
11101 
11102 	return 0;
11103 }
11104 
11105 /**
11106  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
11107  * @irq: Interrupt number.
11108  * @dev_id: The device context pointer.
11109  *
11110  * This function is directly called from the PCI layer as an interrupt
11111  * service routine when device with SLI-3 interface spec is enabled with
11112  * MSI-X multi-message interrupt mode and there are slow-path events in
11113  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
11114  * interrupt mode, this function is called as part of the device-level
11115  * interrupt handler. When the PCI slot is in error recovery or the HBA
11116  * is undergoing initialization, the interrupt handler will not process
11117  * the interrupt. The link attention and ELS ring attention events are
11118  * handled by the worker thread. The interrupt handler signals the worker
11119  * thread and returns for these events. This function is called without
11120  * any lock held. It gets the hbalock to access and update SLI data
11121  * structures.
11122  *
11123  * This function returns IRQ_HANDLED when interrupt is handled else it
11124  * returns IRQ_NONE.
11125  **/
11126 irqreturn_t
11127 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
11128 {
11129 	struct lpfc_hba  *phba;
11130 	uint32_t ha_copy, hc_copy;
11131 	uint32_t work_ha_copy;
11132 	unsigned long status;
11133 	unsigned long iflag;
11134 	uint32_t control;
11135 
11136 	MAILBOX_t *mbox, *pmbox;
11137 	struct lpfc_vport *vport;
11138 	struct lpfc_nodelist *ndlp;
11139 	struct lpfc_dmabuf *mp;
11140 	LPFC_MBOXQ_t *pmb;
11141 	int rc;
11142 
11143 	/*
11144 	 * Get the driver's phba structure from the dev_id and
11145 	 * assume the HBA is not interrupting.
11146 	 */
11147 	phba = (struct lpfc_hba *)dev_id;
11148 
11149 	if (unlikely(!phba))
11150 		return IRQ_NONE;
11151 
11152 	/*
11153 	 * Stuff needs to be attented to when this function is invoked as an
11154 	 * individual interrupt handler in MSI-X multi-message interrupt mode
11155 	 */
11156 	if (phba->intr_type == MSIX) {
11157 		/* Check device state for handling interrupt */
11158 		if (lpfc_intr_state_check(phba))
11159 			return IRQ_NONE;
11160 		/* Need to read HA REG for slow-path events */
11161 		spin_lock_irqsave(&phba->hbalock, iflag);
11162 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
11163 			goto unplug_error;
11164 		/* If somebody is waiting to handle an eratt don't process it
11165 		 * here. The brdkill function will do this.
11166 		 */
11167 		if (phba->link_flag & LS_IGNORE_ERATT)
11168 			ha_copy &= ~HA_ERATT;
11169 		/* Check the need for handling ERATT in interrupt handler */
11170 		if (ha_copy & HA_ERATT) {
11171 			if (phba->hba_flag & HBA_ERATT_HANDLED)
11172 				/* ERATT polling has handled ERATT */
11173 				ha_copy &= ~HA_ERATT;
11174 			else
11175 				/* Indicate interrupt handler handles ERATT */
11176 				phba->hba_flag |= HBA_ERATT_HANDLED;
11177 		}
11178 
11179 		/*
11180 		 * If there is deferred error attention, do not check for any
11181 		 * interrupt.
11182 		 */
11183 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11184 			spin_unlock_irqrestore(&phba->hbalock, iflag);
11185 			return IRQ_NONE;
11186 		}
11187 
11188 		/* Clear up only attention source related to slow-path */
11189 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
11190 			goto unplug_error;
11191 
11192 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
11193 			HC_LAINT_ENA | HC_ERINT_ENA),
11194 			phba->HCregaddr);
11195 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
11196 			phba->HAregaddr);
11197 		writel(hc_copy, phba->HCregaddr);
11198 		readl(phba->HAregaddr); /* flush */
11199 		spin_unlock_irqrestore(&phba->hbalock, iflag);
11200 	} else
11201 		ha_copy = phba->ha_copy;
11202 
11203 	work_ha_copy = ha_copy & phba->work_ha_mask;
11204 
11205 	if (work_ha_copy) {
11206 		if (work_ha_copy & HA_LATT) {
11207 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
11208 				/*
11209 				 * Turn off Link Attention interrupts
11210 				 * until CLEAR_LA done
11211 				 */
11212 				spin_lock_irqsave(&phba->hbalock, iflag);
11213 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
11214 				if (lpfc_readl(phba->HCregaddr, &control))
11215 					goto unplug_error;
11216 				control &= ~HC_LAINT_ENA;
11217 				writel(control, phba->HCregaddr);
11218 				readl(phba->HCregaddr); /* flush */
11219 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11220 			}
11221 			else
11222 				work_ha_copy &= ~HA_LATT;
11223 		}
11224 
11225 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
11226 			/*
11227 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
11228 			 * the only slow ring.
11229 			 */
11230 			status = (work_ha_copy &
11231 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
11232 			status >>= (4*LPFC_ELS_RING);
11233 			if (status & HA_RXMASK) {
11234 				spin_lock_irqsave(&phba->hbalock, iflag);
11235 				if (lpfc_readl(phba->HCregaddr, &control))
11236 					goto unplug_error;
11237 
11238 				lpfc_debugfs_slow_ring_trc(phba,
11239 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
11240 				control, status,
11241 				(uint32_t)phba->sli.slistat.sli_intr);
11242 
11243 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
11244 					lpfc_debugfs_slow_ring_trc(phba,
11245 						"ISR Disable ring:"
11246 						"pwork:x%x hawork:x%x wait:x%x",
11247 						phba->work_ha, work_ha_copy,
11248 						(uint32_t)((unsigned long)
11249 						&phba->work_waitq));
11250 
11251 					control &=
11252 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
11253 					writel(control, phba->HCregaddr);
11254 					readl(phba->HCregaddr); /* flush */
11255 				}
11256 				else {
11257 					lpfc_debugfs_slow_ring_trc(phba,
11258 						"ISR slow ring:   pwork:"
11259 						"x%x hawork:x%x wait:x%x",
11260 						phba->work_ha, work_ha_copy,
11261 						(uint32_t)((unsigned long)
11262 						&phba->work_waitq));
11263 				}
11264 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11265 			}
11266 		}
11267 		spin_lock_irqsave(&phba->hbalock, iflag);
11268 		if (work_ha_copy & HA_ERATT) {
11269 			if (lpfc_sli_read_hs(phba))
11270 				goto unplug_error;
11271 			/*
11272 			 * Check if there is a deferred error condition
11273 			 * is active
11274 			 */
11275 			if ((HS_FFER1 & phba->work_hs) &&
11276 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
11277 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
11278 				  phba->work_hs)) {
11279 				phba->hba_flag |= DEFER_ERATT;
11280 				/* Clear all interrupt enable conditions */
11281 				writel(0, phba->HCregaddr);
11282 				readl(phba->HCregaddr);
11283 			}
11284 		}
11285 
11286 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
11287 			pmb = phba->sli.mbox_active;
11288 			pmbox = &pmb->u.mb;
11289 			mbox = phba->mbox;
11290 			vport = pmb->vport;
11291 
11292 			/* First check out the status word */
11293 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
11294 			if (pmbox->mbxOwner != OWN_HOST) {
11295 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11296 				/*
11297 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
11298 				 * mbxStatus <status>
11299 				 */
11300 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
11301 						LOG_SLI,
11302 						"(%d):0304 Stray Mailbox "
11303 						"Interrupt mbxCommand x%x "
11304 						"mbxStatus x%x\n",
11305 						(vport ? vport->vpi : 0),
11306 						pmbox->mbxCommand,
11307 						pmbox->mbxStatus);
11308 				/* clear mailbox attention bit */
11309 				work_ha_copy &= ~HA_MBATT;
11310 			} else {
11311 				phba->sli.mbox_active = NULL;
11312 				spin_unlock_irqrestore(&phba->hbalock, iflag);
11313 				phba->last_completion_time = jiffies;
11314 				del_timer(&phba->sli.mbox_tmo);
11315 				if (pmb->mbox_cmpl) {
11316 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
11317 							MAILBOX_CMD_SIZE);
11318 					if (pmb->out_ext_byte_len &&
11319 						pmb->context2)
11320 						lpfc_sli_pcimem_bcopy(
11321 						phba->mbox_ext,
11322 						pmb->context2,
11323 						pmb->out_ext_byte_len);
11324 				}
11325 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
11326 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
11327 
11328 					lpfc_debugfs_disc_trc(vport,
11329 						LPFC_DISC_TRC_MBOX_VPORT,
11330 						"MBOX dflt rpi: : "
11331 						"status:x%x rpi:x%x",
11332 						(uint32_t)pmbox->mbxStatus,
11333 						pmbox->un.varWords[0], 0);
11334 
11335 					if (!pmbox->mbxStatus) {
11336 						mp = (struct lpfc_dmabuf *)
11337 							(pmb->context1);
11338 						ndlp = (struct lpfc_nodelist *)
11339 							pmb->context2;
11340 
11341 						/* Reg_LOGIN of dflt RPI was
11342 						 * successful. new lets get
11343 						 * rid of the RPI using the
11344 						 * same mbox buffer.
11345 						 */
11346 						lpfc_unreg_login(phba,
11347 							vport->vpi,
11348 							pmbox->un.varWords[0],
11349 							pmb);
11350 						pmb->mbox_cmpl =
11351 							lpfc_mbx_cmpl_dflt_rpi;
11352 						pmb->context1 = mp;
11353 						pmb->context2 = ndlp;
11354 						pmb->vport = vport;
11355 						rc = lpfc_sli_issue_mbox(phba,
11356 								pmb,
11357 								MBX_NOWAIT);
11358 						if (rc != MBX_BUSY)
11359 							lpfc_printf_log(phba,
11360 							KERN_ERR,
11361 							LOG_MBOX | LOG_SLI,
11362 							"0350 rc should have"
11363 							"been MBX_BUSY\n");
11364 						if (rc != MBX_NOT_FINISHED)
11365 							goto send_current_mbox;
11366 					}
11367 				}
11368 				spin_lock_irqsave(
11369 						&phba->pport->work_port_lock,
11370 						iflag);
11371 				phba->pport->work_port_events &=
11372 					~WORKER_MBOX_TMO;
11373 				spin_unlock_irqrestore(
11374 						&phba->pport->work_port_lock,
11375 						iflag);
11376 				lpfc_mbox_cmpl_put(phba, pmb);
11377 			}
11378 		} else
11379 			spin_unlock_irqrestore(&phba->hbalock, iflag);
11380 
11381 		if ((work_ha_copy & HA_MBATT) &&
11382 		    (phba->sli.mbox_active == NULL)) {
11383 send_current_mbox:
11384 			/* Process next mailbox command if there is one */
11385 			do {
11386 				rc = lpfc_sli_issue_mbox(phba, NULL,
11387 							 MBX_NOWAIT);
11388 			} while (rc == MBX_NOT_FINISHED);
11389 			if (rc != MBX_SUCCESS)
11390 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
11391 						LOG_SLI, "0349 rc should be "
11392 						"MBX_SUCCESS\n");
11393 		}
11394 
11395 		spin_lock_irqsave(&phba->hbalock, iflag);
11396 		phba->work_ha |= work_ha_copy;
11397 		spin_unlock_irqrestore(&phba->hbalock, iflag);
11398 		lpfc_worker_wake_up(phba);
11399 	}
11400 	return IRQ_HANDLED;
11401 unplug_error:
11402 	spin_unlock_irqrestore(&phba->hbalock, iflag);
11403 	return IRQ_HANDLED;
11404 
11405 } /* lpfc_sli_sp_intr_handler */
11406 
11407 /**
11408  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
11409  * @irq: Interrupt number.
11410  * @dev_id: The device context pointer.
11411  *
11412  * This function is directly called from the PCI layer as an interrupt
11413  * service routine when device with SLI-3 interface spec is enabled with
11414  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
11415  * ring event in the HBA. However, when the device is enabled with either
11416  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
11417  * device-level interrupt handler. When the PCI slot is in error recovery
11418  * or the HBA is undergoing initialization, the interrupt handler will not
11419  * process the interrupt. The SCSI FCP fast-path ring event are handled in
11420  * the intrrupt context. This function is called without any lock held.
11421  * It gets the hbalock to access and update SLI data structures.
11422  *
11423  * This function returns IRQ_HANDLED when interrupt is handled else it
11424  * returns IRQ_NONE.
11425  **/
11426 irqreturn_t
11427 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
11428 {
11429 	struct lpfc_hba  *phba;
11430 	uint32_t ha_copy;
11431 	unsigned long status;
11432 	unsigned long iflag;
11433 
11434 	/* Get the driver's phba structure from the dev_id and
11435 	 * assume the HBA is not interrupting.
11436 	 */
11437 	phba = (struct lpfc_hba *) dev_id;
11438 
11439 	if (unlikely(!phba))
11440 		return IRQ_NONE;
11441 
11442 	/*
11443 	 * Stuff needs to be attented to when this function is invoked as an
11444 	 * individual interrupt handler in MSI-X multi-message interrupt mode
11445 	 */
11446 	if (phba->intr_type == MSIX) {
11447 		/* Check device state for handling interrupt */
11448 		if (lpfc_intr_state_check(phba))
11449 			return IRQ_NONE;
11450 		/* Need to read HA REG for FCP ring and other ring events */
11451 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
11452 			return IRQ_HANDLED;
11453 		/* Clear up only attention source related to fast-path */
11454 		spin_lock_irqsave(&phba->hbalock, iflag);
11455 		/*
11456 		 * If there is deferred error attention, do not check for
11457 		 * any interrupt.
11458 		 */
11459 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11460 			spin_unlock_irqrestore(&phba->hbalock, iflag);
11461 			return IRQ_NONE;
11462 		}
11463 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
11464 			phba->HAregaddr);
11465 		readl(phba->HAregaddr); /* flush */
11466 		spin_unlock_irqrestore(&phba->hbalock, iflag);
11467 	} else
11468 		ha_copy = phba->ha_copy;
11469 
11470 	/*
11471 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
11472 	 */
11473 	ha_copy &= ~(phba->work_ha_mask);
11474 
11475 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
11476 	status >>= (4*LPFC_FCP_RING);
11477 	if (status & HA_RXMASK)
11478 		lpfc_sli_handle_fast_ring_event(phba,
11479 						&phba->sli.ring[LPFC_FCP_RING],
11480 						status);
11481 
11482 	if (phba->cfg_multi_ring_support == 2) {
11483 		/*
11484 		 * Process all events on extra ring. Take the optimized path
11485 		 * for extra ring IO.
11486 		 */
11487 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
11488 		status >>= (4*LPFC_EXTRA_RING);
11489 		if (status & HA_RXMASK) {
11490 			lpfc_sli_handle_fast_ring_event(phba,
11491 					&phba->sli.ring[LPFC_EXTRA_RING],
11492 					status);
11493 		}
11494 	}
11495 	return IRQ_HANDLED;
11496 }  /* lpfc_sli_fp_intr_handler */
11497 
11498 /**
11499  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
11500  * @irq: Interrupt number.
11501  * @dev_id: The device context pointer.
11502  *
11503  * This function is the HBA device-level interrupt handler to device with
11504  * SLI-3 interface spec, called from the PCI layer when either MSI or
11505  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
11506  * requires driver attention. This function invokes the slow-path interrupt
11507  * attention handling function and fast-path interrupt attention handling
11508  * function in turn to process the relevant HBA attention events. This
11509  * function is called without any lock held. It gets the hbalock to access
11510  * and update SLI data structures.
11511  *
11512  * This function returns IRQ_HANDLED when interrupt is handled, else it
11513  * returns IRQ_NONE.
11514  **/
11515 irqreturn_t
11516 lpfc_sli_intr_handler(int irq, void *dev_id)
11517 {
11518 	struct lpfc_hba  *phba;
11519 	irqreturn_t sp_irq_rc, fp_irq_rc;
11520 	unsigned long status1, status2;
11521 	uint32_t hc_copy;
11522 
11523 	/*
11524 	 * Get the driver's phba structure from the dev_id and
11525 	 * assume the HBA is not interrupting.
11526 	 */
11527 	phba = (struct lpfc_hba *) dev_id;
11528 
11529 	if (unlikely(!phba))
11530 		return IRQ_NONE;
11531 
11532 	/* Check device state for handling interrupt */
11533 	if (lpfc_intr_state_check(phba))
11534 		return IRQ_NONE;
11535 
11536 	spin_lock(&phba->hbalock);
11537 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
11538 		spin_unlock(&phba->hbalock);
11539 		return IRQ_HANDLED;
11540 	}
11541 
11542 	if (unlikely(!phba->ha_copy)) {
11543 		spin_unlock(&phba->hbalock);
11544 		return IRQ_NONE;
11545 	} else if (phba->ha_copy & HA_ERATT) {
11546 		if (phba->hba_flag & HBA_ERATT_HANDLED)
11547 			/* ERATT polling has handled ERATT */
11548 			phba->ha_copy &= ~HA_ERATT;
11549 		else
11550 			/* Indicate interrupt handler handles ERATT */
11551 			phba->hba_flag |= HBA_ERATT_HANDLED;
11552 	}
11553 
11554 	/*
11555 	 * If there is deferred error attention, do not check for any interrupt.
11556 	 */
11557 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
11558 		spin_unlock(&phba->hbalock);
11559 		return IRQ_NONE;
11560 	}
11561 
11562 	/* Clear attention sources except link and error attentions */
11563 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
11564 		spin_unlock(&phba->hbalock);
11565 		return IRQ_HANDLED;
11566 	}
11567 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
11568 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
11569 		phba->HCregaddr);
11570 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
11571 	writel(hc_copy, phba->HCregaddr);
11572 	readl(phba->HAregaddr); /* flush */
11573 	spin_unlock(&phba->hbalock);
11574 
11575 	/*
11576 	 * Invokes slow-path host attention interrupt handling as appropriate.
11577 	 */
11578 
11579 	/* status of events with mailbox and link attention */
11580 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
11581 
11582 	/* status of events with ELS ring */
11583 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
11584 	status2 >>= (4*LPFC_ELS_RING);
11585 
11586 	if (status1 || (status2 & HA_RXMASK))
11587 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
11588 	else
11589 		sp_irq_rc = IRQ_NONE;
11590 
11591 	/*
11592 	 * Invoke fast-path host attention interrupt handling as appropriate.
11593 	 */
11594 
11595 	/* status of events with FCP ring */
11596 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
11597 	status1 >>= (4*LPFC_FCP_RING);
11598 
11599 	/* status of events with extra ring */
11600 	if (phba->cfg_multi_ring_support == 2) {
11601 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
11602 		status2 >>= (4*LPFC_EXTRA_RING);
11603 	} else
11604 		status2 = 0;
11605 
11606 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
11607 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
11608 	else
11609 		fp_irq_rc = IRQ_NONE;
11610 
11611 	/* Return device-level interrupt handling status */
11612 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
11613 }  /* lpfc_sli_intr_handler */
11614 
11615 /**
11616  * lpfc_sli4_fcp_xri_abort_event_proc - Process fcp xri abort event
11617  * @phba: pointer to lpfc hba data structure.
11618  *
11619  * This routine is invoked by the worker thread to process all the pending
11620  * SLI4 FCP abort XRI events.
11621  **/
11622 void lpfc_sli4_fcp_xri_abort_event_proc(struct lpfc_hba *phba)
11623 {
11624 	struct lpfc_cq_event *cq_event;
11625 
11626 	/* First, declare the fcp xri abort event has been handled */
11627 	spin_lock_irq(&phba->hbalock);
11628 	phba->hba_flag &= ~FCP_XRI_ABORT_EVENT;
11629 	spin_unlock_irq(&phba->hbalock);
11630 	/* Now, handle all the fcp xri abort events */
11631 	while (!list_empty(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue)) {
11632 		/* Get the first event from the head of the event queue */
11633 		spin_lock_irq(&phba->hbalock);
11634 		list_remove_head(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue,
11635 				 cq_event, struct lpfc_cq_event, list);
11636 		spin_unlock_irq(&phba->hbalock);
11637 		/* Notify aborted XRI for FCP work queue */
11638 		lpfc_sli4_fcp_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
11639 		/* Free the event processed back to the free pool */
11640 		lpfc_sli4_cq_event_release(phba, cq_event);
11641 	}
11642 }
11643 
11644 /**
11645  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
11646  * @phba: pointer to lpfc hba data structure.
11647  *
11648  * This routine is invoked by the worker thread to process all the pending
11649  * SLI4 els abort xri events.
11650  **/
11651 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
11652 {
11653 	struct lpfc_cq_event *cq_event;
11654 
11655 	/* First, declare the els xri abort event has been handled */
11656 	spin_lock_irq(&phba->hbalock);
11657 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
11658 	spin_unlock_irq(&phba->hbalock);
11659 	/* Now, handle all the els xri abort events */
11660 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
11661 		/* Get the first event from the head of the event queue */
11662 		spin_lock_irq(&phba->hbalock);
11663 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
11664 				 cq_event, struct lpfc_cq_event, list);
11665 		spin_unlock_irq(&phba->hbalock);
11666 		/* Notify aborted XRI for ELS work queue */
11667 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
11668 		/* Free the event processed back to the free pool */
11669 		lpfc_sli4_cq_event_release(phba, cq_event);
11670 	}
11671 }
11672 
11673 /**
11674  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
11675  * @phba: pointer to lpfc hba data structure
11676  * @pIocbIn: pointer to the rspiocbq
11677  * @pIocbOut: pointer to the cmdiocbq
11678  * @wcqe: pointer to the complete wcqe
11679  *
11680  * This routine transfers the fields of a command iocbq to a response iocbq
11681  * by copying all the IOCB fields from command iocbq and transferring the
11682  * completion status information from the complete wcqe.
11683  **/
11684 static void
11685 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
11686 			      struct lpfc_iocbq *pIocbIn,
11687 			      struct lpfc_iocbq *pIocbOut,
11688 			      struct lpfc_wcqe_complete *wcqe)
11689 {
11690 	int numBdes, i;
11691 	unsigned long iflags;
11692 	uint32_t status, max_response;
11693 	struct lpfc_dmabuf *dmabuf;
11694 	struct ulp_bde64 *bpl, bde;
11695 	size_t offset = offsetof(struct lpfc_iocbq, iocb);
11696 
11697 	memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
11698 	       sizeof(struct lpfc_iocbq) - offset);
11699 	/* Map WCQE parameters into irspiocb parameters */
11700 	status = bf_get(lpfc_wcqe_c_status, wcqe);
11701 	pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
11702 	if (pIocbOut->iocb_flag & LPFC_IO_FCP)
11703 		if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
11704 			pIocbIn->iocb.un.fcpi.fcpi_parm =
11705 					pIocbOut->iocb.un.fcpi.fcpi_parm -
11706 					wcqe->total_data_placed;
11707 		else
11708 			pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
11709 	else {
11710 		pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
11711 		switch (pIocbOut->iocb.ulpCommand) {
11712 		case CMD_ELS_REQUEST64_CR:
11713 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
11714 			bpl  = (struct ulp_bde64 *)dmabuf->virt;
11715 			bde.tus.w = le32_to_cpu(bpl[1].tus.w);
11716 			max_response = bde.tus.f.bdeSize;
11717 			break;
11718 		case CMD_GEN_REQUEST64_CR:
11719 			max_response = 0;
11720 			if (!pIocbOut->context3)
11721 				break;
11722 			numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
11723 					sizeof(struct ulp_bde64);
11724 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
11725 			bpl = (struct ulp_bde64 *)dmabuf->virt;
11726 			for (i = 0; i < numBdes; i++) {
11727 				bde.tus.w = le32_to_cpu(bpl[i].tus.w);
11728 				if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
11729 					max_response += bde.tus.f.bdeSize;
11730 			}
11731 			break;
11732 		default:
11733 			max_response = wcqe->total_data_placed;
11734 			break;
11735 		}
11736 		if (max_response < wcqe->total_data_placed)
11737 			pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
11738 		else
11739 			pIocbIn->iocb.un.genreq64.bdl.bdeSize =
11740 				wcqe->total_data_placed;
11741 	}
11742 
11743 	/* Convert BG errors for completion status */
11744 	if (status == CQE_STATUS_DI_ERROR) {
11745 		pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
11746 
11747 		if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
11748 			pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
11749 		else
11750 			pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
11751 
11752 		pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
11753 		if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
11754 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11755 				BGS_GUARD_ERR_MASK;
11756 		if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
11757 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11758 				BGS_APPTAG_ERR_MASK;
11759 		if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
11760 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11761 				BGS_REFTAG_ERR_MASK;
11762 
11763 		/* Check to see if there was any good data before the error */
11764 		if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
11765 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11766 				BGS_HI_WATER_MARK_PRESENT_MASK;
11767 			pIocbIn->iocb.unsli3.sli3_bg.bghm =
11768 				wcqe->total_data_placed;
11769 		}
11770 
11771 		/*
11772 		* Set ALL the error bits to indicate we don't know what
11773 		* type of error it is.
11774 		*/
11775 		if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
11776 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
11777 				(BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
11778 				BGS_GUARD_ERR_MASK);
11779 	}
11780 
11781 	/* Pick up HBA exchange busy condition */
11782 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
11783 		spin_lock_irqsave(&phba->hbalock, iflags);
11784 		pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
11785 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11786 	}
11787 }
11788 
11789 /**
11790  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
11791  * @phba: Pointer to HBA context object.
11792  * @wcqe: Pointer to work-queue completion queue entry.
11793  *
11794  * This routine handles an ELS work-queue completion event and construct
11795  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
11796  * discovery engine to handle.
11797  *
11798  * Return: Pointer to the receive IOCBQ, NULL otherwise.
11799  **/
11800 static struct lpfc_iocbq *
11801 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
11802 			       struct lpfc_iocbq *irspiocbq)
11803 {
11804 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
11805 	struct lpfc_iocbq *cmdiocbq;
11806 	struct lpfc_wcqe_complete *wcqe;
11807 	unsigned long iflags;
11808 
11809 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
11810 	spin_lock_irqsave(&pring->ring_lock, iflags);
11811 	pring->stats.iocb_event++;
11812 	/* Look up the ELS command IOCB and create pseudo response IOCB */
11813 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
11814 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
11815 	/* Put the iocb back on the txcmplq */
11816 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
11817 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
11818 
11819 	if (unlikely(!cmdiocbq)) {
11820 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11821 				"0386 ELS complete with no corresponding "
11822 				"cmdiocb: iotag (%d)\n",
11823 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
11824 		lpfc_sli_release_iocbq(phba, irspiocbq);
11825 		return NULL;
11826 	}
11827 
11828 	/* Fake the irspiocbq and copy necessary response information */
11829 	lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
11830 
11831 	return irspiocbq;
11832 }
11833 
11834 /**
11835  * lpfc_sli4_sp_handle_async_event - Handle an asynchroous event
11836  * @phba: Pointer to HBA context object.
11837  * @cqe: Pointer to mailbox completion queue entry.
11838  *
11839  * This routine process a mailbox completion queue entry with asynchrous
11840  * event.
11841  *
11842  * Return: true if work posted to worker thread, otherwise false.
11843  **/
11844 static bool
11845 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
11846 {
11847 	struct lpfc_cq_event *cq_event;
11848 	unsigned long iflags;
11849 
11850 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11851 			"0392 Async Event: word0:x%x, word1:x%x, "
11852 			"word2:x%x, word3:x%x\n", mcqe->word0,
11853 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
11854 
11855 	/* Allocate a new internal CQ_EVENT entry */
11856 	cq_event = lpfc_sli4_cq_event_alloc(phba);
11857 	if (!cq_event) {
11858 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11859 				"0394 Failed to allocate CQ_EVENT entry\n");
11860 		return false;
11861 	}
11862 
11863 	/* Move the CQE into an asynchronous event entry */
11864 	memcpy(&cq_event->cqe, mcqe, sizeof(struct lpfc_mcqe));
11865 	spin_lock_irqsave(&phba->hbalock, iflags);
11866 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
11867 	/* Set the async event flag */
11868 	phba->hba_flag |= ASYNC_EVENT;
11869 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11870 
11871 	return true;
11872 }
11873 
11874 /**
11875  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
11876  * @phba: Pointer to HBA context object.
11877  * @cqe: Pointer to mailbox completion queue entry.
11878  *
11879  * This routine process a mailbox completion queue entry with mailbox
11880  * completion event.
11881  *
11882  * Return: true if work posted to worker thread, otherwise false.
11883  **/
11884 static bool
11885 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
11886 {
11887 	uint32_t mcqe_status;
11888 	MAILBOX_t *mbox, *pmbox;
11889 	struct lpfc_mqe *mqe;
11890 	struct lpfc_vport *vport;
11891 	struct lpfc_nodelist *ndlp;
11892 	struct lpfc_dmabuf *mp;
11893 	unsigned long iflags;
11894 	LPFC_MBOXQ_t *pmb;
11895 	bool workposted = false;
11896 	int rc;
11897 
11898 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
11899 	if (!bf_get(lpfc_trailer_completed, mcqe))
11900 		goto out_no_mqe_complete;
11901 
11902 	/* Get the reference to the active mbox command */
11903 	spin_lock_irqsave(&phba->hbalock, iflags);
11904 	pmb = phba->sli.mbox_active;
11905 	if (unlikely(!pmb)) {
11906 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
11907 				"1832 No pending MBOX command to handle\n");
11908 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11909 		goto out_no_mqe_complete;
11910 	}
11911 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11912 	mqe = &pmb->u.mqe;
11913 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
11914 	mbox = phba->mbox;
11915 	vport = pmb->vport;
11916 
11917 	/* Reset heartbeat timer */
11918 	phba->last_completion_time = jiffies;
11919 	del_timer(&phba->sli.mbox_tmo);
11920 
11921 	/* Move mbox data to caller's mailbox region, do endian swapping */
11922 	if (pmb->mbox_cmpl && mbox)
11923 		lpfc_sli_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
11924 
11925 	/*
11926 	 * For mcqe errors, conditionally move a modified error code to
11927 	 * the mbox so that the error will not be missed.
11928 	 */
11929 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
11930 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
11931 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
11932 			bf_set(lpfc_mqe_status, mqe,
11933 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
11934 	}
11935 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
11936 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
11937 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
11938 				      "MBOX dflt rpi: status:x%x rpi:x%x",
11939 				      mcqe_status,
11940 				      pmbox->un.varWords[0], 0);
11941 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
11942 			mp = (struct lpfc_dmabuf *)(pmb->context1);
11943 			ndlp = (struct lpfc_nodelist *)pmb->context2;
11944 			/* Reg_LOGIN of dflt RPI was successful. Now lets get
11945 			 * RID of the PPI using the same mbox buffer.
11946 			 */
11947 			lpfc_unreg_login(phba, vport->vpi,
11948 					 pmbox->un.varWords[0], pmb);
11949 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
11950 			pmb->context1 = mp;
11951 			pmb->context2 = ndlp;
11952 			pmb->vport = vport;
11953 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
11954 			if (rc != MBX_BUSY)
11955 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
11956 						LOG_SLI, "0385 rc should "
11957 						"have been MBX_BUSY\n");
11958 			if (rc != MBX_NOT_FINISHED)
11959 				goto send_current_mbox;
11960 		}
11961 	}
11962 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
11963 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
11964 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
11965 
11966 	/* There is mailbox completion work to do */
11967 	spin_lock_irqsave(&phba->hbalock, iflags);
11968 	__lpfc_mbox_cmpl_put(phba, pmb);
11969 	phba->work_ha |= HA_MBATT;
11970 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11971 	workposted = true;
11972 
11973 send_current_mbox:
11974 	spin_lock_irqsave(&phba->hbalock, iflags);
11975 	/* Release the mailbox command posting token */
11976 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11977 	/* Setting active mailbox pointer need to be in sync to flag clear */
11978 	phba->sli.mbox_active = NULL;
11979 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11980 	/* Wake up worker thread to post the next pending mailbox command */
11981 	lpfc_worker_wake_up(phba);
11982 out_no_mqe_complete:
11983 	if (bf_get(lpfc_trailer_consumed, mcqe))
11984 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
11985 	return workposted;
11986 }
11987 
11988 /**
11989  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
11990  * @phba: Pointer to HBA context object.
11991  * @cqe: Pointer to mailbox completion queue entry.
11992  *
11993  * This routine process a mailbox completion queue entry, it invokes the
11994  * proper mailbox complete handling or asynchrous event handling routine
11995  * according to the MCQE's async bit.
11996  *
11997  * Return: true if work posted to worker thread, otherwise false.
11998  **/
11999 static bool
12000 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_cqe *cqe)
12001 {
12002 	struct lpfc_mcqe mcqe;
12003 	bool workposted;
12004 
12005 	/* Copy the mailbox MCQE and convert endian order as needed */
12006 	lpfc_sli_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
12007 
12008 	/* Invoke the proper event handling routine */
12009 	if (!bf_get(lpfc_trailer_async, &mcqe))
12010 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
12011 	else
12012 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
12013 	return workposted;
12014 }
12015 
12016 /**
12017  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
12018  * @phba: Pointer to HBA context object.
12019  * @cq: Pointer to associated CQ
12020  * @wcqe: Pointer to work-queue completion queue entry.
12021  *
12022  * This routine handles an ELS work-queue completion event.
12023  *
12024  * Return: true if work posted to worker thread, otherwise false.
12025  **/
12026 static bool
12027 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12028 			     struct lpfc_wcqe_complete *wcqe)
12029 {
12030 	struct lpfc_iocbq *irspiocbq;
12031 	unsigned long iflags;
12032 	struct lpfc_sli_ring *pring = cq->pring;
12033 	int txq_cnt = 0;
12034 	int txcmplq_cnt = 0;
12035 	int fcp_txcmplq_cnt = 0;
12036 
12037 	/* Get an irspiocbq for later ELS response processing use */
12038 	irspiocbq = lpfc_sli_get_iocbq(phba);
12039 	if (!irspiocbq) {
12040 		if (!list_empty(&pring->txq))
12041 			txq_cnt++;
12042 		if (!list_empty(&pring->txcmplq))
12043 			txcmplq_cnt++;
12044 		if (!list_empty(&phba->sli.ring[LPFC_FCP_RING].txcmplq))
12045 			fcp_txcmplq_cnt++;
12046 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12047 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
12048 			"fcp_txcmplq_cnt=%d, els_txcmplq_cnt=%d\n",
12049 			txq_cnt, phba->iocb_cnt,
12050 			fcp_txcmplq_cnt,
12051 			txcmplq_cnt);
12052 		return false;
12053 	}
12054 
12055 	/* Save off the slow-path queue event for work thread to process */
12056 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
12057 	spin_lock_irqsave(&phba->hbalock, iflags);
12058 	list_add_tail(&irspiocbq->cq_event.list,
12059 		      &phba->sli4_hba.sp_queue_event);
12060 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
12061 	spin_unlock_irqrestore(&phba->hbalock, iflags);
12062 
12063 	return true;
12064 }
12065 
12066 /**
12067  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
12068  * @phba: Pointer to HBA context object.
12069  * @wcqe: Pointer to work-queue completion queue entry.
12070  *
12071  * This routine handles slow-path WQ entry comsumed event by invoking the
12072  * proper WQ release routine to the slow-path WQ.
12073  **/
12074 static void
12075 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
12076 			     struct lpfc_wcqe_release *wcqe)
12077 {
12078 	/* sanity check on queue memory */
12079 	if (unlikely(!phba->sli4_hba.els_wq))
12080 		return;
12081 	/* Check for the slow-path ELS work queue */
12082 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
12083 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
12084 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
12085 	else
12086 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12087 				"2579 Slow-path wqe consume event carries "
12088 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
12089 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
12090 				phba->sli4_hba.els_wq->queue_id);
12091 }
12092 
12093 /**
12094  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
12095  * @phba: Pointer to HBA context object.
12096  * @cq: Pointer to a WQ completion queue.
12097  * @wcqe: Pointer to work-queue completion queue entry.
12098  *
12099  * This routine handles an XRI abort event.
12100  *
12101  * Return: true if work posted to worker thread, otherwise false.
12102  **/
12103 static bool
12104 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
12105 				   struct lpfc_queue *cq,
12106 				   struct sli4_wcqe_xri_aborted *wcqe)
12107 {
12108 	bool workposted = false;
12109 	struct lpfc_cq_event *cq_event;
12110 	unsigned long iflags;
12111 
12112 	/* Allocate a new internal CQ_EVENT entry */
12113 	cq_event = lpfc_sli4_cq_event_alloc(phba);
12114 	if (!cq_event) {
12115 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12116 				"0602 Failed to allocate CQ_EVENT entry\n");
12117 		return false;
12118 	}
12119 
12120 	/* Move the CQE into the proper xri abort event list */
12121 	memcpy(&cq_event->cqe, wcqe, sizeof(struct sli4_wcqe_xri_aborted));
12122 	switch (cq->subtype) {
12123 	case LPFC_FCP:
12124 		spin_lock_irqsave(&phba->hbalock, iflags);
12125 		list_add_tail(&cq_event->list,
12126 			      &phba->sli4_hba.sp_fcp_xri_aborted_work_queue);
12127 		/* Set the fcp xri abort event flag */
12128 		phba->hba_flag |= FCP_XRI_ABORT_EVENT;
12129 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12130 		workposted = true;
12131 		break;
12132 	case LPFC_ELS:
12133 		spin_lock_irqsave(&phba->hbalock, iflags);
12134 		list_add_tail(&cq_event->list,
12135 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
12136 		/* Set the els xri abort event flag */
12137 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
12138 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12139 		workposted = true;
12140 		break;
12141 	default:
12142 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12143 				"0603 Invalid work queue CQE subtype (x%x)\n",
12144 				cq->subtype);
12145 		workposted = false;
12146 		break;
12147 	}
12148 	return workposted;
12149 }
12150 
12151 /**
12152  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
12153  * @phba: Pointer to HBA context object.
12154  * @rcqe: Pointer to receive-queue completion queue entry.
12155  *
12156  * This routine process a receive-queue completion queue entry.
12157  *
12158  * Return: true if work posted to worker thread, otherwise false.
12159  **/
12160 static bool
12161 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
12162 {
12163 	bool workposted = false;
12164 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
12165 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
12166 	struct hbq_dmabuf *dma_buf;
12167 	uint32_t status, rq_id;
12168 	unsigned long iflags;
12169 
12170 	/* sanity check on queue memory */
12171 	if (unlikely(!hrq) || unlikely(!drq))
12172 		return workposted;
12173 
12174 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
12175 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
12176 	else
12177 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
12178 	if (rq_id != hrq->queue_id)
12179 		goto out;
12180 
12181 	status = bf_get(lpfc_rcqe_status, rcqe);
12182 	switch (status) {
12183 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
12184 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12185 				"2537 Receive Frame Truncated!!\n");
12186 		hrq->RQ_buf_trunc++;
12187 	case FC_STATUS_RQ_SUCCESS:
12188 		lpfc_sli4_rq_release(hrq, drq);
12189 		spin_lock_irqsave(&phba->hbalock, iflags);
12190 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
12191 		if (!dma_buf) {
12192 			hrq->RQ_no_buf_found++;
12193 			spin_unlock_irqrestore(&phba->hbalock, iflags);
12194 			goto out;
12195 		}
12196 		hrq->RQ_rcv_buf++;
12197 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
12198 		/* save off the frame for the word thread to process */
12199 		list_add_tail(&dma_buf->cq_event.list,
12200 			      &phba->sli4_hba.sp_queue_event);
12201 		/* Frame received */
12202 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
12203 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12204 		workposted = true;
12205 		break;
12206 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
12207 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
12208 		hrq->RQ_no_posted_buf++;
12209 		/* Post more buffers if possible */
12210 		spin_lock_irqsave(&phba->hbalock, iflags);
12211 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
12212 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12213 		workposted = true;
12214 		break;
12215 	}
12216 out:
12217 	return workposted;
12218 }
12219 
12220 /**
12221  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
12222  * @phba: Pointer to HBA context object.
12223  * @cq: Pointer to the completion queue.
12224  * @wcqe: Pointer to a completion queue entry.
12225  *
12226  * This routine process a slow-path work-queue or receive queue completion queue
12227  * entry.
12228  *
12229  * Return: true if work posted to worker thread, otherwise false.
12230  **/
12231 static bool
12232 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12233 			 struct lpfc_cqe *cqe)
12234 {
12235 	struct lpfc_cqe cqevt;
12236 	bool workposted = false;
12237 
12238 	/* Copy the work queue CQE and convert endian order if needed */
12239 	lpfc_sli_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
12240 
12241 	/* Check and process for different type of WCQE and dispatch */
12242 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
12243 	case CQE_CODE_COMPL_WQE:
12244 		/* Process the WQ/RQ complete event */
12245 		phba->last_completion_time = jiffies;
12246 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
12247 				(struct lpfc_wcqe_complete *)&cqevt);
12248 		break;
12249 	case CQE_CODE_RELEASE_WQE:
12250 		/* Process the WQ release event */
12251 		lpfc_sli4_sp_handle_rel_wcqe(phba,
12252 				(struct lpfc_wcqe_release *)&cqevt);
12253 		break;
12254 	case CQE_CODE_XRI_ABORTED:
12255 		/* Process the WQ XRI abort event */
12256 		phba->last_completion_time = jiffies;
12257 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
12258 				(struct sli4_wcqe_xri_aborted *)&cqevt);
12259 		break;
12260 	case CQE_CODE_RECEIVE:
12261 	case CQE_CODE_RECEIVE_V1:
12262 		/* Process the RQ event */
12263 		phba->last_completion_time = jiffies;
12264 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
12265 				(struct lpfc_rcqe *)&cqevt);
12266 		break;
12267 	default:
12268 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12269 				"0388 Not a valid WCQE code: x%x\n",
12270 				bf_get(lpfc_cqe_code, &cqevt));
12271 		break;
12272 	}
12273 	return workposted;
12274 }
12275 
12276 /**
12277  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
12278  * @phba: Pointer to HBA context object.
12279  * @eqe: Pointer to fast-path event queue entry.
12280  *
12281  * This routine process a event queue entry from the slow-path event queue.
12282  * It will check the MajorCode and MinorCode to determine this is for a
12283  * completion event on a completion queue, if not, an error shall be logged
12284  * and just return. Otherwise, it will get to the corresponding completion
12285  * queue and process all the entries on that completion queue, rearm the
12286  * completion queue, and then return.
12287  *
12288  **/
12289 static void
12290 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
12291 	struct lpfc_queue *speq)
12292 {
12293 	struct lpfc_queue *cq = NULL, *childq;
12294 	struct lpfc_cqe *cqe;
12295 	bool workposted = false;
12296 	int ecount = 0;
12297 	uint16_t cqid;
12298 
12299 	/* Get the reference to the corresponding CQ */
12300 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
12301 
12302 	list_for_each_entry(childq, &speq->child_list, list) {
12303 		if (childq->queue_id == cqid) {
12304 			cq = childq;
12305 			break;
12306 		}
12307 	}
12308 	if (unlikely(!cq)) {
12309 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
12310 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12311 					"0365 Slow-path CQ identifier "
12312 					"(%d) does not exist\n", cqid);
12313 		return;
12314 	}
12315 
12316 	/* Process all the entries to the CQ */
12317 	switch (cq->type) {
12318 	case LPFC_MCQ:
12319 		while ((cqe = lpfc_sli4_cq_get(cq))) {
12320 			workposted |= lpfc_sli4_sp_handle_mcqe(phba, cqe);
12321 			if (!(++ecount % cq->entry_repost))
12322 				lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12323 			cq->CQ_mbox++;
12324 		}
12325 		break;
12326 	case LPFC_WCQ:
12327 		while ((cqe = lpfc_sli4_cq_get(cq))) {
12328 			if (cq->subtype == LPFC_FCP)
12329 				workposted |= lpfc_sli4_fp_handle_wcqe(phba, cq,
12330 								       cqe);
12331 			else
12332 				workposted |= lpfc_sli4_sp_handle_cqe(phba, cq,
12333 								      cqe);
12334 			if (!(++ecount % cq->entry_repost))
12335 				lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12336 		}
12337 
12338 		/* Track the max number of CQEs processed in 1 EQ */
12339 		if (ecount > cq->CQ_max_cqe)
12340 			cq->CQ_max_cqe = ecount;
12341 		break;
12342 	default:
12343 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12344 				"0370 Invalid completion queue type (%d)\n",
12345 				cq->type);
12346 		return;
12347 	}
12348 
12349 	/* Catch the no cq entry condition, log an error */
12350 	if (unlikely(ecount == 0))
12351 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12352 				"0371 No entry from the CQ: identifier "
12353 				"(x%x), type (%d)\n", cq->queue_id, cq->type);
12354 
12355 	/* In any case, flash and re-arm the RCQ */
12356 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
12357 
12358 	/* wake up worker thread if there are works to be done */
12359 	if (workposted)
12360 		lpfc_worker_wake_up(phba);
12361 }
12362 
12363 /**
12364  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
12365  * @phba: Pointer to HBA context object.
12366  * @cq: Pointer to associated CQ
12367  * @wcqe: Pointer to work-queue completion queue entry.
12368  *
12369  * This routine process a fast-path work queue completion entry from fast-path
12370  * event queue for FCP command response completion.
12371  **/
12372 static void
12373 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12374 			     struct lpfc_wcqe_complete *wcqe)
12375 {
12376 	struct lpfc_sli_ring *pring = cq->pring;
12377 	struct lpfc_iocbq *cmdiocbq;
12378 	struct lpfc_iocbq irspiocbq;
12379 	unsigned long iflags;
12380 
12381 	/* Check for response status */
12382 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
12383 		/* If resource errors reported from HBA, reduce queue
12384 		 * depth of the SCSI device.
12385 		 */
12386 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
12387 		     IOSTAT_LOCAL_REJECT)) &&
12388 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
12389 		     IOERR_NO_RESOURCES))
12390 			phba->lpfc_rampdown_queue_depth(phba);
12391 
12392 		/* Log the error status */
12393 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12394 				"0373 FCP complete error: status=x%x, "
12395 				"hw_status=x%x, total_data_specified=%d, "
12396 				"parameter=x%x, word3=x%x\n",
12397 				bf_get(lpfc_wcqe_c_status, wcqe),
12398 				bf_get(lpfc_wcqe_c_hw_status, wcqe),
12399 				wcqe->total_data_placed, wcqe->parameter,
12400 				wcqe->word3);
12401 	}
12402 
12403 	/* Look up the FCP command IOCB and create pseudo response IOCB */
12404 	spin_lock_irqsave(&pring->ring_lock, iflags);
12405 	pring->stats.iocb_event++;
12406 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
12407 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12408 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
12409 	if (unlikely(!cmdiocbq)) {
12410 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12411 				"0374 FCP complete with no corresponding "
12412 				"cmdiocb: iotag (%d)\n",
12413 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12414 		return;
12415 	}
12416 	if (unlikely(!cmdiocbq->iocb_cmpl)) {
12417 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12418 				"0375 FCP cmdiocb not callback function "
12419 				"iotag: (%d)\n",
12420 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
12421 		return;
12422 	}
12423 
12424 	/* Fake the irspiocb and copy necessary response information */
12425 	lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
12426 
12427 	if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
12428 		spin_lock_irqsave(&phba->hbalock, iflags);
12429 		cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
12430 		spin_unlock_irqrestore(&phba->hbalock, iflags);
12431 	}
12432 
12433 	/* Pass the cmd_iocb and the rsp state to the upper layer */
12434 	(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
12435 }
12436 
12437 /**
12438  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
12439  * @phba: Pointer to HBA context object.
12440  * @cq: Pointer to completion queue.
12441  * @wcqe: Pointer to work-queue completion queue entry.
12442  *
12443  * This routine handles an fast-path WQ entry comsumed event by invoking the
12444  * proper WQ release routine to the slow-path WQ.
12445  **/
12446 static void
12447 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12448 			     struct lpfc_wcqe_release *wcqe)
12449 {
12450 	struct lpfc_queue *childwq;
12451 	bool wqid_matched = false;
12452 	uint16_t fcp_wqid;
12453 
12454 	/* Check for fast-path FCP work queue release */
12455 	fcp_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
12456 	list_for_each_entry(childwq, &cq->child_list, list) {
12457 		if (childwq->queue_id == fcp_wqid) {
12458 			lpfc_sli4_wq_release(childwq,
12459 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
12460 			wqid_matched = true;
12461 			break;
12462 		}
12463 	}
12464 	/* Report warning log message if no match found */
12465 	if (wqid_matched != true)
12466 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12467 				"2580 Fast-path wqe consume event carries "
12468 				"miss-matched qid: wcqe-qid=x%x\n", fcp_wqid);
12469 }
12470 
12471 /**
12472  * lpfc_sli4_fp_handle_wcqe - Process fast-path work queue completion entry
12473  * @cq: Pointer to the completion queue.
12474  * @eqe: Pointer to fast-path completion queue entry.
12475  *
12476  * This routine process a fast-path work queue completion entry from fast-path
12477  * event queue for FCP command response completion.
12478  **/
12479 static int
12480 lpfc_sli4_fp_handle_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
12481 			 struct lpfc_cqe *cqe)
12482 {
12483 	struct lpfc_wcqe_release wcqe;
12484 	bool workposted = false;
12485 
12486 	/* Copy the work queue CQE and convert endian order if needed */
12487 	lpfc_sli_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
12488 
12489 	/* Check and process for different type of WCQE and dispatch */
12490 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
12491 	case CQE_CODE_COMPL_WQE:
12492 		cq->CQ_wq++;
12493 		/* Process the WQ complete event */
12494 		phba->last_completion_time = jiffies;
12495 		lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
12496 				(struct lpfc_wcqe_complete *)&wcqe);
12497 		break;
12498 	case CQE_CODE_RELEASE_WQE:
12499 		cq->CQ_release_wqe++;
12500 		/* Process the WQ release event */
12501 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
12502 				(struct lpfc_wcqe_release *)&wcqe);
12503 		break;
12504 	case CQE_CODE_XRI_ABORTED:
12505 		cq->CQ_xri_aborted++;
12506 		/* Process the WQ XRI abort event */
12507 		phba->last_completion_time = jiffies;
12508 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
12509 				(struct sli4_wcqe_xri_aborted *)&wcqe);
12510 		break;
12511 	default:
12512 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12513 				"0144 Not a valid WCQE code: x%x\n",
12514 				bf_get(lpfc_wcqe_c_code, &wcqe));
12515 		break;
12516 	}
12517 	return workposted;
12518 }
12519 
12520 /**
12521  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
12522  * @phba: Pointer to HBA context object.
12523  * @eqe: Pointer to fast-path event queue entry.
12524  *
12525  * This routine process a event queue entry from the fast-path event queue.
12526  * It will check the MajorCode and MinorCode to determine this is for a
12527  * completion event on a completion queue, if not, an error shall be logged
12528  * and just return. Otherwise, it will get to the corresponding completion
12529  * queue and process all the entries on the completion queue, rearm the
12530  * completion queue, and then return.
12531  **/
12532 static void
12533 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
12534 			uint32_t qidx)
12535 {
12536 	struct lpfc_queue *cq;
12537 	struct lpfc_cqe *cqe;
12538 	bool workposted = false;
12539 	uint16_t cqid;
12540 	int ecount = 0;
12541 
12542 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
12543 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12544 				"0366 Not a valid completion "
12545 				"event: majorcode=x%x, minorcode=x%x\n",
12546 				bf_get_le32(lpfc_eqe_major_code, eqe),
12547 				bf_get_le32(lpfc_eqe_minor_code, eqe));
12548 		return;
12549 	}
12550 
12551 	/* Get the reference to the corresponding CQ */
12552 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
12553 
12554 	/* Check if this is a Slow path event */
12555 	if (unlikely(cqid != phba->sli4_hba.fcp_cq_map[qidx])) {
12556 		lpfc_sli4_sp_handle_eqe(phba, eqe,
12557 			phba->sli4_hba.hba_eq[qidx]);
12558 		return;
12559 	}
12560 
12561 	if (unlikely(!phba->sli4_hba.fcp_cq)) {
12562 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12563 				"3146 Fast-path completion queues "
12564 				"does not exist\n");
12565 		return;
12566 	}
12567 	cq = phba->sli4_hba.fcp_cq[qidx];
12568 	if (unlikely(!cq)) {
12569 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
12570 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12571 					"0367 Fast-path completion queue "
12572 					"(%d) does not exist\n", qidx);
12573 		return;
12574 	}
12575 
12576 	if (unlikely(cqid != cq->queue_id)) {
12577 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12578 				"0368 Miss-matched fast-path completion "
12579 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
12580 				cqid, cq->queue_id);
12581 		return;
12582 	}
12583 
12584 	/* Process all the entries to the CQ */
12585 	while ((cqe = lpfc_sli4_cq_get(cq))) {
12586 		workposted |= lpfc_sli4_fp_handle_wcqe(phba, cq, cqe);
12587 		if (!(++ecount % cq->entry_repost))
12588 			lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12589 	}
12590 
12591 	/* Track the max number of CQEs processed in 1 EQ */
12592 	if (ecount > cq->CQ_max_cqe)
12593 		cq->CQ_max_cqe = ecount;
12594 
12595 	/* Catch the no cq entry condition */
12596 	if (unlikely(ecount == 0))
12597 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12598 				"0369 No entry from fast-path completion "
12599 				"queue fcpcqid=%d\n", cq->queue_id);
12600 
12601 	/* In any case, flash and re-arm the CQ */
12602 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
12603 
12604 	/* wake up worker thread if there are works to be done */
12605 	if (workposted)
12606 		lpfc_worker_wake_up(phba);
12607 }
12608 
12609 static void
12610 lpfc_sli4_eq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
12611 {
12612 	struct lpfc_eqe *eqe;
12613 
12614 	/* walk all the EQ entries and drop on the floor */
12615 	while ((eqe = lpfc_sli4_eq_get(eq)))
12616 		;
12617 
12618 	/* Clear and re-arm the EQ */
12619 	lpfc_sli4_eq_release(eq, LPFC_QUEUE_REARM);
12620 }
12621 
12622 
12623 /**
12624  * lpfc_sli4_fof_handle_eqe - Process a Flash Optimized Fabric event queue
12625  *			     entry
12626  * @phba: Pointer to HBA context object.
12627  * @eqe: Pointer to fast-path event queue entry.
12628  *
12629  * This routine process a event queue entry from the Flash Optimized Fabric
12630  * event queue.  It will check the MajorCode and MinorCode to determine this
12631  * is for a completion event on a completion queue, if not, an error shall be
12632  * logged and just return. Otherwise, it will get to the corresponding
12633  * completion queue and process all the entries on the completion queue, rearm
12634  * the completion queue, and then return.
12635  **/
12636 static void
12637 lpfc_sli4_fof_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe)
12638 {
12639 	struct lpfc_queue *cq;
12640 	struct lpfc_cqe *cqe;
12641 	bool workposted = false;
12642 	uint16_t cqid;
12643 	int ecount = 0;
12644 
12645 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
12646 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12647 				"9147 Not a valid completion "
12648 				"event: majorcode=x%x, minorcode=x%x\n",
12649 				bf_get_le32(lpfc_eqe_major_code, eqe),
12650 				bf_get_le32(lpfc_eqe_minor_code, eqe));
12651 		return;
12652 	}
12653 
12654 	/* Get the reference to the corresponding CQ */
12655 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
12656 
12657 	/* Next check for OAS */
12658 	cq = phba->sli4_hba.oas_cq;
12659 	if (unlikely(!cq)) {
12660 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
12661 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12662 					"9148 OAS completion queue "
12663 					"does not exist\n");
12664 		return;
12665 	}
12666 
12667 	if (unlikely(cqid != cq->queue_id)) {
12668 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12669 				"9149 Miss-matched fast-path compl "
12670 				"queue id: eqcqid=%d, fcpcqid=%d\n",
12671 				cqid, cq->queue_id);
12672 		return;
12673 	}
12674 
12675 	/* Process all the entries to the OAS CQ */
12676 	while ((cqe = lpfc_sli4_cq_get(cq))) {
12677 		workposted |= lpfc_sli4_fp_handle_wcqe(phba, cq, cqe);
12678 		if (!(++ecount % cq->entry_repost))
12679 			lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
12680 	}
12681 
12682 	/* Track the max number of CQEs processed in 1 EQ */
12683 	if (ecount > cq->CQ_max_cqe)
12684 		cq->CQ_max_cqe = ecount;
12685 
12686 	/* Catch the no cq entry condition */
12687 	if (unlikely(ecount == 0))
12688 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12689 				"9153 No entry from fast-path completion "
12690 				"queue fcpcqid=%d\n", cq->queue_id);
12691 
12692 	/* In any case, flash and re-arm the CQ */
12693 	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
12694 
12695 	/* wake up worker thread if there are works to be done */
12696 	if (workposted)
12697 		lpfc_worker_wake_up(phba);
12698 }
12699 
12700 /**
12701  * lpfc_sli4_fof_intr_handler - HBA interrupt handler to SLI-4 device
12702  * @irq: Interrupt number.
12703  * @dev_id: The device context pointer.
12704  *
12705  * This function is directly called from the PCI layer as an interrupt
12706  * service routine when device with SLI-4 interface spec is enabled with
12707  * MSI-X multi-message interrupt mode and there is a Flash Optimized Fabric
12708  * IOCB ring event in the HBA. However, when the device is enabled with either
12709  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
12710  * device-level interrupt handler. When the PCI slot is in error recovery
12711  * or the HBA is undergoing initialization, the interrupt handler will not
12712  * process the interrupt. The Flash Optimized Fabric ring event are handled in
12713  * the intrrupt context. This function is called without any lock held.
12714  * It gets the hbalock to access and update SLI data structures. Note that,
12715  * the EQ to CQ are one-to-one map such that the EQ index is
12716  * equal to that of CQ index.
12717  *
12718  * This function returns IRQ_HANDLED when interrupt is handled else it
12719  * returns IRQ_NONE.
12720  **/
12721 irqreturn_t
12722 lpfc_sli4_fof_intr_handler(int irq, void *dev_id)
12723 {
12724 	struct lpfc_hba *phba;
12725 	struct lpfc_fcp_eq_hdl *fcp_eq_hdl;
12726 	struct lpfc_queue *eq;
12727 	struct lpfc_eqe *eqe;
12728 	unsigned long iflag;
12729 	int ecount = 0;
12730 
12731 	/* Get the driver's phba structure from the dev_id */
12732 	fcp_eq_hdl = (struct lpfc_fcp_eq_hdl *)dev_id;
12733 	phba = fcp_eq_hdl->phba;
12734 
12735 	if (unlikely(!phba))
12736 		return IRQ_NONE;
12737 
12738 	/* Get to the EQ struct associated with this vector */
12739 	eq = phba->sli4_hba.fof_eq;
12740 	if (unlikely(!eq))
12741 		return IRQ_NONE;
12742 
12743 	/* Check device state for handling interrupt */
12744 	if (unlikely(lpfc_intr_state_check(phba))) {
12745 		eq->EQ_badstate++;
12746 		/* Check again for link_state with lock held */
12747 		spin_lock_irqsave(&phba->hbalock, iflag);
12748 		if (phba->link_state < LPFC_LINK_DOWN)
12749 			/* Flush, clear interrupt, and rearm the EQ */
12750 			lpfc_sli4_eq_flush(phba, eq);
12751 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12752 		return IRQ_NONE;
12753 	}
12754 
12755 	/*
12756 	 * Process all the event on FCP fast-path EQ
12757 	 */
12758 	while ((eqe = lpfc_sli4_eq_get(eq))) {
12759 		lpfc_sli4_fof_handle_eqe(phba, eqe);
12760 		if (!(++ecount % eq->entry_repost))
12761 			lpfc_sli4_eq_release(eq, LPFC_QUEUE_NOARM);
12762 		eq->EQ_processed++;
12763 	}
12764 
12765 	/* Track the max number of EQEs processed in 1 intr */
12766 	if (ecount > eq->EQ_max_eqe)
12767 		eq->EQ_max_eqe = ecount;
12768 
12769 
12770 	if (unlikely(ecount == 0)) {
12771 		eq->EQ_no_entry++;
12772 
12773 		if (phba->intr_type == MSIX)
12774 			/* MSI-X treated interrupt served as no EQ share INT */
12775 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12776 					"9145 MSI-X interrupt with no EQE\n");
12777 		else {
12778 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12779 					"9146 ISR interrupt with no EQE\n");
12780 			/* Non MSI-X treated on interrupt as EQ share INT */
12781 			return IRQ_NONE;
12782 		}
12783 	}
12784 	/* Always clear and re-arm the fast-path EQ */
12785 	lpfc_sli4_eq_release(eq, LPFC_QUEUE_REARM);
12786 	return IRQ_HANDLED;
12787 }
12788 
12789 /**
12790  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
12791  * @irq: Interrupt number.
12792  * @dev_id: The device context pointer.
12793  *
12794  * This function is directly called from the PCI layer as an interrupt
12795  * service routine when device with SLI-4 interface spec is enabled with
12796  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
12797  * ring event in the HBA. However, when the device is enabled with either
12798  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
12799  * device-level interrupt handler. When the PCI slot is in error recovery
12800  * or the HBA is undergoing initialization, the interrupt handler will not
12801  * process the interrupt. The SCSI FCP fast-path ring event are handled in
12802  * the intrrupt context. This function is called without any lock held.
12803  * It gets the hbalock to access and update SLI data structures. Note that,
12804  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
12805  * equal to that of FCP CQ index.
12806  *
12807  * The link attention and ELS ring attention events are handled
12808  * by the worker thread. The interrupt handler signals the worker thread
12809  * and returns for these events. This function is called without any lock
12810  * held. It gets the hbalock to access and update SLI data structures.
12811  *
12812  * This function returns IRQ_HANDLED when interrupt is handled else it
12813  * returns IRQ_NONE.
12814  **/
12815 irqreturn_t
12816 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
12817 {
12818 	struct lpfc_hba *phba;
12819 	struct lpfc_fcp_eq_hdl *fcp_eq_hdl;
12820 	struct lpfc_queue *fpeq;
12821 	struct lpfc_eqe *eqe;
12822 	unsigned long iflag;
12823 	int ecount = 0;
12824 	int fcp_eqidx;
12825 
12826 	/* Get the driver's phba structure from the dev_id */
12827 	fcp_eq_hdl = (struct lpfc_fcp_eq_hdl *)dev_id;
12828 	phba = fcp_eq_hdl->phba;
12829 	fcp_eqidx = fcp_eq_hdl->idx;
12830 
12831 	if (unlikely(!phba))
12832 		return IRQ_NONE;
12833 	if (unlikely(!phba->sli4_hba.hba_eq))
12834 		return IRQ_NONE;
12835 
12836 	/* Get to the EQ struct associated with this vector */
12837 	fpeq = phba->sli4_hba.hba_eq[fcp_eqidx];
12838 	if (unlikely(!fpeq))
12839 		return IRQ_NONE;
12840 
12841 	if (lpfc_fcp_look_ahead) {
12842 		if (atomic_dec_and_test(&fcp_eq_hdl->fcp_eq_in_use))
12843 			lpfc_sli4_eq_clr_intr(fpeq);
12844 		else {
12845 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12846 			return IRQ_NONE;
12847 		}
12848 	}
12849 
12850 	/* Check device state for handling interrupt */
12851 	if (unlikely(lpfc_intr_state_check(phba))) {
12852 		fpeq->EQ_badstate++;
12853 		/* Check again for link_state with lock held */
12854 		spin_lock_irqsave(&phba->hbalock, iflag);
12855 		if (phba->link_state < LPFC_LINK_DOWN)
12856 			/* Flush, clear interrupt, and rearm the EQ */
12857 			lpfc_sli4_eq_flush(phba, fpeq);
12858 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12859 		if (lpfc_fcp_look_ahead)
12860 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12861 		return IRQ_NONE;
12862 	}
12863 
12864 	/*
12865 	 * Process all the event on FCP fast-path EQ
12866 	 */
12867 	while ((eqe = lpfc_sli4_eq_get(fpeq))) {
12868 		if (eqe == NULL)
12869 			break;
12870 
12871 		lpfc_sli4_hba_handle_eqe(phba, eqe, fcp_eqidx);
12872 		if (!(++ecount % fpeq->entry_repost))
12873 			lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_NOARM);
12874 		fpeq->EQ_processed++;
12875 	}
12876 
12877 	/* Track the max number of EQEs processed in 1 intr */
12878 	if (ecount > fpeq->EQ_max_eqe)
12879 		fpeq->EQ_max_eqe = ecount;
12880 
12881 	/* Always clear and re-arm the fast-path EQ */
12882 	lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_REARM);
12883 
12884 	if (unlikely(ecount == 0)) {
12885 		fpeq->EQ_no_entry++;
12886 
12887 		if (lpfc_fcp_look_ahead) {
12888 			atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12889 			return IRQ_NONE;
12890 		}
12891 
12892 		if (phba->intr_type == MSIX)
12893 			/* MSI-X treated interrupt served as no EQ share INT */
12894 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
12895 					"0358 MSI-X interrupt with no EQE\n");
12896 		else
12897 			/* Non MSI-X treated on interrupt as EQ share INT */
12898 			return IRQ_NONE;
12899 	}
12900 
12901 	if (lpfc_fcp_look_ahead)
12902 		atomic_inc(&fcp_eq_hdl->fcp_eq_in_use);
12903 	return IRQ_HANDLED;
12904 } /* lpfc_sli4_fp_intr_handler */
12905 
12906 /**
12907  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
12908  * @irq: Interrupt number.
12909  * @dev_id: The device context pointer.
12910  *
12911  * This function is the device-level interrupt handler to device with SLI-4
12912  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
12913  * interrupt mode is enabled and there is an event in the HBA which requires
12914  * driver attention. This function invokes the slow-path interrupt attention
12915  * handling function and fast-path interrupt attention handling function in
12916  * turn to process the relevant HBA attention events. This function is called
12917  * without any lock held. It gets the hbalock to access and update SLI data
12918  * structures.
12919  *
12920  * This function returns IRQ_HANDLED when interrupt is handled, else it
12921  * returns IRQ_NONE.
12922  **/
12923 irqreturn_t
12924 lpfc_sli4_intr_handler(int irq, void *dev_id)
12925 {
12926 	struct lpfc_hba  *phba;
12927 	irqreturn_t hba_irq_rc;
12928 	bool hba_handled = false;
12929 	int fcp_eqidx;
12930 
12931 	/* Get the driver's phba structure from the dev_id */
12932 	phba = (struct lpfc_hba *)dev_id;
12933 
12934 	if (unlikely(!phba))
12935 		return IRQ_NONE;
12936 
12937 	/*
12938 	 * Invoke fast-path host attention interrupt handling as appropriate.
12939 	 */
12940 	for (fcp_eqidx = 0; fcp_eqidx < phba->cfg_fcp_io_channel; fcp_eqidx++) {
12941 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
12942 					&phba->sli4_hba.fcp_eq_hdl[fcp_eqidx]);
12943 		if (hba_irq_rc == IRQ_HANDLED)
12944 			hba_handled |= true;
12945 	}
12946 
12947 	if (phba->cfg_fof) {
12948 		hba_irq_rc = lpfc_sli4_fof_intr_handler(irq,
12949 					&phba->sli4_hba.fcp_eq_hdl[0]);
12950 		if (hba_irq_rc == IRQ_HANDLED)
12951 			hba_handled |= true;
12952 	}
12953 
12954 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
12955 } /* lpfc_sli4_intr_handler */
12956 
12957 /**
12958  * lpfc_sli4_queue_free - free a queue structure and associated memory
12959  * @queue: The queue structure to free.
12960  *
12961  * This function frees a queue structure and the DMAable memory used for
12962  * the host resident queue. This function must be called after destroying the
12963  * queue on the HBA.
12964  **/
12965 void
12966 lpfc_sli4_queue_free(struct lpfc_queue *queue)
12967 {
12968 	struct lpfc_dmabuf *dmabuf;
12969 
12970 	if (!queue)
12971 		return;
12972 
12973 	while (!list_empty(&queue->page_list)) {
12974 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
12975 				 list);
12976 		dma_free_coherent(&queue->phba->pcidev->dev, SLI4_PAGE_SIZE,
12977 				  dmabuf->virt, dmabuf->phys);
12978 		kfree(dmabuf);
12979 	}
12980 	kfree(queue);
12981 	return;
12982 }
12983 
12984 /**
12985  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
12986  * @phba: The HBA that this queue is being created on.
12987  * @entry_size: The size of each queue entry for this queue.
12988  * @entry count: The number of entries that this queue will handle.
12989  *
12990  * This function allocates a queue structure and the DMAable memory used for
12991  * the host resident queue. This function must be called before creating the
12992  * queue on the HBA.
12993  **/
12994 struct lpfc_queue *
12995 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t entry_size,
12996 		      uint32_t entry_count)
12997 {
12998 	struct lpfc_queue *queue;
12999 	struct lpfc_dmabuf *dmabuf;
13000 	int x, total_qe_count;
13001 	void *dma_pointer;
13002 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13003 
13004 	if (!phba->sli4_hba.pc_sli4_params.supported)
13005 		hw_page_size = SLI4_PAGE_SIZE;
13006 
13007 	queue = kzalloc(sizeof(struct lpfc_queue) +
13008 			(sizeof(union sli4_qe) * entry_count), GFP_KERNEL);
13009 	if (!queue)
13010 		return NULL;
13011 	queue->page_count = (ALIGN(entry_size * entry_count,
13012 			hw_page_size))/hw_page_size;
13013 	INIT_LIST_HEAD(&queue->list);
13014 	INIT_LIST_HEAD(&queue->page_list);
13015 	INIT_LIST_HEAD(&queue->child_list);
13016 	for (x = 0, total_qe_count = 0; x < queue->page_count; x++) {
13017 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
13018 		if (!dmabuf)
13019 			goto out_fail;
13020 		dmabuf->virt = dma_zalloc_coherent(&phba->pcidev->dev,
13021 						   hw_page_size, &dmabuf->phys,
13022 						   GFP_KERNEL);
13023 		if (!dmabuf->virt) {
13024 			kfree(dmabuf);
13025 			goto out_fail;
13026 		}
13027 		dmabuf->buffer_tag = x;
13028 		list_add_tail(&dmabuf->list, &queue->page_list);
13029 		/* initialize queue's entry array */
13030 		dma_pointer = dmabuf->virt;
13031 		for (; total_qe_count < entry_count &&
13032 		     dma_pointer < (hw_page_size + dmabuf->virt);
13033 		     total_qe_count++, dma_pointer += entry_size) {
13034 			queue->qe[total_qe_count].address = dma_pointer;
13035 		}
13036 	}
13037 	queue->entry_size = entry_size;
13038 	queue->entry_count = entry_count;
13039 
13040 	/*
13041 	 * entry_repost is calculated based on the number of entries in the
13042 	 * queue. This works out except for RQs. If buffers are NOT initially
13043 	 * posted for every RQE, entry_repost should be adjusted accordingly.
13044 	 */
13045 	queue->entry_repost = (entry_count >> 3);
13046 	if (queue->entry_repost < LPFC_QUEUE_MIN_REPOST)
13047 		queue->entry_repost = LPFC_QUEUE_MIN_REPOST;
13048 	queue->phba = phba;
13049 
13050 	return queue;
13051 out_fail:
13052 	lpfc_sli4_queue_free(queue);
13053 	return NULL;
13054 }
13055 
13056 /**
13057  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
13058  * @phba: HBA structure that indicates port to create a queue on.
13059  * @pci_barset: PCI BAR set flag.
13060  *
13061  * This function shall perform iomap of the specified PCI BAR address to host
13062  * memory address if not already done so and return it. The returned host
13063  * memory address can be NULL.
13064  */
13065 static void __iomem *
13066 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
13067 {
13068 	if (!phba->pcidev)
13069 		return NULL;
13070 
13071 	switch (pci_barset) {
13072 	case WQ_PCI_BAR_0_AND_1:
13073 		return phba->pci_bar0_memmap_p;
13074 	case WQ_PCI_BAR_2_AND_3:
13075 		return phba->pci_bar2_memmap_p;
13076 	case WQ_PCI_BAR_4_AND_5:
13077 		return phba->pci_bar4_memmap_p;
13078 	default:
13079 		break;
13080 	}
13081 	return NULL;
13082 }
13083 
13084 /**
13085  * lpfc_modify_fcp_eq_delay - Modify Delay Multiplier on FCP EQs
13086  * @phba: HBA structure that indicates port to create a queue on.
13087  * @startq: The starting FCP EQ to modify
13088  *
13089  * This function sends an MODIFY_EQ_DELAY mailbox command to the HBA.
13090  *
13091  * The @phba struct is used to send mailbox command to HBA. The @startq
13092  * is used to get the starting FCP EQ to change.
13093  * This function is asynchronous and will wait for the mailbox
13094  * command to finish before continuing.
13095  *
13096  * On success this function will return a zero. If unable to allocate enough
13097  * memory this function will return -ENOMEM. If the queue create mailbox command
13098  * fails this function will return -ENXIO.
13099  **/
13100 int
13101 lpfc_modify_fcp_eq_delay(struct lpfc_hba *phba, uint32_t startq)
13102 {
13103 	struct lpfc_mbx_modify_eq_delay *eq_delay;
13104 	LPFC_MBOXQ_t *mbox;
13105 	struct lpfc_queue *eq;
13106 	int cnt, rc, length, status = 0;
13107 	uint32_t shdr_status, shdr_add_status;
13108 	uint32_t result;
13109 	int fcp_eqidx;
13110 	union lpfc_sli4_cfg_shdr *shdr;
13111 	uint16_t dmult;
13112 
13113 	if (startq >= phba->cfg_fcp_io_channel)
13114 		return 0;
13115 
13116 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13117 	if (!mbox)
13118 		return -ENOMEM;
13119 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
13120 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13121 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13122 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
13123 			 length, LPFC_SLI4_MBX_EMBED);
13124 	eq_delay = &mbox->u.mqe.un.eq_delay;
13125 
13126 	/* Calculate delay multiper from maximum interrupt per second */
13127 	result = phba->cfg_fcp_imax / phba->cfg_fcp_io_channel;
13128 	if (result > LPFC_DMULT_CONST)
13129 		dmult = 0;
13130 	else
13131 		dmult = LPFC_DMULT_CONST/result - 1;
13132 
13133 	cnt = 0;
13134 	for (fcp_eqidx = startq; fcp_eqidx < phba->cfg_fcp_io_channel;
13135 	    fcp_eqidx++) {
13136 		eq = phba->sli4_hba.hba_eq[fcp_eqidx];
13137 		if (!eq)
13138 			continue;
13139 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
13140 		eq_delay->u.request.eq[cnt].phase = 0;
13141 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
13142 		cnt++;
13143 		if (cnt >= LPFC_MAX_EQ_DELAY)
13144 			break;
13145 	}
13146 	eq_delay->u.request.num_eq = cnt;
13147 
13148 	mbox->vport = phba->pport;
13149 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13150 	mbox->context1 = NULL;
13151 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13152 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
13153 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13154 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13155 	if (shdr_status || shdr_add_status || rc) {
13156 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13157 				"2512 MODIFY_EQ_DELAY mailbox failed with "
13158 				"status x%x add_status x%x, mbx status x%x\n",
13159 				shdr_status, shdr_add_status, rc);
13160 		status = -ENXIO;
13161 	}
13162 	mempool_free(mbox, phba->mbox_mem_pool);
13163 	return status;
13164 }
13165 
13166 /**
13167  * lpfc_eq_create - Create an Event Queue on the HBA
13168  * @phba: HBA structure that indicates port to create a queue on.
13169  * @eq: The queue structure to use to create the event queue.
13170  * @imax: The maximum interrupt per second limit.
13171  *
13172  * This function creates an event queue, as detailed in @eq, on a port,
13173  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
13174  *
13175  * The @phba struct is used to send mailbox command to HBA. The @eq struct
13176  * is used to get the entry count and entry size that are necessary to
13177  * determine the number of pages to allocate and use for this queue. This
13178  * function will send the EQ_CREATE mailbox command to the HBA to setup the
13179  * event queue. This function is asynchronous and will wait for the mailbox
13180  * command to finish before continuing.
13181  *
13182  * On success this function will return a zero. If unable to allocate enough
13183  * memory this function will return -ENOMEM. If the queue create mailbox command
13184  * fails this function will return -ENXIO.
13185  **/
13186 int
13187 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
13188 {
13189 	struct lpfc_mbx_eq_create *eq_create;
13190 	LPFC_MBOXQ_t *mbox;
13191 	int rc, length, status = 0;
13192 	struct lpfc_dmabuf *dmabuf;
13193 	uint32_t shdr_status, shdr_add_status;
13194 	union lpfc_sli4_cfg_shdr *shdr;
13195 	uint16_t dmult;
13196 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13197 
13198 	/* sanity check on queue memory */
13199 	if (!eq)
13200 		return -ENODEV;
13201 	if (!phba->sli4_hba.pc_sli4_params.supported)
13202 		hw_page_size = SLI4_PAGE_SIZE;
13203 
13204 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13205 	if (!mbox)
13206 		return -ENOMEM;
13207 	length = (sizeof(struct lpfc_mbx_eq_create) -
13208 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13209 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13210 			 LPFC_MBOX_OPCODE_EQ_CREATE,
13211 			 length, LPFC_SLI4_MBX_EMBED);
13212 	eq_create = &mbox->u.mqe.un.eq_create;
13213 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
13214 	       eq->page_count);
13215 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
13216 	       LPFC_EQE_SIZE);
13217 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
13218 	/* don't setup delay multiplier using EQ_CREATE */
13219 	dmult = 0;
13220 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
13221 	       dmult);
13222 	switch (eq->entry_count) {
13223 	default:
13224 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13225 				"0360 Unsupported EQ count. (%d)\n",
13226 				eq->entry_count);
13227 		if (eq->entry_count < 256)
13228 			return -EINVAL;
13229 		/* otherwise default to smallest count (drop through) */
13230 	case 256:
13231 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13232 		       LPFC_EQ_CNT_256);
13233 		break;
13234 	case 512:
13235 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13236 		       LPFC_EQ_CNT_512);
13237 		break;
13238 	case 1024:
13239 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13240 		       LPFC_EQ_CNT_1024);
13241 		break;
13242 	case 2048:
13243 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13244 		       LPFC_EQ_CNT_2048);
13245 		break;
13246 	case 4096:
13247 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
13248 		       LPFC_EQ_CNT_4096);
13249 		break;
13250 	}
13251 	list_for_each_entry(dmabuf, &eq->page_list, list) {
13252 		memset(dmabuf->virt, 0, hw_page_size);
13253 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13254 					putPaddrLow(dmabuf->phys);
13255 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13256 					putPaddrHigh(dmabuf->phys);
13257 	}
13258 	mbox->vport = phba->pport;
13259 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13260 	mbox->context1 = NULL;
13261 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13262 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
13263 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13264 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13265 	if (shdr_status || shdr_add_status || rc) {
13266 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13267 				"2500 EQ_CREATE mailbox failed with "
13268 				"status x%x add_status x%x, mbx status x%x\n",
13269 				shdr_status, shdr_add_status, rc);
13270 		status = -ENXIO;
13271 	}
13272 	eq->type = LPFC_EQ;
13273 	eq->subtype = LPFC_NONE;
13274 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
13275 	if (eq->queue_id == 0xFFFF)
13276 		status = -ENXIO;
13277 	eq->host_index = 0;
13278 	eq->hba_index = 0;
13279 
13280 	mempool_free(mbox, phba->mbox_mem_pool);
13281 	return status;
13282 }
13283 
13284 /**
13285  * lpfc_cq_create - Create a Completion Queue on the HBA
13286  * @phba: HBA structure that indicates port to create a queue on.
13287  * @cq: The queue structure to use to create the completion queue.
13288  * @eq: The event queue to bind this completion queue to.
13289  *
13290  * This function creates a completion queue, as detailed in @wq, on a port,
13291  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
13292  *
13293  * The @phba struct is used to send mailbox command to HBA. The @cq struct
13294  * is used to get the entry count and entry size that are necessary to
13295  * determine the number of pages to allocate and use for this queue. The @eq
13296  * is used to indicate which event queue to bind this completion queue to. This
13297  * function will send the CQ_CREATE mailbox command to the HBA to setup the
13298  * completion queue. This function is asynchronous and will wait for the mailbox
13299  * command to finish before continuing.
13300  *
13301  * On success this function will return a zero. If unable to allocate enough
13302  * memory this function will return -ENOMEM. If the queue create mailbox command
13303  * fails this function will return -ENXIO.
13304  **/
13305 int
13306 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
13307 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
13308 {
13309 	struct lpfc_mbx_cq_create *cq_create;
13310 	struct lpfc_dmabuf *dmabuf;
13311 	LPFC_MBOXQ_t *mbox;
13312 	int rc, length, status = 0;
13313 	uint32_t shdr_status, shdr_add_status;
13314 	union lpfc_sli4_cfg_shdr *shdr;
13315 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13316 
13317 	/* sanity check on queue memory */
13318 	if (!cq || !eq)
13319 		return -ENODEV;
13320 	if (!phba->sli4_hba.pc_sli4_params.supported)
13321 		hw_page_size = SLI4_PAGE_SIZE;
13322 
13323 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13324 	if (!mbox)
13325 		return -ENOMEM;
13326 	length = (sizeof(struct lpfc_mbx_cq_create) -
13327 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13328 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13329 			 LPFC_MBOX_OPCODE_CQ_CREATE,
13330 			 length, LPFC_SLI4_MBX_EMBED);
13331 	cq_create = &mbox->u.mqe.un.cq_create;
13332 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
13333 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
13334 		    cq->page_count);
13335 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
13336 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
13337 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13338 	       phba->sli4_hba.pc_sli4_params.cqv);
13339 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
13340 		/* FW only supports 1. Should be PAGE_SIZE/SLI4_PAGE_SIZE */
13341 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request, 1);
13342 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
13343 		       eq->queue_id);
13344 	} else {
13345 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
13346 		       eq->queue_id);
13347 	}
13348 	switch (cq->entry_count) {
13349 	default:
13350 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13351 				"0361 Unsupported CQ count. (%d)\n",
13352 				cq->entry_count);
13353 		if (cq->entry_count < 256) {
13354 			status = -EINVAL;
13355 			goto out;
13356 		}
13357 		/* otherwise default to smallest count (drop through) */
13358 	case 256:
13359 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
13360 		       LPFC_CQ_CNT_256);
13361 		break;
13362 	case 512:
13363 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
13364 		       LPFC_CQ_CNT_512);
13365 		break;
13366 	case 1024:
13367 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
13368 		       LPFC_CQ_CNT_1024);
13369 		break;
13370 	}
13371 	list_for_each_entry(dmabuf, &cq->page_list, list) {
13372 		memset(dmabuf->virt, 0, hw_page_size);
13373 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13374 					putPaddrLow(dmabuf->phys);
13375 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13376 					putPaddrHigh(dmabuf->phys);
13377 	}
13378 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13379 
13380 	/* The IOCTL status is embedded in the mailbox subheader. */
13381 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13382 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13383 	if (shdr_status || shdr_add_status || rc) {
13384 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13385 				"2501 CQ_CREATE mailbox failed with "
13386 				"status x%x add_status x%x, mbx status x%x\n",
13387 				shdr_status, shdr_add_status, rc);
13388 		status = -ENXIO;
13389 		goto out;
13390 	}
13391 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
13392 	if (cq->queue_id == 0xFFFF) {
13393 		status = -ENXIO;
13394 		goto out;
13395 	}
13396 	/* link the cq onto the parent eq child list */
13397 	list_add_tail(&cq->list, &eq->child_list);
13398 	/* Set up completion queue's type and subtype */
13399 	cq->type = type;
13400 	cq->subtype = subtype;
13401 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
13402 	cq->assoc_qid = eq->queue_id;
13403 	cq->host_index = 0;
13404 	cq->hba_index = 0;
13405 
13406 out:
13407 	mempool_free(mbox, phba->mbox_mem_pool);
13408 	return status;
13409 }
13410 
13411 /**
13412  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
13413  * @phba: HBA structure that indicates port to create a queue on.
13414  * @mq: The queue structure to use to create the mailbox queue.
13415  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
13416  * @cq: The completion queue to associate with this cq.
13417  *
13418  * This function provides failback (fb) functionality when the
13419  * mq_create_ext fails on older FW generations.  It's purpose is identical
13420  * to mq_create_ext otherwise.
13421  *
13422  * This routine cannot fail as all attributes were previously accessed and
13423  * initialized in mq_create_ext.
13424  **/
13425 static void
13426 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
13427 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
13428 {
13429 	struct lpfc_mbx_mq_create *mq_create;
13430 	struct lpfc_dmabuf *dmabuf;
13431 	int length;
13432 
13433 	length = (sizeof(struct lpfc_mbx_mq_create) -
13434 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13435 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13436 			 LPFC_MBOX_OPCODE_MQ_CREATE,
13437 			 length, LPFC_SLI4_MBX_EMBED);
13438 	mq_create = &mbox->u.mqe.un.mq_create;
13439 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
13440 	       mq->page_count);
13441 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
13442 	       cq->queue_id);
13443 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
13444 	switch (mq->entry_count) {
13445 	case 16:
13446 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13447 		       LPFC_MQ_RING_SIZE_16);
13448 		break;
13449 	case 32:
13450 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13451 		       LPFC_MQ_RING_SIZE_32);
13452 		break;
13453 	case 64:
13454 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13455 		       LPFC_MQ_RING_SIZE_64);
13456 		break;
13457 	case 128:
13458 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
13459 		       LPFC_MQ_RING_SIZE_128);
13460 		break;
13461 	}
13462 	list_for_each_entry(dmabuf, &mq->page_list, list) {
13463 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13464 			putPaddrLow(dmabuf->phys);
13465 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13466 			putPaddrHigh(dmabuf->phys);
13467 	}
13468 }
13469 
13470 /**
13471  * lpfc_mq_create - Create a mailbox Queue on the HBA
13472  * @phba: HBA structure that indicates port to create a queue on.
13473  * @mq: The queue structure to use to create the mailbox queue.
13474  * @cq: The completion queue to associate with this cq.
13475  * @subtype: The queue's subtype.
13476  *
13477  * This function creates a mailbox queue, as detailed in @mq, on a port,
13478  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
13479  *
13480  * The @phba struct is used to send mailbox command to HBA. The @cq struct
13481  * is used to get the entry count and entry size that are necessary to
13482  * determine the number of pages to allocate and use for this queue. This
13483  * function will send the MQ_CREATE mailbox command to the HBA to setup the
13484  * mailbox queue. This function is asynchronous and will wait for the mailbox
13485  * command to finish before continuing.
13486  *
13487  * On success this function will return a zero. If unable to allocate enough
13488  * memory this function will return -ENOMEM. If the queue create mailbox command
13489  * fails this function will return -ENXIO.
13490  **/
13491 int32_t
13492 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
13493 	       struct lpfc_queue *cq, uint32_t subtype)
13494 {
13495 	struct lpfc_mbx_mq_create *mq_create;
13496 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
13497 	struct lpfc_dmabuf *dmabuf;
13498 	LPFC_MBOXQ_t *mbox;
13499 	int rc, length, status = 0;
13500 	uint32_t shdr_status, shdr_add_status;
13501 	union lpfc_sli4_cfg_shdr *shdr;
13502 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13503 
13504 	/* sanity check on queue memory */
13505 	if (!mq || !cq)
13506 		return -ENODEV;
13507 	if (!phba->sli4_hba.pc_sli4_params.supported)
13508 		hw_page_size = SLI4_PAGE_SIZE;
13509 
13510 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13511 	if (!mbox)
13512 		return -ENOMEM;
13513 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
13514 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13515 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
13516 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
13517 			 length, LPFC_SLI4_MBX_EMBED);
13518 
13519 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
13520 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
13521 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
13522 	       &mq_create_ext->u.request, mq->page_count);
13523 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
13524 	       &mq_create_ext->u.request, 1);
13525 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
13526 	       &mq_create_ext->u.request, 1);
13527 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
13528 	       &mq_create_ext->u.request, 1);
13529 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
13530 	       &mq_create_ext->u.request, 1);
13531 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
13532 	       &mq_create_ext->u.request, 1);
13533 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
13534 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13535 	       phba->sli4_hba.pc_sli4_params.mqv);
13536 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
13537 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
13538 		       cq->queue_id);
13539 	else
13540 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
13541 		       cq->queue_id);
13542 	switch (mq->entry_count) {
13543 	default:
13544 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13545 				"0362 Unsupported MQ count. (%d)\n",
13546 				mq->entry_count);
13547 		if (mq->entry_count < 16) {
13548 			status = -EINVAL;
13549 			goto out;
13550 		}
13551 		/* otherwise default to smallest count (drop through) */
13552 	case 16:
13553 		bf_set(lpfc_mq_context_ring_size,
13554 		       &mq_create_ext->u.request.context,
13555 		       LPFC_MQ_RING_SIZE_16);
13556 		break;
13557 	case 32:
13558 		bf_set(lpfc_mq_context_ring_size,
13559 		       &mq_create_ext->u.request.context,
13560 		       LPFC_MQ_RING_SIZE_32);
13561 		break;
13562 	case 64:
13563 		bf_set(lpfc_mq_context_ring_size,
13564 		       &mq_create_ext->u.request.context,
13565 		       LPFC_MQ_RING_SIZE_64);
13566 		break;
13567 	case 128:
13568 		bf_set(lpfc_mq_context_ring_size,
13569 		       &mq_create_ext->u.request.context,
13570 		       LPFC_MQ_RING_SIZE_128);
13571 		break;
13572 	}
13573 	list_for_each_entry(dmabuf, &mq->page_list, list) {
13574 		memset(dmabuf->virt, 0, hw_page_size);
13575 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
13576 					putPaddrLow(dmabuf->phys);
13577 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
13578 					putPaddrHigh(dmabuf->phys);
13579 	}
13580 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13581 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
13582 			      &mq_create_ext->u.response);
13583 	if (rc != MBX_SUCCESS) {
13584 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13585 				"2795 MQ_CREATE_EXT failed with "
13586 				"status x%x. Failback to MQ_CREATE.\n",
13587 				rc);
13588 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
13589 		mq_create = &mbox->u.mqe.un.mq_create;
13590 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13591 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
13592 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
13593 				      &mq_create->u.response);
13594 	}
13595 
13596 	/* The IOCTL status is embedded in the mailbox subheader. */
13597 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13598 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13599 	if (shdr_status || shdr_add_status || rc) {
13600 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13601 				"2502 MQ_CREATE mailbox failed with "
13602 				"status x%x add_status x%x, mbx status x%x\n",
13603 				shdr_status, shdr_add_status, rc);
13604 		status = -ENXIO;
13605 		goto out;
13606 	}
13607 	if (mq->queue_id == 0xFFFF) {
13608 		status = -ENXIO;
13609 		goto out;
13610 	}
13611 	mq->type = LPFC_MQ;
13612 	mq->assoc_qid = cq->queue_id;
13613 	mq->subtype = subtype;
13614 	mq->host_index = 0;
13615 	mq->hba_index = 0;
13616 
13617 	/* link the mq onto the parent cq child list */
13618 	list_add_tail(&mq->list, &cq->child_list);
13619 out:
13620 	mempool_free(mbox, phba->mbox_mem_pool);
13621 	return status;
13622 }
13623 
13624 /**
13625  * lpfc_wq_create - Create a Work Queue on the HBA
13626  * @phba: HBA structure that indicates port to create a queue on.
13627  * @wq: The queue structure to use to create the work queue.
13628  * @cq: The completion queue to bind this work queue to.
13629  * @subtype: The subtype of the work queue indicating its functionality.
13630  *
13631  * This function creates a work queue, as detailed in @wq, on a port, described
13632  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
13633  *
13634  * The @phba struct is used to send mailbox command to HBA. The @wq struct
13635  * is used to get the entry count and entry size that are necessary to
13636  * determine the number of pages to allocate and use for this queue. The @cq
13637  * is used to indicate which completion queue to bind this work queue to. This
13638  * function will send the WQ_CREATE mailbox command to the HBA to setup the
13639  * work queue. This function is asynchronous and will wait for the mailbox
13640  * command to finish before continuing.
13641  *
13642  * On success this function will return a zero. If unable to allocate enough
13643  * memory this function will return -ENOMEM. If the queue create mailbox command
13644  * fails this function will return -ENXIO.
13645  **/
13646 int
13647 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
13648 	       struct lpfc_queue *cq, uint32_t subtype)
13649 {
13650 	struct lpfc_mbx_wq_create *wq_create;
13651 	struct lpfc_dmabuf *dmabuf;
13652 	LPFC_MBOXQ_t *mbox;
13653 	int rc, length, status = 0;
13654 	uint32_t shdr_status, shdr_add_status;
13655 	union lpfc_sli4_cfg_shdr *shdr;
13656 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13657 	struct dma_address *page;
13658 	void __iomem *bar_memmap_p;
13659 	uint32_t db_offset;
13660 	uint16_t pci_barset;
13661 
13662 	/* sanity check on queue memory */
13663 	if (!wq || !cq)
13664 		return -ENODEV;
13665 	if (!phba->sli4_hba.pc_sli4_params.supported)
13666 		hw_page_size = SLI4_PAGE_SIZE;
13667 
13668 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13669 	if (!mbox)
13670 		return -ENOMEM;
13671 	length = (sizeof(struct lpfc_mbx_wq_create) -
13672 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13673 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
13674 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
13675 			 length, LPFC_SLI4_MBX_EMBED);
13676 	wq_create = &mbox->u.mqe.un.wq_create;
13677 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
13678 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
13679 		    wq->page_count);
13680 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
13681 		    cq->queue_id);
13682 
13683 	/* wqv is the earliest version supported, NOT the latest */
13684 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13685 	       phba->sli4_hba.pc_sli4_params.wqv);
13686 
13687 	switch (phba->sli4_hba.pc_sli4_params.wqv) {
13688 	case LPFC_Q_CREATE_VERSION_0:
13689 		switch (wq->entry_size) {
13690 		default:
13691 		case 64:
13692 			/* Nothing to do, version 0 ONLY supports 64 byte */
13693 			page = wq_create->u.request.page;
13694 			break;
13695 		case 128:
13696 			if (!(phba->sli4_hba.pc_sli4_params.wqsize &
13697 			    LPFC_WQ_SZ128_SUPPORT)) {
13698 				status = -ERANGE;
13699 				goto out;
13700 			}
13701 			/* If we get here the HBA MUST also support V1 and
13702 			 * we MUST use it
13703 			 */
13704 			bf_set(lpfc_mbox_hdr_version, &shdr->request,
13705 			       LPFC_Q_CREATE_VERSION_1);
13706 
13707 			bf_set(lpfc_mbx_wq_create_wqe_count,
13708 			       &wq_create->u.request_1, wq->entry_count);
13709 			bf_set(lpfc_mbx_wq_create_wqe_size,
13710 			       &wq_create->u.request_1,
13711 			       LPFC_WQ_WQE_SIZE_128);
13712 			bf_set(lpfc_mbx_wq_create_page_size,
13713 			       &wq_create->u.request_1,
13714 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
13715 			page = wq_create->u.request_1.page;
13716 			break;
13717 		}
13718 		break;
13719 	case LPFC_Q_CREATE_VERSION_1:
13720 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
13721 		       wq->entry_count);
13722 		switch (wq->entry_size) {
13723 		default:
13724 		case 64:
13725 			bf_set(lpfc_mbx_wq_create_wqe_size,
13726 			       &wq_create->u.request_1,
13727 			       LPFC_WQ_WQE_SIZE_64);
13728 			break;
13729 		case 128:
13730 			if (!(phba->sli4_hba.pc_sli4_params.wqsize &
13731 				LPFC_WQ_SZ128_SUPPORT)) {
13732 				status = -ERANGE;
13733 				goto out;
13734 			}
13735 			bf_set(lpfc_mbx_wq_create_wqe_size,
13736 			       &wq_create->u.request_1,
13737 			       LPFC_WQ_WQE_SIZE_128);
13738 			break;
13739 		}
13740 		bf_set(lpfc_mbx_wq_create_page_size, &wq_create->u.request_1,
13741 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
13742 		page = wq_create->u.request_1.page;
13743 		break;
13744 	default:
13745 		status = -ERANGE;
13746 		goto out;
13747 	}
13748 
13749 	list_for_each_entry(dmabuf, &wq->page_list, list) {
13750 		memset(dmabuf->virt, 0, hw_page_size);
13751 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
13752 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
13753 	}
13754 
13755 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
13756 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
13757 
13758 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13759 	/* The IOCTL status is embedded in the mailbox subheader. */
13760 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13761 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13762 	if (shdr_status || shdr_add_status || rc) {
13763 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13764 				"2503 WQ_CREATE mailbox failed with "
13765 				"status x%x add_status x%x, mbx status x%x\n",
13766 				shdr_status, shdr_add_status, rc);
13767 		status = -ENXIO;
13768 		goto out;
13769 	}
13770 	wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id, &wq_create->u.response);
13771 	if (wq->queue_id == 0xFFFF) {
13772 		status = -ENXIO;
13773 		goto out;
13774 	}
13775 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
13776 		wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
13777 				       &wq_create->u.response);
13778 		if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
13779 		    (wq->db_format != LPFC_DB_RING_FORMAT)) {
13780 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13781 					"3265 WQ[%d] doorbell format not "
13782 					"supported: x%x\n", wq->queue_id,
13783 					wq->db_format);
13784 			status = -EINVAL;
13785 			goto out;
13786 		}
13787 		pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
13788 				    &wq_create->u.response);
13789 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
13790 		if (!bar_memmap_p) {
13791 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13792 					"3263 WQ[%d] failed to memmap pci "
13793 					"barset:x%x\n", wq->queue_id,
13794 					pci_barset);
13795 			status = -ENOMEM;
13796 			goto out;
13797 		}
13798 		db_offset = wq_create->u.response.doorbell_offset;
13799 		if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
13800 		    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
13801 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13802 					"3252 WQ[%d] doorbell offset not "
13803 					"supported: x%x\n", wq->queue_id,
13804 					db_offset);
13805 			status = -EINVAL;
13806 			goto out;
13807 		}
13808 		wq->db_regaddr = bar_memmap_p + db_offset;
13809 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
13810 				"3264 WQ[%d]: barset:x%x, offset:x%x, "
13811 				"format:x%x\n", wq->queue_id, pci_barset,
13812 				db_offset, wq->db_format);
13813 	} else {
13814 		wq->db_format = LPFC_DB_LIST_FORMAT;
13815 		wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
13816 	}
13817 	wq->type = LPFC_WQ;
13818 	wq->assoc_qid = cq->queue_id;
13819 	wq->subtype = subtype;
13820 	wq->host_index = 0;
13821 	wq->hba_index = 0;
13822 	wq->entry_repost = LPFC_RELEASE_NOTIFICATION_INTERVAL;
13823 
13824 	/* link the wq onto the parent cq child list */
13825 	list_add_tail(&wq->list, &cq->child_list);
13826 out:
13827 	mempool_free(mbox, phba->mbox_mem_pool);
13828 	return status;
13829 }
13830 
13831 /**
13832  * lpfc_rq_adjust_repost - Adjust entry_repost for an RQ
13833  * @phba: HBA structure that indicates port to create a queue on.
13834  * @rq:   The queue structure to use for the receive queue.
13835  * @qno:  The associated HBQ number
13836  *
13837  *
13838  * For SLI4 we need to adjust the RQ repost value based on
13839  * the number of buffers that are initially posted to the RQ.
13840  */
13841 void
13842 lpfc_rq_adjust_repost(struct lpfc_hba *phba, struct lpfc_queue *rq, int qno)
13843 {
13844 	uint32_t cnt;
13845 
13846 	/* sanity check on queue memory */
13847 	if (!rq)
13848 		return;
13849 	cnt = lpfc_hbq_defs[qno]->entry_count;
13850 
13851 	/* Recalc repost for RQs based on buffers initially posted */
13852 	cnt = (cnt >> 3);
13853 	if (cnt < LPFC_QUEUE_MIN_REPOST)
13854 		cnt = LPFC_QUEUE_MIN_REPOST;
13855 
13856 	rq->entry_repost = cnt;
13857 }
13858 
13859 /**
13860  * lpfc_rq_create - Create a Receive Queue on the HBA
13861  * @phba: HBA structure that indicates port to create a queue on.
13862  * @hrq: The queue structure to use to create the header receive queue.
13863  * @drq: The queue structure to use to create the data receive queue.
13864  * @cq: The completion queue to bind this work queue to.
13865  *
13866  * This function creates a receive buffer queue pair , as detailed in @hrq and
13867  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
13868  * to the HBA.
13869  *
13870  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
13871  * struct is used to get the entry count that is necessary to determine the
13872  * number of pages to use for this queue. The @cq is used to indicate which
13873  * completion queue to bind received buffers that are posted to these queues to.
13874  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
13875  * receive queue pair. This function is asynchronous and will wait for the
13876  * mailbox command to finish before continuing.
13877  *
13878  * On success this function will return a zero. If unable to allocate enough
13879  * memory this function will return -ENOMEM. If the queue create mailbox command
13880  * fails this function will return -ENXIO.
13881  **/
13882 int
13883 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
13884 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
13885 {
13886 	struct lpfc_mbx_rq_create *rq_create;
13887 	struct lpfc_dmabuf *dmabuf;
13888 	LPFC_MBOXQ_t *mbox;
13889 	int rc, length, status = 0;
13890 	uint32_t shdr_status, shdr_add_status;
13891 	union lpfc_sli4_cfg_shdr *shdr;
13892 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
13893 	void __iomem *bar_memmap_p;
13894 	uint32_t db_offset;
13895 	uint16_t pci_barset;
13896 
13897 	/* sanity check on queue memory */
13898 	if (!hrq || !drq || !cq)
13899 		return -ENODEV;
13900 	if (!phba->sli4_hba.pc_sli4_params.supported)
13901 		hw_page_size = SLI4_PAGE_SIZE;
13902 
13903 	if (hrq->entry_count != drq->entry_count)
13904 		return -EINVAL;
13905 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
13906 	if (!mbox)
13907 		return -ENOMEM;
13908 	length = (sizeof(struct lpfc_mbx_rq_create) -
13909 		  sizeof(struct lpfc_sli4_cfg_mhdr));
13910 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
13911 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
13912 			 length, LPFC_SLI4_MBX_EMBED);
13913 	rq_create = &mbox->u.mqe.un.rq_create;
13914 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
13915 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
13916 	       phba->sli4_hba.pc_sli4_params.rqv);
13917 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
13918 		bf_set(lpfc_rq_context_rqe_count_1,
13919 		       &rq_create->u.request.context,
13920 		       hrq->entry_count);
13921 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
13922 		bf_set(lpfc_rq_context_rqe_size,
13923 		       &rq_create->u.request.context,
13924 		       LPFC_RQE_SIZE_8);
13925 		bf_set(lpfc_rq_context_page_size,
13926 		       &rq_create->u.request.context,
13927 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
13928 	} else {
13929 		switch (hrq->entry_count) {
13930 		default:
13931 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13932 					"2535 Unsupported RQ count. (%d)\n",
13933 					hrq->entry_count);
13934 			if (hrq->entry_count < 512) {
13935 				status = -EINVAL;
13936 				goto out;
13937 			}
13938 			/* otherwise default to smallest count (drop through) */
13939 		case 512:
13940 			bf_set(lpfc_rq_context_rqe_count,
13941 			       &rq_create->u.request.context,
13942 			       LPFC_RQ_RING_SIZE_512);
13943 			break;
13944 		case 1024:
13945 			bf_set(lpfc_rq_context_rqe_count,
13946 			       &rq_create->u.request.context,
13947 			       LPFC_RQ_RING_SIZE_1024);
13948 			break;
13949 		case 2048:
13950 			bf_set(lpfc_rq_context_rqe_count,
13951 			       &rq_create->u.request.context,
13952 			       LPFC_RQ_RING_SIZE_2048);
13953 			break;
13954 		case 4096:
13955 			bf_set(lpfc_rq_context_rqe_count,
13956 			       &rq_create->u.request.context,
13957 			       LPFC_RQ_RING_SIZE_4096);
13958 			break;
13959 		}
13960 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
13961 		       LPFC_HDR_BUF_SIZE);
13962 	}
13963 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
13964 	       cq->queue_id);
13965 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
13966 	       hrq->page_count);
13967 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
13968 		memset(dmabuf->virt, 0, hw_page_size);
13969 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
13970 					putPaddrLow(dmabuf->phys);
13971 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
13972 					putPaddrHigh(dmabuf->phys);
13973 	}
13974 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
13975 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
13976 
13977 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
13978 	/* The IOCTL status is embedded in the mailbox subheader. */
13979 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
13980 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
13981 	if (shdr_status || shdr_add_status || rc) {
13982 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
13983 				"2504 RQ_CREATE mailbox failed with "
13984 				"status x%x add_status x%x, mbx status x%x\n",
13985 				shdr_status, shdr_add_status, rc);
13986 		status = -ENXIO;
13987 		goto out;
13988 	}
13989 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
13990 	if (hrq->queue_id == 0xFFFF) {
13991 		status = -ENXIO;
13992 		goto out;
13993 	}
13994 
13995 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
13996 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
13997 					&rq_create->u.response);
13998 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
13999 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
14000 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14001 					"3262 RQ [%d] doorbell format not "
14002 					"supported: x%x\n", hrq->queue_id,
14003 					hrq->db_format);
14004 			status = -EINVAL;
14005 			goto out;
14006 		}
14007 
14008 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
14009 				    &rq_create->u.response);
14010 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
14011 		if (!bar_memmap_p) {
14012 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14013 					"3269 RQ[%d] failed to memmap pci "
14014 					"barset:x%x\n", hrq->queue_id,
14015 					pci_barset);
14016 			status = -ENOMEM;
14017 			goto out;
14018 		}
14019 
14020 		db_offset = rq_create->u.response.doorbell_offset;
14021 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
14022 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
14023 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14024 					"3270 RQ[%d] doorbell offset not "
14025 					"supported: x%x\n", hrq->queue_id,
14026 					db_offset);
14027 			status = -EINVAL;
14028 			goto out;
14029 		}
14030 		hrq->db_regaddr = bar_memmap_p + db_offset;
14031 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
14032 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
14033 				"format:x%x\n", hrq->queue_id, pci_barset,
14034 				db_offset, hrq->db_format);
14035 	} else {
14036 		hrq->db_format = LPFC_DB_RING_FORMAT;
14037 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
14038 	}
14039 	hrq->type = LPFC_HRQ;
14040 	hrq->assoc_qid = cq->queue_id;
14041 	hrq->subtype = subtype;
14042 	hrq->host_index = 0;
14043 	hrq->hba_index = 0;
14044 
14045 	/* now create the data queue */
14046 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14047 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
14048 			 length, LPFC_SLI4_MBX_EMBED);
14049 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
14050 	       phba->sli4_hba.pc_sli4_params.rqv);
14051 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
14052 		bf_set(lpfc_rq_context_rqe_count_1,
14053 		       &rq_create->u.request.context, hrq->entry_count);
14054 		rq_create->u.request.context.buffer_size = LPFC_DATA_BUF_SIZE;
14055 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
14056 		       LPFC_RQE_SIZE_8);
14057 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
14058 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
14059 	} else {
14060 		switch (drq->entry_count) {
14061 		default:
14062 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14063 					"2536 Unsupported RQ count. (%d)\n",
14064 					drq->entry_count);
14065 			if (drq->entry_count < 512) {
14066 				status = -EINVAL;
14067 				goto out;
14068 			}
14069 			/* otherwise default to smallest count (drop through) */
14070 		case 512:
14071 			bf_set(lpfc_rq_context_rqe_count,
14072 			       &rq_create->u.request.context,
14073 			       LPFC_RQ_RING_SIZE_512);
14074 			break;
14075 		case 1024:
14076 			bf_set(lpfc_rq_context_rqe_count,
14077 			       &rq_create->u.request.context,
14078 			       LPFC_RQ_RING_SIZE_1024);
14079 			break;
14080 		case 2048:
14081 			bf_set(lpfc_rq_context_rqe_count,
14082 			       &rq_create->u.request.context,
14083 			       LPFC_RQ_RING_SIZE_2048);
14084 			break;
14085 		case 4096:
14086 			bf_set(lpfc_rq_context_rqe_count,
14087 			       &rq_create->u.request.context,
14088 			       LPFC_RQ_RING_SIZE_4096);
14089 			break;
14090 		}
14091 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
14092 		       LPFC_DATA_BUF_SIZE);
14093 	}
14094 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
14095 	       cq->queue_id);
14096 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
14097 	       drq->page_count);
14098 	list_for_each_entry(dmabuf, &drq->page_list, list) {
14099 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
14100 					putPaddrLow(dmabuf->phys);
14101 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
14102 					putPaddrHigh(dmabuf->phys);
14103 	}
14104 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
14105 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
14106 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14107 	/* The IOCTL status is embedded in the mailbox subheader. */
14108 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
14109 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14110 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14111 	if (shdr_status || shdr_add_status || rc) {
14112 		status = -ENXIO;
14113 		goto out;
14114 	}
14115 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
14116 	if (drq->queue_id == 0xFFFF) {
14117 		status = -ENXIO;
14118 		goto out;
14119 	}
14120 	drq->type = LPFC_DRQ;
14121 	drq->assoc_qid = cq->queue_id;
14122 	drq->subtype = subtype;
14123 	drq->host_index = 0;
14124 	drq->hba_index = 0;
14125 
14126 	/* link the header and data RQs onto the parent cq child list */
14127 	list_add_tail(&hrq->list, &cq->child_list);
14128 	list_add_tail(&drq->list, &cq->child_list);
14129 
14130 out:
14131 	mempool_free(mbox, phba->mbox_mem_pool);
14132 	return status;
14133 }
14134 
14135 /**
14136  * lpfc_eq_destroy - Destroy an event Queue on the HBA
14137  * @eq: The queue structure associated with the queue to destroy.
14138  *
14139  * This function destroys a queue, as detailed in @eq by sending an mailbox
14140  * command, specific to the type of queue, to the HBA.
14141  *
14142  * The @eq struct is used to get the queue ID of the queue to destroy.
14143  *
14144  * On success this function will return a zero. If the queue destroy mailbox
14145  * command fails this function will return -ENXIO.
14146  **/
14147 int
14148 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
14149 {
14150 	LPFC_MBOXQ_t *mbox;
14151 	int rc, length, status = 0;
14152 	uint32_t shdr_status, shdr_add_status;
14153 	union lpfc_sli4_cfg_shdr *shdr;
14154 
14155 	/* sanity check on queue memory */
14156 	if (!eq)
14157 		return -ENODEV;
14158 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
14159 	if (!mbox)
14160 		return -ENOMEM;
14161 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
14162 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14163 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14164 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
14165 			 length, LPFC_SLI4_MBX_EMBED);
14166 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
14167 	       eq->queue_id);
14168 	mbox->vport = eq->phba->pport;
14169 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14170 
14171 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
14172 	/* The IOCTL status is embedded in the mailbox subheader. */
14173 	shdr = (union lpfc_sli4_cfg_shdr *)
14174 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
14175 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14176 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14177 	if (shdr_status || shdr_add_status || rc) {
14178 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14179 				"2505 EQ_DESTROY mailbox failed with "
14180 				"status x%x add_status x%x, mbx status x%x\n",
14181 				shdr_status, shdr_add_status, rc);
14182 		status = -ENXIO;
14183 	}
14184 
14185 	/* Remove eq from any list */
14186 	list_del_init(&eq->list);
14187 	mempool_free(mbox, eq->phba->mbox_mem_pool);
14188 	return status;
14189 }
14190 
14191 /**
14192  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
14193  * @cq: The queue structure associated with the queue to destroy.
14194  *
14195  * This function destroys a queue, as detailed in @cq by sending an mailbox
14196  * command, specific to the type of queue, to the HBA.
14197  *
14198  * The @cq struct is used to get the queue ID of the queue to destroy.
14199  *
14200  * On success this function will return a zero. If the queue destroy mailbox
14201  * command fails this function will return -ENXIO.
14202  **/
14203 int
14204 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
14205 {
14206 	LPFC_MBOXQ_t *mbox;
14207 	int rc, length, status = 0;
14208 	uint32_t shdr_status, shdr_add_status;
14209 	union lpfc_sli4_cfg_shdr *shdr;
14210 
14211 	/* sanity check on queue memory */
14212 	if (!cq)
14213 		return -ENODEV;
14214 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
14215 	if (!mbox)
14216 		return -ENOMEM;
14217 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
14218 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14219 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14220 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
14221 			 length, LPFC_SLI4_MBX_EMBED);
14222 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
14223 	       cq->queue_id);
14224 	mbox->vport = cq->phba->pport;
14225 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14226 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
14227 	/* The IOCTL status is embedded in the mailbox subheader. */
14228 	shdr = (union lpfc_sli4_cfg_shdr *)
14229 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
14230 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14231 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14232 	if (shdr_status || shdr_add_status || rc) {
14233 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14234 				"2506 CQ_DESTROY mailbox failed with "
14235 				"status x%x add_status x%x, mbx status x%x\n",
14236 				shdr_status, shdr_add_status, rc);
14237 		status = -ENXIO;
14238 	}
14239 	/* Remove cq from any list */
14240 	list_del_init(&cq->list);
14241 	mempool_free(mbox, cq->phba->mbox_mem_pool);
14242 	return status;
14243 }
14244 
14245 /**
14246  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
14247  * @qm: The queue structure associated with the queue to destroy.
14248  *
14249  * This function destroys a queue, as detailed in @mq by sending an mailbox
14250  * command, specific to the type of queue, to the HBA.
14251  *
14252  * The @mq struct is used to get the queue ID of the queue to destroy.
14253  *
14254  * On success this function will return a zero. If the queue destroy mailbox
14255  * command fails this function will return -ENXIO.
14256  **/
14257 int
14258 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
14259 {
14260 	LPFC_MBOXQ_t *mbox;
14261 	int rc, length, status = 0;
14262 	uint32_t shdr_status, shdr_add_status;
14263 	union lpfc_sli4_cfg_shdr *shdr;
14264 
14265 	/* sanity check on queue memory */
14266 	if (!mq)
14267 		return -ENODEV;
14268 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
14269 	if (!mbox)
14270 		return -ENOMEM;
14271 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
14272 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14273 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14274 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
14275 			 length, LPFC_SLI4_MBX_EMBED);
14276 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
14277 	       mq->queue_id);
14278 	mbox->vport = mq->phba->pport;
14279 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14280 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
14281 	/* The IOCTL status is embedded in the mailbox subheader. */
14282 	shdr = (union lpfc_sli4_cfg_shdr *)
14283 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
14284 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14285 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14286 	if (shdr_status || shdr_add_status || rc) {
14287 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14288 				"2507 MQ_DESTROY mailbox failed with "
14289 				"status x%x add_status x%x, mbx status x%x\n",
14290 				shdr_status, shdr_add_status, rc);
14291 		status = -ENXIO;
14292 	}
14293 	/* Remove mq from any list */
14294 	list_del_init(&mq->list);
14295 	mempool_free(mbox, mq->phba->mbox_mem_pool);
14296 	return status;
14297 }
14298 
14299 /**
14300  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
14301  * @wq: The queue structure associated with the queue to destroy.
14302  *
14303  * This function destroys a queue, as detailed in @wq by sending an mailbox
14304  * command, specific to the type of queue, to the HBA.
14305  *
14306  * The @wq struct is used to get the queue ID of the queue to destroy.
14307  *
14308  * On success this function will return a zero. If the queue destroy mailbox
14309  * command fails this function will return -ENXIO.
14310  **/
14311 int
14312 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
14313 {
14314 	LPFC_MBOXQ_t *mbox;
14315 	int rc, length, status = 0;
14316 	uint32_t shdr_status, shdr_add_status;
14317 	union lpfc_sli4_cfg_shdr *shdr;
14318 
14319 	/* sanity check on queue memory */
14320 	if (!wq)
14321 		return -ENODEV;
14322 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
14323 	if (!mbox)
14324 		return -ENOMEM;
14325 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
14326 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14327 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14328 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
14329 			 length, LPFC_SLI4_MBX_EMBED);
14330 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
14331 	       wq->queue_id);
14332 	mbox->vport = wq->phba->pport;
14333 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14334 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
14335 	shdr = (union lpfc_sli4_cfg_shdr *)
14336 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
14337 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14338 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14339 	if (shdr_status || shdr_add_status || rc) {
14340 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14341 				"2508 WQ_DESTROY mailbox failed with "
14342 				"status x%x add_status x%x, mbx status x%x\n",
14343 				shdr_status, shdr_add_status, rc);
14344 		status = -ENXIO;
14345 	}
14346 	/* Remove wq from any list */
14347 	list_del_init(&wq->list);
14348 	mempool_free(mbox, wq->phba->mbox_mem_pool);
14349 	return status;
14350 }
14351 
14352 /**
14353  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
14354  * @rq: The queue structure associated with the queue to destroy.
14355  *
14356  * This function destroys a queue, as detailed in @rq by sending an mailbox
14357  * command, specific to the type of queue, to the HBA.
14358  *
14359  * The @rq struct is used to get the queue ID of the queue to destroy.
14360  *
14361  * On success this function will return a zero. If the queue destroy mailbox
14362  * command fails this function will return -ENXIO.
14363  **/
14364 int
14365 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
14366 		struct lpfc_queue *drq)
14367 {
14368 	LPFC_MBOXQ_t *mbox;
14369 	int rc, length, status = 0;
14370 	uint32_t shdr_status, shdr_add_status;
14371 	union lpfc_sli4_cfg_shdr *shdr;
14372 
14373 	/* sanity check on queue memory */
14374 	if (!hrq || !drq)
14375 		return -ENODEV;
14376 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
14377 	if (!mbox)
14378 		return -ENOMEM;
14379 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
14380 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14381 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14382 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
14383 			 length, LPFC_SLI4_MBX_EMBED);
14384 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
14385 	       hrq->queue_id);
14386 	mbox->vport = hrq->phba->pport;
14387 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14388 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
14389 	/* The IOCTL status is embedded in the mailbox subheader. */
14390 	shdr = (union lpfc_sli4_cfg_shdr *)
14391 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
14392 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14393 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14394 	if (shdr_status || shdr_add_status || rc) {
14395 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14396 				"2509 RQ_DESTROY mailbox failed with "
14397 				"status x%x add_status x%x, mbx status x%x\n",
14398 				shdr_status, shdr_add_status, rc);
14399 		if (rc != MBX_TIMEOUT)
14400 			mempool_free(mbox, hrq->phba->mbox_mem_pool);
14401 		return -ENXIO;
14402 	}
14403 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
14404 	       drq->queue_id);
14405 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
14406 	shdr = (union lpfc_sli4_cfg_shdr *)
14407 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
14408 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14409 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14410 	if (shdr_status || shdr_add_status || rc) {
14411 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14412 				"2510 RQ_DESTROY mailbox failed with "
14413 				"status x%x add_status x%x, mbx status x%x\n",
14414 				shdr_status, shdr_add_status, rc);
14415 		status = -ENXIO;
14416 	}
14417 	list_del_init(&hrq->list);
14418 	list_del_init(&drq->list);
14419 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
14420 	return status;
14421 }
14422 
14423 /**
14424  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
14425  * @phba: The virtual port for which this call being executed.
14426  * @pdma_phys_addr0: Physical address of the 1st SGL page.
14427  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
14428  * @xritag: the xritag that ties this io to the SGL pages.
14429  *
14430  * This routine will post the sgl pages for the IO that has the xritag
14431  * that is in the iocbq structure. The xritag is assigned during iocbq
14432  * creation and persists for as long as the driver is loaded.
14433  * if the caller has fewer than 256 scatter gather segments to map then
14434  * pdma_phys_addr1 should be 0.
14435  * If the caller needs to map more than 256 scatter gather segment then
14436  * pdma_phys_addr1 should be a valid physical address.
14437  * physical address for SGLs must be 64 byte aligned.
14438  * If you are going to map 2 SGL's then the first one must have 256 entries
14439  * the second sgl can have between 1 and 256 entries.
14440  *
14441  * Return codes:
14442  * 	0 - Success
14443  * 	-ENXIO, -ENOMEM - Failure
14444  **/
14445 int
14446 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
14447 		dma_addr_t pdma_phys_addr0,
14448 		dma_addr_t pdma_phys_addr1,
14449 		uint16_t xritag)
14450 {
14451 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
14452 	LPFC_MBOXQ_t *mbox;
14453 	int rc;
14454 	uint32_t shdr_status, shdr_add_status;
14455 	uint32_t mbox_tmo;
14456 	union lpfc_sli4_cfg_shdr *shdr;
14457 
14458 	if (xritag == NO_XRI) {
14459 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14460 				"0364 Invalid param:\n");
14461 		return -EINVAL;
14462 	}
14463 
14464 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14465 	if (!mbox)
14466 		return -ENOMEM;
14467 
14468 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14469 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
14470 			sizeof(struct lpfc_mbx_post_sgl_pages) -
14471 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
14472 
14473 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
14474 				&mbox->u.mqe.un.post_sgl_pages;
14475 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
14476 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
14477 
14478 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
14479 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
14480 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
14481 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
14482 
14483 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
14484 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
14485 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
14486 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
14487 	if (!phba->sli4_hba.intr_enable)
14488 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14489 	else {
14490 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
14491 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
14492 	}
14493 	/* The IOCTL status is embedded in the mailbox subheader. */
14494 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
14495 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14496 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14497 	if (rc != MBX_TIMEOUT)
14498 		mempool_free(mbox, phba->mbox_mem_pool);
14499 	if (shdr_status || shdr_add_status || rc) {
14500 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14501 				"2511 POST_SGL mailbox failed with "
14502 				"status x%x add_status x%x, mbx status x%x\n",
14503 				shdr_status, shdr_add_status, rc);
14504 	}
14505 	return 0;
14506 }
14507 
14508 /**
14509  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
14510  * @phba: pointer to lpfc hba data structure.
14511  *
14512  * This routine is invoked to post rpi header templates to the
14513  * HBA consistent with the SLI-4 interface spec.  This routine
14514  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
14515  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
14516  *
14517  * Returns
14518  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
14519  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
14520  **/
14521 static uint16_t
14522 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
14523 {
14524 	unsigned long xri;
14525 
14526 	/*
14527 	 * Fetch the next logical xri.  Because this index is logical,
14528 	 * the driver starts at 0 each time.
14529 	 */
14530 	spin_lock_irq(&phba->hbalock);
14531 	xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
14532 				 phba->sli4_hba.max_cfg_param.max_xri, 0);
14533 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
14534 		spin_unlock_irq(&phba->hbalock);
14535 		return NO_XRI;
14536 	} else {
14537 		set_bit(xri, phba->sli4_hba.xri_bmask);
14538 		phba->sli4_hba.max_cfg_param.xri_used++;
14539 	}
14540 	spin_unlock_irq(&phba->hbalock);
14541 	return xri;
14542 }
14543 
14544 /**
14545  * lpfc_sli4_free_xri - Release an xri for reuse.
14546  * @phba: pointer to lpfc hba data structure.
14547  *
14548  * This routine is invoked to release an xri to the pool of
14549  * available rpis maintained by the driver.
14550  **/
14551 static void
14552 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
14553 {
14554 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
14555 		phba->sli4_hba.max_cfg_param.xri_used--;
14556 	}
14557 }
14558 
14559 /**
14560  * lpfc_sli4_free_xri - Release an xri for reuse.
14561  * @phba: pointer to lpfc hba data structure.
14562  *
14563  * This routine is invoked to release an xri to the pool of
14564  * available rpis maintained by the driver.
14565  **/
14566 void
14567 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
14568 {
14569 	spin_lock_irq(&phba->hbalock);
14570 	__lpfc_sli4_free_xri(phba, xri);
14571 	spin_unlock_irq(&phba->hbalock);
14572 }
14573 
14574 /**
14575  * lpfc_sli4_next_xritag - Get an xritag for the io
14576  * @phba: Pointer to HBA context object.
14577  *
14578  * This function gets an xritag for the iocb. If there is no unused xritag
14579  * it will return 0xffff.
14580  * The function returns the allocated xritag if successful, else returns zero.
14581  * Zero is not a valid xritag.
14582  * The caller is not required to hold any lock.
14583  **/
14584 uint16_t
14585 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
14586 {
14587 	uint16_t xri_index;
14588 
14589 	xri_index = lpfc_sli4_alloc_xri(phba);
14590 	if (xri_index == NO_XRI)
14591 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14592 				"2004 Failed to allocate XRI.last XRITAG is %d"
14593 				" Max XRI is %d, Used XRI is %d\n",
14594 				xri_index,
14595 				phba->sli4_hba.max_cfg_param.max_xri,
14596 				phba->sli4_hba.max_cfg_param.xri_used);
14597 	return xri_index;
14598 }
14599 
14600 /**
14601  * lpfc_sli4_post_els_sgl_list - post a block of ELS sgls to the port.
14602  * @phba: pointer to lpfc hba data structure.
14603  * @post_sgl_list: pointer to els sgl entry list.
14604  * @count: number of els sgl entries on the list.
14605  *
14606  * This routine is invoked to post a block of driver's sgl pages to the
14607  * HBA using non-embedded mailbox command. No Lock is held. This routine
14608  * is only called when the driver is loading and after all IO has been
14609  * stopped.
14610  **/
14611 static int
14612 lpfc_sli4_post_els_sgl_list(struct lpfc_hba *phba,
14613 			    struct list_head *post_sgl_list,
14614 			    int post_cnt)
14615 {
14616 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
14617 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
14618 	struct sgl_page_pairs *sgl_pg_pairs;
14619 	void *viraddr;
14620 	LPFC_MBOXQ_t *mbox;
14621 	uint32_t reqlen, alloclen, pg_pairs;
14622 	uint32_t mbox_tmo;
14623 	uint16_t xritag_start = 0;
14624 	int rc = 0;
14625 	uint32_t shdr_status, shdr_add_status;
14626 	union lpfc_sli4_cfg_shdr *shdr;
14627 
14628 	reqlen = phba->sli4_hba.els_xri_cnt * sizeof(struct sgl_page_pairs) +
14629 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
14630 	if (reqlen > SLI4_PAGE_SIZE) {
14631 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
14632 				"2559 Block sgl registration required DMA "
14633 				"size (%d) great than a page\n", reqlen);
14634 		return -ENOMEM;
14635 	}
14636 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14637 	if (!mbox)
14638 		return -ENOMEM;
14639 
14640 	/* Allocate DMA memory and set up the non-embedded mailbox command */
14641 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14642 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
14643 			 LPFC_SLI4_MBX_NEMBED);
14644 
14645 	if (alloclen < reqlen) {
14646 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14647 				"0285 Allocated DMA memory size (%d) is "
14648 				"less than the requested DMA memory "
14649 				"size (%d)\n", alloclen, reqlen);
14650 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14651 		return -ENOMEM;
14652 	}
14653 	/* Set up the SGL pages in the non-embedded DMA pages */
14654 	viraddr = mbox->sge_array->addr[0];
14655 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
14656 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
14657 
14658 	pg_pairs = 0;
14659 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
14660 		/* Set up the sge entry */
14661 		sgl_pg_pairs->sgl_pg0_addr_lo =
14662 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
14663 		sgl_pg_pairs->sgl_pg0_addr_hi =
14664 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
14665 		sgl_pg_pairs->sgl_pg1_addr_lo =
14666 				cpu_to_le32(putPaddrLow(0));
14667 		sgl_pg_pairs->sgl_pg1_addr_hi =
14668 				cpu_to_le32(putPaddrHigh(0));
14669 
14670 		/* Keep the first xritag on the list */
14671 		if (pg_pairs == 0)
14672 			xritag_start = sglq_entry->sli4_xritag;
14673 		sgl_pg_pairs++;
14674 		pg_pairs++;
14675 	}
14676 
14677 	/* Complete initialization and perform endian conversion. */
14678 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
14679 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, phba->sli4_hba.els_xri_cnt);
14680 	sgl->word0 = cpu_to_le32(sgl->word0);
14681 	if (!phba->sli4_hba.intr_enable)
14682 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14683 	else {
14684 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
14685 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
14686 	}
14687 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
14688 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14689 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14690 	if (rc != MBX_TIMEOUT)
14691 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14692 	if (shdr_status || shdr_add_status || rc) {
14693 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14694 				"2513 POST_SGL_BLOCK mailbox command failed "
14695 				"status x%x add_status x%x mbx status x%x\n",
14696 				shdr_status, shdr_add_status, rc);
14697 		rc = -ENXIO;
14698 	}
14699 	return rc;
14700 }
14701 
14702 /**
14703  * lpfc_sli4_post_scsi_sgl_block - post a block of scsi sgl list to firmware
14704  * @phba: pointer to lpfc hba data structure.
14705  * @sblist: pointer to scsi buffer list.
14706  * @count: number of scsi buffers on the list.
14707  *
14708  * This routine is invoked to post a block of @count scsi sgl pages from a
14709  * SCSI buffer list @sblist to the HBA using non-embedded mailbox command.
14710  * No Lock is held.
14711  *
14712  **/
14713 int
14714 lpfc_sli4_post_scsi_sgl_block(struct lpfc_hba *phba,
14715 			      struct list_head *sblist,
14716 			      int count)
14717 {
14718 	struct lpfc_scsi_buf *psb;
14719 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
14720 	struct sgl_page_pairs *sgl_pg_pairs;
14721 	void *viraddr;
14722 	LPFC_MBOXQ_t *mbox;
14723 	uint32_t reqlen, alloclen, pg_pairs;
14724 	uint32_t mbox_tmo;
14725 	uint16_t xritag_start = 0;
14726 	int rc = 0;
14727 	uint32_t shdr_status, shdr_add_status;
14728 	dma_addr_t pdma_phys_bpl1;
14729 	union lpfc_sli4_cfg_shdr *shdr;
14730 
14731 	/* Calculate the requested length of the dma memory */
14732 	reqlen = count * sizeof(struct sgl_page_pairs) +
14733 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
14734 	if (reqlen > SLI4_PAGE_SIZE) {
14735 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
14736 				"0217 Block sgl registration required DMA "
14737 				"size (%d) great than a page\n", reqlen);
14738 		return -ENOMEM;
14739 	}
14740 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14741 	if (!mbox) {
14742 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14743 				"0283 Failed to allocate mbox cmd memory\n");
14744 		return -ENOMEM;
14745 	}
14746 
14747 	/* Allocate DMA memory and set up the non-embedded mailbox command */
14748 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
14749 				LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
14750 				LPFC_SLI4_MBX_NEMBED);
14751 
14752 	if (alloclen < reqlen) {
14753 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14754 				"2561 Allocated DMA memory size (%d) is "
14755 				"less than the requested DMA memory "
14756 				"size (%d)\n", alloclen, reqlen);
14757 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14758 		return -ENOMEM;
14759 	}
14760 
14761 	/* Get the first SGE entry from the non-embedded DMA memory */
14762 	viraddr = mbox->sge_array->addr[0];
14763 
14764 	/* Set up the SGL pages in the non-embedded DMA pages */
14765 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
14766 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
14767 
14768 	pg_pairs = 0;
14769 	list_for_each_entry(psb, sblist, list) {
14770 		/* Set up the sge entry */
14771 		sgl_pg_pairs->sgl_pg0_addr_lo =
14772 			cpu_to_le32(putPaddrLow(psb->dma_phys_bpl));
14773 		sgl_pg_pairs->sgl_pg0_addr_hi =
14774 			cpu_to_le32(putPaddrHigh(psb->dma_phys_bpl));
14775 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
14776 			pdma_phys_bpl1 = psb->dma_phys_bpl + SGL_PAGE_SIZE;
14777 		else
14778 			pdma_phys_bpl1 = 0;
14779 		sgl_pg_pairs->sgl_pg1_addr_lo =
14780 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
14781 		sgl_pg_pairs->sgl_pg1_addr_hi =
14782 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
14783 		/* Keep the first xritag on the list */
14784 		if (pg_pairs == 0)
14785 			xritag_start = psb->cur_iocbq.sli4_xritag;
14786 		sgl_pg_pairs++;
14787 		pg_pairs++;
14788 	}
14789 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
14790 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
14791 	/* Perform endian conversion if necessary */
14792 	sgl->word0 = cpu_to_le32(sgl->word0);
14793 
14794 	if (!phba->sli4_hba.intr_enable)
14795 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14796 	else {
14797 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
14798 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
14799 	}
14800 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
14801 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14802 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14803 	if (rc != MBX_TIMEOUT)
14804 		lpfc_sli4_mbox_cmd_free(phba, mbox);
14805 	if (shdr_status || shdr_add_status || rc) {
14806 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14807 				"2564 POST_SGL_BLOCK mailbox command failed "
14808 				"status x%x add_status x%x mbx status x%x\n",
14809 				shdr_status, shdr_add_status, rc);
14810 		rc = -ENXIO;
14811 	}
14812 	return rc;
14813 }
14814 
14815 /**
14816  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
14817  * @phba: pointer to lpfc_hba struct that the frame was received on
14818  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
14819  *
14820  * This function checks the fields in the @fc_hdr to see if the FC frame is a
14821  * valid type of frame that the LPFC driver will handle. This function will
14822  * return a zero if the frame is a valid frame or a non zero value when the
14823  * frame does not pass the check.
14824  **/
14825 static int
14826 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
14827 {
14828 	/*  make rctl_names static to save stack space */
14829 	static char *rctl_names[] = FC_RCTL_NAMES_INIT;
14830 	char *type_names[] = FC_TYPE_NAMES_INIT;
14831 	struct fc_vft_header *fc_vft_hdr;
14832 	uint32_t *header = (uint32_t *) fc_hdr;
14833 
14834 	switch (fc_hdr->fh_r_ctl) {
14835 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
14836 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
14837 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
14838 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
14839 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
14840 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
14841 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
14842 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
14843 	case FC_RCTL_ELS_REQ:	/* extended link services request */
14844 	case FC_RCTL_ELS_REP:	/* extended link services reply */
14845 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
14846 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
14847 	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
14848 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
14849 	case FC_RCTL_BA_RMC: 	/* remove connection */
14850 	case FC_RCTL_BA_ACC:	/* basic accept */
14851 	case FC_RCTL_BA_RJT:	/* basic reject */
14852 	case FC_RCTL_BA_PRMT:
14853 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
14854 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
14855 	case FC_RCTL_P_RJT:	/* port reject */
14856 	case FC_RCTL_F_RJT:	/* fabric reject */
14857 	case FC_RCTL_P_BSY:	/* port busy */
14858 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
14859 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
14860 	case FC_RCTL_LCR:	/* link credit reset */
14861 	case FC_RCTL_END:	/* end */
14862 		break;
14863 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
14864 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
14865 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
14866 		return lpfc_fc_frame_check(phba, fc_hdr);
14867 	default:
14868 		goto drop;
14869 	}
14870 	switch (fc_hdr->fh_type) {
14871 	case FC_TYPE_BLS:
14872 	case FC_TYPE_ELS:
14873 	case FC_TYPE_FCP:
14874 	case FC_TYPE_CT:
14875 		break;
14876 	case FC_TYPE_IP:
14877 	case FC_TYPE_ILS:
14878 	default:
14879 		goto drop;
14880 	}
14881 
14882 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
14883 			"2538 Received frame rctl:%s (x%x), type:%s (x%x), "
14884 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
14885 			rctl_names[fc_hdr->fh_r_ctl], fc_hdr->fh_r_ctl,
14886 			type_names[fc_hdr->fh_type], fc_hdr->fh_type,
14887 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
14888 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
14889 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
14890 			be32_to_cpu(header[6]));
14891 	return 0;
14892 drop:
14893 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
14894 			"2539 Dropped frame rctl:%s type:%s\n",
14895 			rctl_names[fc_hdr->fh_r_ctl],
14896 			type_names[fc_hdr->fh_type]);
14897 	return 1;
14898 }
14899 
14900 /**
14901  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
14902  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
14903  *
14904  * This function processes the FC header to retrieve the VFI from the VF
14905  * header, if one exists. This function will return the VFI if one exists
14906  * or 0 if no VSAN Header exists.
14907  **/
14908 static uint32_t
14909 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
14910 {
14911 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
14912 
14913 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
14914 		return 0;
14915 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
14916 }
14917 
14918 /**
14919  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
14920  * @phba: Pointer to the HBA structure to search for the vport on
14921  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
14922  * @fcfi: The FC Fabric ID that the frame came from
14923  *
14924  * This function searches the @phba for a vport that matches the content of the
14925  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
14926  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
14927  * returns the matching vport pointer or NULL if unable to match frame to a
14928  * vport.
14929  **/
14930 static struct lpfc_vport *
14931 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
14932 		       uint16_t fcfi)
14933 {
14934 	struct lpfc_vport **vports;
14935 	struct lpfc_vport *vport = NULL;
14936 	int i;
14937 	uint32_t did = (fc_hdr->fh_d_id[0] << 16 |
14938 			fc_hdr->fh_d_id[1] << 8 |
14939 			fc_hdr->fh_d_id[2]);
14940 
14941 	if (did == Fabric_DID)
14942 		return phba->pport;
14943 	if ((phba->pport->fc_flag & FC_PT2PT) &&
14944 		!(phba->link_state == LPFC_HBA_READY))
14945 		return phba->pport;
14946 
14947 	vports = lpfc_create_vport_work_array(phba);
14948 	if (vports != NULL)
14949 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
14950 			if (phba->fcf.fcfi == fcfi &&
14951 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
14952 			    vports[i]->fc_myDID == did) {
14953 				vport = vports[i];
14954 				break;
14955 			}
14956 		}
14957 	lpfc_destroy_vport_work_array(phba, vports);
14958 	return vport;
14959 }
14960 
14961 /**
14962  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
14963  * @vport: The vport to work on.
14964  *
14965  * This function updates the receive sequence time stamp for this vport. The
14966  * receive sequence time stamp indicates the time that the last frame of the
14967  * the sequence that has been idle for the longest amount of time was received.
14968  * the driver uses this time stamp to indicate if any received sequences have
14969  * timed out.
14970  **/
14971 static void
14972 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
14973 {
14974 	struct lpfc_dmabuf *h_buf;
14975 	struct hbq_dmabuf *dmabuf = NULL;
14976 
14977 	/* get the oldest sequence on the rcv list */
14978 	h_buf = list_get_first(&vport->rcv_buffer_list,
14979 			       struct lpfc_dmabuf, list);
14980 	if (!h_buf)
14981 		return;
14982 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
14983 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
14984 }
14985 
14986 /**
14987  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
14988  * @vport: The vport that the received sequences were sent to.
14989  *
14990  * This function cleans up all outstanding received sequences. This is called
14991  * by the driver when a link event or user action invalidates all the received
14992  * sequences.
14993  **/
14994 void
14995 lpfc_cleanup_rcv_buffers(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 
15001 	/* start with the oldest sequence on the rcv list */
15002 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
15003 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
15004 		list_del_init(&dmabuf->hbuf.list);
15005 		list_for_each_entry_safe(d_buf, dnext,
15006 					 &dmabuf->dbuf.list, list) {
15007 			list_del_init(&d_buf->list);
15008 			lpfc_in_buf_free(vport->phba, d_buf);
15009 		}
15010 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
15011 	}
15012 }
15013 
15014 /**
15015  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
15016  * @vport: The vport that the received sequences were sent to.
15017  *
15018  * This function determines whether any received sequences have timed out by
15019  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
15020  * indicates that there is at least one timed out sequence this routine will
15021  * go through the received sequences one at a time from most inactive to most
15022  * active to determine which ones need to be cleaned up. Once it has determined
15023  * that a sequence needs to be cleaned up it will simply free up the resources
15024  * without sending an abort.
15025  **/
15026 void
15027 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
15028 {
15029 	struct lpfc_dmabuf *h_buf, *hnext;
15030 	struct lpfc_dmabuf *d_buf, *dnext;
15031 	struct hbq_dmabuf *dmabuf = NULL;
15032 	unsigned long timeout;
15033 	int abort_count = 0;
15034 
15035 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
15036 		   vport->rcv_buffer_time_stamp);
15037 	if (list_empty(&vport->rcv_buffer_list) ||
15038 	    time_before(jiffies, timeout))
15039 		return;
15040 	/* start with the oldest sequence on the rcv list */
15041 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
15042 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
15043 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
15044 			   dmabuf->time_stamp);
15045 		if (time_before(jiffies, timeout))
15046 			break;
15047 		abort_count++;
15048 		list_del_init(&dmabuf->hbuf.list);
15049 		list_for_each_entry_safe(d_buf, dnext,
15050 					 &dmabuf->dbuf.list, list) {
15051 			list_del_init(&d_buf->list);
15052 			lpfc_in_buf_free(vport->phba, d_buf);
15053 		}
15054 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
15055 	}
15056 	if (abort_count)
15057 		lpfc_update_rcv_time_stamp(vport);
15058 }
15059 
15060 /**
15061  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
15062  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
15063  *
15064  * This function searches through the existing incomplete sequences that have
15065  * been sent to this @vport. If the frame matches one of the incomplete
15066  * sequences then the dbuf in the @dmabuf is added to the list of frames that
15067  * make up that sequence. If no sequence is found that matches this frame then
15068  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
15069  * This function returns a pointer to the first dmabuf in the sequence list that
15070  * the frame was linked to.
15071  **/
15072 static struct hbq_dmabuf *
15073 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
15074 {
15075 	struct fc_frame_header *new_hdr;
15076 	struct fc_frame_header *temp_hdr;
15077 	struct lpfc_dmabuf *d_buf;
15078 	struct lpfc_dmabuf *h_buf;
15079 	struct hbq_dmabuf *seq_dmabuf = NULL;
15080 	struct hbq_dmabuf *temp_dmabuf = NULL;
15081 	uint8_t	found = 0;
15082 
15083 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
15084 	dmabuf->time_stamp = jiffies;
15085 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
15086 
15087 	/* Use the hdr_buf to find the sequence that this frame belongs to */
15088 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
15089 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
15090 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
15091 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
15092 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
15093 			continue;
15094 		/* found a pending sequence that matches this frame */
15095 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
15096 		break;
15097 	}
15098 	if (!seq_dmabuf) {
15099 		/*
15100 		 * This indicates first frame received for this sequence.
15101 		 * Queue the buffer on the vport's rcv_buffer_list.
15102 		 */
15103 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
15104 		lpfc_update_rcv_time_stamp(vport);
15105 		return dmabuf;
15106 	}
15107 	temp_hdr = seq_dmabuf->hbuf.virt;
15108 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
15109 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
15110 		list_del_init(&seq_dmabuf->hbuf.list);
15111 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
15112 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
15113 		lpfc_update_rcv_time_stamp(vport);
15114 		return dmabuf;
15115 	}
15116 	/* move this sequence to the tail to indicate a young sequence */
15117 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
15118 	seq_dmabuf->time_stamp = jiffies;
15119 	lpfc_update_rcv_time_stamp(vport);
15120 	if (list_empty(&seq_dmabuf->dbuf.list)) {
15121 		temp_hdr = dmabuf->hbuf.virt;
15122 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
15123 		return seq_dmabuf;
15124 	}
15125 	/* find the correct place in the sequence to insert this frame */
15126 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
15127 	while (!found) {
15128 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15129 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
15130 		/*
15131 		 * If the frame's sequence count is greater than the frame on
15132 		 * the list then insert the frame right after this frame
15133 		 */
15134 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
15135 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
15136 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
15137 			found = 1;
15138 			break;
15139 		}
15140 
15141 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
15142 			break;
15143 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
15144 	}
15145 
15146 	if (found)
15147 		return seq_dmabuf;
15148 	return NULL;
15149 }
15150 
15151 /**
15152  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
15153  * @vport: pointer to a vitural port
15154  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15155  *
15156  * This function tries to abort from the partially assembed sequence, described
15157  * by the information from basic abbort @dmabuf. It checks to see whether such
15158  * partially assembled sequence held by the driver. If so, it shall free up all
15159  * the frames from the partially assembled sequence.
15160  *
15161  * Return
15162  * true  -- if there is matching partially assembled sequence present and all
15163  *          the frames freed with the sequence;
15164  * false -- if there is no matching partially assembled sequence present so
15165  *          nothing got aborted in the lower layer driver
15166  **/
15167 static bool
15168 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
15169 			    struct hbq_dmabuf *dmabuf)
15170 {
15171 	struct fc_frame_header *new_hdr;
15172 	struct fc_frame_header *temp_hdr;
15173 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
15174 	struct hbq_dmabuf *seq_dmabuf = NULL;
15175 
15176 	/* Use the hdr_buf to find the sequence that matches this frame */
15177 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
15178 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
15179 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
15180 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
15181 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
15182 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
15183 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
15184 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
15185 			continue;
15186 		/* found a pending sequence that matches this frame */
15187 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
15188 		break;
15189 	}
15190 
15191 	/* Free up all the frames from the partially assembled sequence */
15192 	if (seq_dmabuf) {
15193 		list_for_each_entry_safe(d_buf, n_buf,
15194 					 &seq_dmabuf->dbuf.list, list) {
15195 			list_del_init(&d_buf->list);
15196 			lpfc_in_buf_free(vport->phba, d_buf);
15197 		}
15198 		return true;
15199 	}
15200 	return false;
15201 }
15202 
15203 /**
15204  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
15205  * @vport: pointer to a vitural port
15206  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15207  *
15208  * This function tries to abort from the assembed sequence from upper level
15209  * protocol, described by the information from basic abbort @dmabuf. It
15210  * checks to see whether such pending context exists at upper level protocol.
15211  * If so, it shall clean up the pending context.
15212  *
15213  * Return
15214  * true  -- if there is matching pending context of the sequence cleaned
15215  *          at ulp;
15216  * false -- if there is no matching pending context of the sequence present
15217  *          at ulp.
15218  **/
15219 static bool
15220 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
15221 {
15222 	struct lpfc_hba *phba = vport->phba;
15223 	int handled;
15224 
15225 	/* Accepting abort at ulp with SLI4 only */
15226 	if (phba->sli_rev < LPFC_SLI_REV4)
15227 		return false;
15228 
15229 	/* Register all caring upper level protocols to attend abort */
15230 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
15231 	if (handled)
15232 		return true;
15233 
15234 	return false;
15235 }
15236 
15237 /**
15238  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
15239  * @phba: Pointer to HBA context object.
15240  * @cmd_iocbq: pointer to the command iocbq structure.
15241  * @rsp_iocbq: pointer to the response iocbq structure.
15242  *
15243  * This function handles the sequence abort response iocb command complete
15244  * event. It properly releases the memory allocated to the sequence abort
15245  * accept iocb.
15246  **/
15247 static void
15248 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
15249 			     struct lpfc_iocbq *cmd_iocbq,
15250 			     struct lpfc_iocbq *rsp_iocbq)
15251 {
15252 	struct lpfc_nodelist *ndlp;
15253 
15254 	if (cmd_iocbq) {
15255 		ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
15256 		lpfc_nlp_put(ndlp);
15257 		lpfc_nlp_not_used(ndlp);
15258 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
15259 	}
15260 
15261 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
15262 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
15263 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15264 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
15265 			rsp_iocbq->iocb.ulpStatus,
15266 			rsp_iocbq->iocb.un.ulpWord[4]);
15267 }
15268 
15269 /**
15270  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
15271  * @phba: Pointer to HBA context object.
15272  * @xri: xri id in transaction.
15273  *
15274  * This function validates the xri maps to the known range of XRIs allocated an
15275  * used by the driver.
15276  **/
15277 uint16_t
15278 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
15279 		      uint16_t xri)
15280 {
15281 	uint16_t i;
15282 
15283 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
15284 		if (xri == phba->sli4_hba.xri_ids[i])
15285 			return i;
15286 	}
15287 	return NO_XRI;
15288 }
15289 
15290 /**
15291  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
15292  * @phba: Pointer to HBA context object.
15293  * @fc_hdr: pointer to a FC frame header.
15294  *
15295  * This function sends a basic response to a previous unsol sequence abort
15296  * event after aborting the sequence handling.
15297  **/
15298 static void
15299 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
15300 			struct fc_frame_header *fc_hdr, bool aborted)
15301 {
15302 	struct lpfc_hba *phba = vport->phba;
15303 	struct lpfc_iocbq *ctiocb = NULL;
15304 	struct lpfc_nodelist *ndlp;
15305 	uint16_t oxid, rxid, xri, lxri;
15306 	uint32_t sid, fctl;
15307 	IOCB_t *icmd;
15308 	int rc;
15309 
15310 	if (!lpfc_is_link_up(phba))
15311 		return;
15312 
15313 	sid = sli4_sid_from_fc_hdr(fc_hdr);
15314 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
15315 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
15316 
15317 	ndlp = lpfc_findnode_did(vport, sid);
15318 	if (!ndlp) {
15319 		ndlp = mempool_alloc(phba->nlp_mem_pool, GFP_KERNEL);
15320 		if (!ndlp) {
15321 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
15322 					 "1268 Failed to allocate ndlp for "
15323 					 "oxid:x%x SID:x%x\n", oxid, sid);
15324 			return;
15325 		}
15326 		lpfc_nlp_init(vport, ndlp, sid);
15327 		/* Put ndlp onto pport node list */
15328 		lpfc_enqueue_node(vport, ndlp);
15329 	} else if (!NLP_CHK_NODE_ACT(ndlp)) {
15330 		/* re-setup ndlp without removing from node list */
15331 		ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_UNUSED_NODE);
15332 		if (!ndlp) {
15333 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
15334 					 "3275 Failed to active ndlp found "
15335 					 "for oxid:x%x SID:x%x\n", oxid, sid);
15336 			return;
15337 		}
15338 	}
15339 
15340 	/* Allocate buffer for rsp iocb */
15341 	ctiocb = lpfc_sli_get_iocbq(phba);
15342 	if (!ctiocb)
15343 		return;
15344 
15345 	/* Extract the F_CTL field from FC_HDR */
15346 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
15347 
15348 	icmd = &ctiocb->iocb;
15349 	icmd->un.xseq64.bdl.bdeSize = 0;
15350 	icmd->un.xseq64.bdl.ulpIoTag32 = 0;
15351 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
15352 	icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
15353 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
15354 
15355 	/* Fill in the rest of iocb fields */
15356 	icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
15357 	icmd->ulpBdeCount = 0;
15358 	icmd->ulpLe = 1;
15359 	icmd->ulpClass = CLASS3;
15360 	icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
15361 	ctiocb->context1 = lpfc_nlp_get(ndlp);
15362 
15363 	ctiocb->iocb_cmpl = NULL;
15364 	ctiocb->vport = phba->pport;
15365 	ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
15366 	ctiocb->sli4_lxritag = NO_XRI;
15367 	ctiocb->sli4_xritag = NO_XRI;
15368 
15369 	if (fctl & FC_FC_EX_CTX)
15370 		/* Exchange responder sent the abort so we
15371 		 * own the oxid.
15372 		 */
15373 		xri = oxid;
15374 	else
15375 		xri = rxid;
15376 	lxri = lpfc_sli4_xri_inrange(phba, xri);
15377 	if (lxri != NO_XRI)
15378 		lpfc_set_rrq_active(phba, ndlp, lxri,
15379 			(xri == oxid) ? rxid : oxid, 0);
15380 	/* For BA_ABTS from exchange responder, if the logical xri with
15381 	 * the oxid maps to the FCP XRI range, the port no longer has
15382 	 * that exchange context, send a BLS_RJT. Override the IOCB for
15383 	 * a BA_RJT.
15384 	 */
15385 	if ((fctl & FC_FC_EX_CTX) &&
15386 	    (lxri > lpfc_sli4_get_els_iocb_cnt(phba))) {
15387 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
15388 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
15389 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
15390 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
15391 	}
15392 
15393 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
15394 	 * the driver no longer has that exchange, send a BLS_RJT. Override
15395 	 * the IOCB for a BA_RJT.
15396 	 */
15397 	if (aborted == false) {
15398 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
15399 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
15400 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
15401 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
15402 	}
15403 
15404 	if (fctl & FC_FC_EX_CTX) {
15405 		/* ABTS sent by responder to CT exchange, construction
15406 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
15407 		 * field and RX_ID from ABTS for RX_ID field.
15408 		 */
15409 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
15410 	} else {
15411 		/* ABTS sent by initiator to CT exchange, construction
15412 		 * of BA_ACC will need to allocate a new XRI as for the
15413 		 * XRI_TAG field.
15414 		 */
15415 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
15416 	}
15417 	bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
15418 	bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
15419 
15420 	/* Xmit CT abts response on exchange <xid> */
15421 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
15422 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
15423 			 icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
15424 
15425 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
15426 	if (rc == IOCB_ERROR) {
15427 		lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
15428 				 "2925 Failed to issue CT ABTS RSP x%x on "
15429 				 "xri x%x, Data x%x\n",
15430 				 icmd->un.xseq64.w5.hcsw.Rctl, oxid,
15431 				 phba->link_state);
15432 		lpfc_nlp_put(ndlp);
15433 		ctiocb->context1 = NULL;
15434 		lpfc_sli_release_iocbq(phba, ctiocb);
15435 	}
15436 }
15437 
15438 /**
15439  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
15440  * @vport: Pointer to the vport on which this sequence was received
15441  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15442  *
15443  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
15444  * receive sequence is only partially assembed by the driver, it shall abort
15445  * the partially assembled frames for the sequence. Otherwise, if the
15446  * unsolicited receive sequence has been completely assembled and passed to
15447  * the Upper Layer Protocol (UPL), it then mark the per oxid status for the
15448  * unsolicited sequence has been aborted. After that, it will issue a basic
15449  * accept to accept the abort.
15450  **/
15451 static void
15452 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
15453 			     struct hbq_dmabuf *dmabuf)
15454 {
15455 	struct lpfc_hba *phba = vport->phba;
15456 	struct fc_frame_header fc_hdr;
15457 	uint32_t fctl;
15458 	bool aborted;
15459 
15460 	/* Make a copy of fc_hdr before the dmabuf being released */
15461 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
15462 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
15463 
15464 	if (fctl & FC_FC_EX_CTX) {
15465 		/* ABTS by responder to exchange, no cleanup needed */
15466 		aborted = true;
15467 	} else {
15468 		/* ABTS by initiator to exchange, need to do cleanup */
15469 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
15470 		if (aborted == false)
15471 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
15472 	}
15473 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
15474 
15475 	/* Respond with BA_ACC or BA_RJT accordingly */
15476 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
15477 }
15478 
15479 /**
15480  * lpfc_seq_complete - Indicates if a sequence is complete
15481  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15482  *
15483  * This function checks the sequence, starting with the frame described by
15484  * @dmabuf, to see if all the frames associated with this sequence are present.
15485  * the frames associated with this sequence are linked to the @dmabuf using the
15486  * dbuf list. This function looks for two major things. 1) That the first frame
15487  * has a sequence count of zero. 2) There is a frame with last frame of sequence
15488  * set. 3) That there are no holes in the sequence count. The function will
15489  * return 1 when the sequence is complete, otherwise it will return 0.
15490  **/
15491 static int
15492 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
15493 {
15494 	struct fc_frame_header *hdr;
15495 	struct lpfc_dmabuf *d_buf;
15496 	struct hbq_dmabuf *seq_dmabuf;
15497 	uint32_t fctl;
15498 	int seq_count = 0;
15499 
15500 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
15501 	/* make sure first fame of sequence has a sequence count of zero */
15502 	if (hdr->fh_seq_cnt != seq_count)
15503 		return 0;
15504 	fctl = (hdr->fh_f_ctl[0] << 16 |
15505 		hdr->fh_f_ctl[1] << 8 |
15506 		hdr->fh_f_ctl[2]);
15507 	/* If last frame of sequence we can return success. */
15508 	if (fctl & FC_FC_END_SEQ)
15509 		return 1;
15510 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
15511 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15512 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
15513 		/* If there is a hole in the sequence count then fail. */
15514 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
15515 			return 0;
15516 		fctl = (hdr->fh_f_ctl[0] << 16 |
15517 			hdr->fh_f_ctl[1] << 8 |
15518 			hdr->fh_f_ctl[2]);
15519 		/* If last frame of sequence we can return success. */
15520 		if (fctl & FC_FC_END_SEQ)
15521 			return 1;
15522 	}
15523 	return 0;
15524 }
15525 
15526 /**
15527  * lpfc_prep_seq - Prep sequence for ULP processing
15528  * @vport: Pointer to the vport on which this sequence was received
15529  * @dmabuf: pointer to a dmabuf that describes the FC sequence
15530  *
15531  * This function takes a sequence, described by a list of frames, and creates
15532  * a list of iocbq structures to describe the sequence. This iocbq list will be
15533  * used to issue to the generic unsolicited sequence handler. This routine
15534  * returns a pointer to the first iocbq in the list. If the function is unable
15535  * to allocate an iocbq then it throw out the received frames that were not
15536  * able to be described and return a pointer to the first iocbq. If unable to
15537  * allocate any iocbqs (including the first) this function will return NULL.
15538  **/
15539 static struct lpfc_iocbq *
15540 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
15541 {
15542 	struct hbq_dmabuf *hbq_buf;
15543 	struct lpfc_dmabuf *d_buf, *n_buf;
15544 	struct lpfc_iocbq *first_iocbq, *iocbq;
15545 	struct fc_frame_header *fc_hdr;
15546 	uint32_t sid;
15547 	uint32_t len, tot_len;
15548 	struct ulp_bde64 *pbde;
15549 
15550 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
15551 	/* remove from receive buffer list */
15552 	list_del_init(&seq_dmabuf->hbuf.list);
15553 	lpfc_update_rcv_time_stamp(vport);
15554 	/* get the Remote Port's SID */
15555 	sid = sli4_sid_from_fc_hdr(fc_hdr);
15556 	tot_len = 0;
15557 	/* Get an iocbq struct to fill in. */
15558 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
15559 	if (first_iocbq) {
15560 		/* Initialize the first IOCB. */
15561 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
15562 		first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
15563 
15564 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
15565 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
15566 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
15567 			first_iocbq->iocb.un.rcvels.parmRo =
15568 				sli4_did_from_fc_hdr(fc_hdr);
15569 			first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
15570 		} else
15571 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
15572 		first_iocbq->iocb.ulpContext = NO_XRI;
15573 		first_iocbq->iocb.unsli3.rcvsli3.ox_id =
15574 			be16_to_cpu(fc_hdr->fh_ox_id);
15575 		/* iocbq is prepped for internal consumption.  Physical vpi. */
15576 		first_iocbq->iocb.unsli3.rcvsli3.vpi =
15577 			vport->phba->vpi_ids[vport->vpi];
15578 		/* put the first buffer into the first IOCBq */
15579 		tot_len = bf_get(lpfc_rcqe_length,
15580 				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
15581 
15582 		first_iocbq->context2 = &seq_dmabuf->dbuf;
15583 		first_iocbq->context3 = NULL;
15584 		first_iocbq->iocb.ulpBdeCount = 1;
15585 		if (tot_len > LPFC_DATA_BUF_SIZE)
15586 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
15587 							LPFC_DATA_BUF_SIZE;
15588 		else
15589 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
15590 
15591 		first_iocbq->iocb.un.rcvels.remoteID = sid;
15592 
15593 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
15594 	}
15595 	iocbq = first_iocbq;
15596 	/*
15597 	 * Each IOCBq can have two Buffers assigned, so go through the list
15598 	 * of buffers for this sequence and save two buffers in each IOCBq
15599 	 */
15600 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
15601 		if (!iocbq) {
15602 			lpfc_in_buf_free(vport->phba, d_buf);
15603 			continue;
15604 		}
15605 		if (!iocbq->context3) {
15606 			iocbq->context3 = d_buf;
15607 			iocbq->iocb.ulpBdeCount++;
15608 			/* We need to get the size out of the right CQE */
15609 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15610 			len = bf_get(lpfc_rcqe_length,
15611 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
15612 			pbde = (struct ulp_bde64 *)
15613 					&iocbq->iocb.unsli3.sli3Words[4];
15614 			if (len > LPFC_DATA_BUF_SIZE)
15615 				pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
15616 			else
15617 				pbde->tus.f.bdeSize = len;
15618 
15619 			iocbq->iocb.unsli3.rcvsli3.acc_len += len;
15620 			tot_len += len;
15621 		} else {
15622 			iocbq = lpfc_sli_get_iocbq(vport->phba);
15623 			if (!iocbq) {
15624 				if (first_iocbq) {
15625 					first_iocbq->iocb.ulpStatus =
15626 							IOSTAT_FCP_RSP_ERROR;
15627 					first_iocbq->iocb.un.ulpWord[4] =
15628 							IOERR_NO_RESOURCES;
15629 				}
15630 				lpfc_in_buf_free(vport->phba, d_buf);
15631 				continue;
15632 			}
15633 			/* We need to get the size out of the right CQE */
15634 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
15635 			len = bf_get(lpfc_rcqe_length,
15636 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
15637 			iocbq->context2 = d_buf;
15638 			iocbq->context3 = NULL;
15639 			iocbq->iocb.ulpBdeCount = 1;
15640 			if (len > LPFC_DATA_BUF_SIZE)
15641 				iocbq->iocb.un.cont64[0].tus.f.bdeSize =
15642 							LPFC_DATA_BUF_SIZE;
15643 			else
15644 				iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
15645 
15646 			tot_len += len;
15647 			iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
15648 
15649 			iocbq->iocb.un.rcvels.remoteID = sid;
15650 			list_add_tail(&iocbq->list, &first_iocbq->list);
15651 		}
15652 	}
15653 	return first_iocbq;
15654 }
15655 
15656 static void
15657 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
15658 			  struct hbq_dmabuf *seq_dmabuf)
15659 {
15660 	struct fc_frame_header *fc_hdr;
15661 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
15662 	struct lpfc_hba *phba = vport->phba;
15663 
15664 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
15665 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
15666 	if (!iocbq) {
15667 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15668 				"2707 Ring %d handler: Failed to allocate "
15669 				"iocb Rctl x%x Type x%x received\n",
15670 				LPFC_ELS_RING,
15671 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
15672 		return;
15673 	}
15674 	if (!lpfc_complete_unsol_iocb(phba,
15675 				      &phba->sli.ring[LPFC_ELS_RING],
15676 				      iocbq, fc_hdr->fh_r_ctl,
15677 				      fc_hdr->fh_type))
15678 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15679 				"2540 Ring %d handler: unexpected Rctl "
15680 				"x%x Type x%x received\n",
15681 				LPFC_ELS_RING,
15682 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
15683 
15684 	/* Free iocb created in lpfc_prep_seq */
15685 	list_for_each_entry_safe(curr_iocb, next_iocb,
15686 		&iocbq->list, list) {
15687 		list_del_init(&curr_iocb->list);
15688 		lpfc_sli_release_iocbq(phba, curr_iocb);
15689 	}
15690 	lpfc_sli_release_iocbq(phba, iocbq);
15691 }
15692 
15693 /**
15694  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
15695  * @phba: Pointer to HBA context object.
15696  *
15697  * This function is called with no lock held. This function processes all
15698  * the received buffers and gives it to upper layers when a received buffer
15699  * indicates that it is the final frame in the sequence. The interrupt
15700  * service routine processes received buffers at interrupt contexts and adds
15701  * received dma buffers to the rb_pend_list queue and signals the worker thread.
15702  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
15703  * appropriate receive function when the final frame in a sequence is received.
15704  **/
15705 void
15706 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
15707 				 struct hbq_dmabuf *dmabuf)
15708 {
15709 	struct hbq_dmabuf *seq_dmabuf;
15710 	struct fc_frame_header *fc_hdr;
15711 	struct lpfc_vport *vport;
15712 	uint32_t fcfi;
15713 	uint32_t did;
15714 
15715 	/* Process each received buffer */
15716 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
15717 	/* check to see if this a valid type of frame */
15718 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
15719 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
15720 		return;
15721 	}
15722 	if ((bf_get(lpfc_cqe_code,
15723 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
15724 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
15725 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
15726 	else
15727 		fcfi = bf_get(lpfc_rcqe_fcf_id,
15728 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
15729 
15730 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi);
15731 	if (!vport) {
15732 		/* throw out the frame */
15733 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
15734 		return;
15735 	}
15736 
15737 	/* d_id this frame is directed to */
15738 	did = sli4_did_from_fc_hdr(fc_hdr);
15739 
15740 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
15741 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
15742 		(did != Fabric_DID)) {
15743 		/*
15744 		 * Throw out the frame if we are not pt2pt.
15745 		 * The pt2pt protocol allows for discovery frames
15746 		 * to be received without a registered VPI.
15747 		 */
15748 		if (!(vport->fc_flag & FC_PT2PT) ||
15749 			(phba->link_state == LPFC_HBA_READY)) {
15750 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
15751 			return;
15752 		}
15753 	}
15754 
15755 	/* Handle the basic abort sequence (BA_ABTS) event */
15756 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
15757 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
15758 		return;
15759 	}
15760 
15761 	/* Link this frame */
15762 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
15763 	if (!seq_dmabuf) {
15764 		/* unable to add frame to vport - throw it out */
15765 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
15766 		return;
15767 	}
15768 	/* If not last frame in sequence continue processing frames. */
15769 	if (!lpfc_seq_complete(seq_dmabuf))
15770 		return;
15771 
15772 	/* Send the complete sequence to the upper layer protocol */
15773 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
15774 }
15775 
15776 /**
15777  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
15778  * @phba: pointer to lpfc hba data structure.
15779  *
15780  * This routine is invoked to post rpi header templates to the
15781  * HBA consistent with the SLI-4 interface spec.  This routine
15782  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
15783  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
15784  *
15785  * This routine does not require any locks.  It's usage is expected
15786  * to be driver load or reset recovery when the driver is
15787  * sequential.
15788  *
15789  * Return codes
15790  * 	0 - successful
15791  *      -EIO - The mailbox failed to complete successfully.
15792  * 	When this error occurs, the driver is not guaranteed
15793  *	to have any rpi regions posted to the device and
15794  *	must either attempt to repost the regions or take a
15795  *	fatal error.
15796  **/
15797 int
15798 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
15799 {
15800 	struct lpfc_rpi_hdr *rpi_page;
15801 	uint32_t rc = 0;
15802 	uint16_t lrpi = 0;
15803 
15804 	/* SLI4 ports that support extents do not require RPI headers. */
15805 	if (!phba->sli4_hba.rpi_hdrs_in_use)
15806 		goto exit;
15807 	if (phba->sli4_hba.extents_in_use)
15808 		return -EIO;
15809 
15810 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
15811 		/*
15812 		 * Assign the rpi headers a physical rpi only if the driver
15813 		 * has not initialized those resources.  A port reset only
15814 		 * needs the headers posted.
15815 		 */
15816 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
15817 		    LPFC_RPI_RSRC_RDY)
15818 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
15819 
15820 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
15821 		if (rc != MBX_SUCCESS) {
15822 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15823 					"2008 Error %d posting all rpi "
15824 					"headers\n", rc);
15825 			rc = -EIO;
15826 			break;
15827 		}
15828 	}
15829 
15830  exit:
15831 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
15832 	       LPFC_RPI_RSRC_RDY);
15833 	return rc;
15834 }
15835 
15836 /**
15837  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
15838  * @phba: pointer to lpfc hba data structure.
15839  * @rpi_page:  pointer to the rpi memory region.
15840  *
15841  * This routine is invoked to post a single rpi header to the
15842  * HBA consistent with the SLI-4 interface spec.  This memory region
15843  * maps up to 64 rpi context regions.
15844  *
15845  * Return codes
15846  * 	0 - successful
15847  * 	-ENOMEM - No available memory
15848  *      -EIO - The mailbox failed to complete successfully.
15849  **/
15850 int
15851 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
15852 {
15853 	LPFC_MBOXQ_t *mboxq;
15854 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
15855 	uint32_t rc = 0;
15856 	uint32_t shdr_status, shdr_add_status;
15857 	union lpfc_sli4_cfg_shdr *shdr;
15858 
15859 	/* SLI4 ports that support extents do not require RPI headers. */
15860 	if (!phba->sli4_hba.rpi_hdrs_in_use)
15861 		return rc;
15862 	if (phba->sli4_hba.extents_in_use)
15863 		return -EIO;
15864 
15865 	/* The port is notified of the header region via a mailbox command. */
15866 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15867 	if (!mboxq) {
15868 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15869 				"2001 Unable to allocate memory for issuing "
15870 				"SLI_CONFIG_SPECIAL mailbox command\n");
15871 		return -ENOMEM;
15872 	}
15873 
15874 	/* Post all rpi memory regions to the port. */
15875 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
15876 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
15877 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
15878 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
15879 			 sizeof(struct lpfc_sli4_cfg_mhdr),
15880 			 LPFC_SLI4_MBX_EMBED);
15881 
15882 
15883 	/* Post the physical rpi to the port for this rpi header. */
15884 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
15885 	       rpi_page->start_rpi);
15886 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
15887 	       hdr_tmpl, rpi_page->page_count);
15888 
15889 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
15890 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
15891 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
15892 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
15893 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15894 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15895 	if (rc != MBX_TIMEOUT)
15896 		mempool_free(mboxq, phba->mbox_mem_pool);
15897 	if (shdr_status || shdr_add_status || rc) {
15898 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15899 				"2514 POST_RPI_HDR mailbox failed with "
15900 				"status x%x add_status x%x, mbx status x%x\n",
15901 				shdr_status, shdr_add_status, rc);
15902 		rc = -ENXIO;
15903 	}
15904 	return rc;
15905 }
15906 
15907 /**
15908  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
15909  * @phba: pointer to lpfc hba data structure.
15910  *
15911  * This routine is invoked to post rpi header templates to the
15912  * HBA consistent with the SLI-4 interface spec.  This routine
15913  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
15914  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
15915  *
15916  * Returns
15917  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
15918  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
15919  **/
15920 int
15921 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
15922 {
15923 	unsigned long rpi;
15924 	uint16_t max_rpi, rpi_limit;
15925 	uint16_t rpi_remaining, lrpi = 0;
15926 	struct lpfc_rpi_hdr *rpi_hdr;
15927 	unsigned long iflag;
15928 
15929 	/*
15930 	 * Fetch the next logical rpi.  Because this index is logical,
15931 	 * the  driver starts at 0 each time.
15932 	 */
15933 	spin_lock_irqsave(&phba->hbalock, iflag);
15934 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
15935 	rpi_limit = phba->sli4_hba.next_rpi;
15936 
15937 	rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
15938 	if (rpi >= rpi_limit)
15939 		rpi = LPFC_RPI_ALLOC_ERROR;
15940 	else {
15941 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
15942 		phba->sli4_hba.max_cfg_param.rpi_used++;
15943 		phba->sli4_hba.rpi_count++;
15944 	}
15945 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
15946 			"0001 rpi:%x max:%x lim:%x\n",
15947 			(int) rpi, max_rpi, rpi_limit);
15948 
15949 	/*
15950 	 * Don't try to allocate more rpi header regions if the device limit
15951 	 * has been exhausted.
15952 	 */
15953 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
15954 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
15955 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15956 		return rpi;
15957 	}
15958 
15959 	/*
15960 	 * RPI header postings are not required for SLI4 ports capable of
15961 	 * extents.
15962 	 */
15963 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
15964 		spin_unlock_irqrestore(&phba->hbalock, iflag);
15965 		return rpi;
15966 	}
15967 
15968 	/*
15969 	 * If the driver is running low on rpi resources, allocate another
15970 	 * page now.  Note that the next_rpi value is used because
15971 	 * it represents how many are actually in use whereas max_rpi notes
15972 	 * how many are supported max by the device.
15973 	 */
15974 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
15975 	spin_unlock_irqrestore(&phba->hbalock, iflag);
15976 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
15977 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
15978 		if (!rpi_hdr) {
15979 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15980 					"2002 Error Could not grow rpi "
15981 					"count\n");
15982 		} else {
15983 			lrpi = rpi_hdr->start_rpi;
15984 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
15985 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
15986 		}
15987 	}
15988 
15989 	return rpi;
15990 }
15991 
15992 /**
15993  * lpfc_sli4_free_rpi - Release an rpi for reuse.
15994  * @phba: pointer to lpfc hba data structure.
15995  *
15996  * This routine is invoked to release an rpi to the pool of
15997  * available rpis maintained by the driver.
15998  **/
15999 static void
16000 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
16001 {
16002 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
16003 		phba->sli4_hba.rpi_count--;
16004 		phba->sli4_hba.max_cfg_param.rpi_used--;
16005 	}
16006 }
16007 
16008 /**
16009  * lpfc_sli4_free_rpi - Release an rpi for reuse.
16010  * @phba: pointer to lpfc hba data structure.
16011  *
16012  * This routine is invoked to release an rpi to the pool of
16013  * available rpis maintained by the driver.
16014  **/
16015 void
16016 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
16017 {
16018 	spin_lock_irq(&phba->hbalock);
16019 	__lpfc_sli4_free_rpi(phba, rpi);
16020 	spin_unlock_irq(&phba->hbalock);
16021 }
16022 
16023 /**
16024  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
16025  * @phba: pointer to lpfc hba data structure.
16026  *
16027  * This routine is invoked to remove the memory region that
16028  * provided rpi via a bitmask.
16029  **/
16030 void
16031 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
16032 {
16033 	kfree(phba->sli4_hba.rpi_bmask);
16034 	kfree(phba->sli4_hba.rpi_ids);
16035 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
16036 }
16037 
16038 /**
16039  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
16040  * @phba: pointer to lpfc hba data structure.
16041  *
16042  * This routine is invoked to remove the memory region that
16043  * provided rpi via a bitmask.
16044  **/
16045 int
16046 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
16047 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
16048 {
16049 	LPFC_MBOXQ_t *mboxq;
16050 	struct lpfc_hba *phba = ndlp->phba;
16051 	int rc;
16052 
16053 	/* The port is notified of the header region via a mailbox command. */
16054 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16055 	if (!mboxq)
16056 		return -ENOMEM;
16057 
16058 	/* Post all rpi memory regions to the port. */
16059 	lpfc_resume_rpi(mboxq, ndlp);
16060 	if (cmpl) {
16061 		mboxq->mbox_cmpl = cmpl;
16062 		mboxq->context1 = arg;
16063 		mboxq->context2 = ndlp;
16064 	} else
16065 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16066 	mboxq->vport = ndlp->vport;
16067 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16068 	if (rc == MBX_NOT_FINISHED) {
16069 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16070 				"2010 Resume RPI Mailbox failed "
16071 				"status %d, mbxStatus x%x\n", rc,
16072 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
16073 		mempool_free(mboxq, phba->mbox_mem_pool);
16074 		return -EIO;
16075 	}
16076 	return 0;
16077 }
16078 
16079 /**
16080  * lpfc_sli4_init_vpi - Initialize a vpi with the port
16081  * @vport: Pointer to the vport for which the vpi is being initialized
16082  *
16083  * This routine is invoked to activate a vpi with the port.
16084  *
16085  * Returns:
16086  *    0 success
16087  *    -Evalue otherwise
16088  **/
16089 int
16090 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
16091 {
16092 	LPFC_MBOXQ_t *mboxq;
16093 	int rc = 0;
16094 	int retval = MBX_SUCCESS;
16095 	uint32_t mbox_tmo;
16096 	struct lpfc_hba *phba = vport->phba;
16097 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16098 	if (!mboxq)
16099 		return -ENOMEM;
16100 	lpfc_init_vpi(phba, mboxq, vport->vpi);
16101 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
16102 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
16103 	if (rc != MBX_SUCCESS) {
16104 		lpfc_printf_vlog(vport, KERN_ERR, LOG_SLI,
16105 				"2022 INIT VPI Mailbox failed "
16106 				"status %d, mbxStatus x%x\n", rc,
16107 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
16108 		retval = -EIO;
16109 	}
16110 	if (rc != MBX_TIMEOUT)
16111 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
16112 
16113 	return retval;
16114 }
16115 
16116 /**
16117  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
16118  * @phba: pointer to lpfc hba data structure.
16119  * @mboxq: Pointer to mailbox object.
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 static void
16126 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
16127 {
16128 	void *virt_addr;
16129 	union lpfc_sli4_cfg_shdr *shdr;
16130 	uint32_t shdr_status, shdr_add_status;
16131 
16132 	virt_addr = mboxq->sge_array->addr[0];
16133 	/* The IOCTL status is embedded in the mailbox subheader. */
16134 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
16135 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16136 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16137 
16138 	if ((shdr_status || shdr_add_status) &&
16139 		(shdr_status != STATUS_FCF_IN_USE))
16140 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16141 			"2558 ADD_FCF_RECORD mailbox failed with "
16142 			"status x%x add_status x%x\n",
16143 			shdr_status, shdr_add_status);
16144 
16145 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
16146 }
16147 
16148 /**
16149  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
16150  * @phba: pointer to lpfc hba data structure.
16151  * @fcf_record:  pointer to the initialized fcf record to add.
16152  *
16153  * This routine is invoked to manually add a single FCF record. The caller
16154  * must pass a completely initialized FCF_Record.  This routine takes
16155  * care of the nonembedded mailbox operations.
16156  **/
16157 int
16158 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
16159 {
16160 	int rc = 0;
16161 	LPFC_MBOXQ_t *mboxq;
16162 	uint8_t *bytep;
16163 	void *virt_addr;
16164 	struct lpfc_mbx_sge sge;
16165 	uint32_t alloc_len, req_len;
16166 	uint32_t fcfindex;
16167 
16168 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16169 	if (!mboxq) {
16170 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16171 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
16172 		return -ENOMEM;
16173 	}
16174 
16175 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
16176 		  sizeof(uint32_t);
16177 
16178 	/* Allocate DMA memory and set up the non-embedded mailbox command */
16179 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
16180 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
16181 				     req_len, LPFC_SLI4_MBX_NEMBED);
16182 	if (alloc_len < req_len) {
16183 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16184 			"2523 Allocated DMA memory size (x%x) is "
16185 			"less than the requested DMA memory "
16186 			"size (x%x)\n", alloc_len, req_len);
16187 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
16188 		return -ENOMEM;
16189 	}
16190 
16191 	/*
16192 	 * Get the first SGE entry from the non-embedded DMA memory.  This
16193 	 * routine only uses a single SGE.
16194 	 */
16195 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
16196 	virt_addr = mboxq->sge_array->addr[0];
16197 	/*
16198 	 * Configure the FCF record for FCFI 0.  This is the driver's
16199 	 * hardcoded default and gets used in nonFIP mode.
16200 	 */
16201 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
16202 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
16203 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
16204 
16205 	/*
16206 	 * Copy the fcf_index and the FCF Record Data. The data starts after
16207 	 * the FCoE header plus word10. The data copy needs to be endian
16208 	 * correct.
16209 	 */
16210 	bytep += sizeof(uint32_t);
16211 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
16212 	mboxq->vport = phba->pport;
16213 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
16214 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16215 	if (rc == MBX_NOT_FINISHED) {
16216 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16217 			"2515 ADD_FCF_RECORD mailbox failed with "
16218 			"status 0x%x\n", rc);
16219 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
16220 		rc = -EIO;
16221 	} else
16222 		rc = 0;
16223 
16224 	return rc;
16225 }
16226 
16227 /**
16228  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
16229  * @phba: pointer to lpfc hba data structure.
16230  * @fcf_record:  pointer to the fcf record to write the default data.
16231  * @fcf_index: FCF table entry index.
16232  *
16233  * This routine is invoked to build the driver's default FCF record.  The
16234  * values used are hardcoded.  This routine handles memory initialization.
16235  *
16236  **/
16237 void
16238 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
16239 				struct fcf_record *fcf_record,
16240 				uint16_t fcf_index)
16241 {
16242 	memset(fcf_record, 0, sizeof(struct fcf_record));
16243 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
16244 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
16245 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
16246 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
16247 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
16248 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
16249 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
16250 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
16251 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
16252 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
16253 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
16254 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
16255 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
16256 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
16257 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
16258 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
16259 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
16260 	/* Set the VLAN bit map */
16261 	if (phba->valid_vlan) {
16262 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
16263 			= 1 << (phba->vlan_id % 8);
16264 	}
16265 }
16266 
16267 /**
16268  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
16269  * @phba: pointer to lpfc hba data structure.
16270  * @fcf_index: FCF table entry offset.
16271  *
16272  * This routine is invoked to scan the entire FCF table by reading FCF
16273  * record and processing it one at a time starting from the @fcf_index
16274  * for initial FCF discovery or fast FCF failover rediscovery.
16275  *
16276  * Return 0 if the mailbox command is submitted successfully, none 0
16277  * otherwise.
16278  **/
16279 int
16280 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
16281 {
16282 	int rc = 0, error;
16283 	LPFC_MBOXQ_t *mboxq;
16284 
16285 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
16286 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
16287 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16288 	if (!mboxq) {
16289 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16290 				"2000 Failed to allocate mbox for "
16291 				"READ_FCF cmd\n");
16292 		error = -ENOMEM;
16293 		goto fail_fcf_scan;
16294 	}
16295 	/* Construct the read FCF record mailbox command */
16296 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
16297 	if (rc) {
16298 		error = -EINVAL;
16299 		goto fail_fcf_scan;
16300 	}
16301 	/* Issue the mailbox command asynchronously */
16302 	mboxq->vport = phba->pport;
16303 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
16304 
16305 	spin_lock_irq(&phba->hbalock);
16306 	phba->hba_flag |= FCF_TS_INPROG;
16307 	spin_unlock_irq(&phba->hbalock);
16308 
16309 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16310 	if (rc == MBX_NOT_FINISHED)
16311 		error = -EIO;
16312 	else {
16313 		/* Reset eligible FCF count for new scan */
16314 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
16315 			phba->fcf.eligible_fcf_cnt = 0;
16316 		error = 0;
16317 	}
16318 fail_fcf_scan:
16319 	if (error) {
16320 		if (mboxq)
16321 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
16322 		/* FCF scan failed, clear FCF_TS_INPROG flag */
16323 		spin_lock_irq(&phba->hbalock);
16324 		phba->hba_flag &= ~FCF_TS_INPROG;
16325 		spin_unlock_irq(&phba->hbalock);
16326 	}
16327 	return error;
16328 }
16329 
16330 /**
16331  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
16332  * @phba: pointer to lpfc hba data structure.
16333  * @fcf_index: FCF table entry offset.
16334  *
16335  * This routine is invoked to read an FCF record indicated by @fcf_index
16336  * and to use it for FLOGI roundrobin FCF failover.
16337  *
16338  * Return 0 if the mailbox command is submitted successfully, none 0
16339  * otherwise.
16340  **/
16341 int
16342 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
16343 {
16344 	int rc = 0, error;
16345 	LPFC_MBOXQ_t *mboxq;
16346 
16347 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16348 	if (!mboxq) {
16349 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
16350 				"2763 Failed to allocate mbox for "
16351 				"READ_FCF cmd\n");
16352 		error = -ENOMEM;
16353 		goto fail_fcf_read;
16354 	}
16355 	/* Construct the read FCF record mailbox command */
16356 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
16357 	if (rc) {
16358 		error = -EINVAL;
16359 		goto fail_fcf_read;
16360 	}
16361 	/* Issue the mailbox command asynchronously */
16362 	mboxq->vport = phba->pport;
16363 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
16364 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16365 	if (rc == MBX_NOT_FINISHED)
16366 		error = -EIO;
16367 	else
16368 		error = 0;
16369 
16370 fail_fcf_read:
16371 	if (error && mboxq)
16372 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
16373 	return error;
16374 }
16375 
16376 /**
16377  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
16378  * @phba: pointer to lpfc hba data structure.
16379  * @fcf_index: FCF table entry offset.
16380  *
16381  * This routine is invoked to read an FCF record indicated by @fcf_index to
16382  * determine whether it's eligible for FLOGI roundrobin failover list.
16383  *
16384  * Return 0 if the mailbox command is submitted successfully, none 0
16385  * otherwise.
16386  **/
16387 int
16388 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
16389 {
16390 	int rc = 0, error;
16391 	LPFC_MBOXQ_t *mboxq;
16392 
16393 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16394 	if (!mboxq) {
16395 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
16396 				"2758 Failed to allocate mbox for "
16397 				"READ_FCF cmd\n");
16398 				error = -ENOMEM;
16399 				goto fail_fcf_read;
16400 	}
16401 	/* Construct the read FCF record mailbox command */
16402 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
16403 	if (rc) {
16404 		error = -EINVAL;
16405 		goto fail_fcf_read;
16406 	}
16407 	/* Issue the mailbox command asynchronously */
16408 	mboxq->vport = phba->pport;
16409 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
16410 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
16411 	if (rc == MBX_NOT_FINISHED)
16412 		error = -EIO;
16413 	else
16414 		error = 0;
16415 
16416 fail_fcf_read:
16417 	if (error && mboxq)
16418 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
16419 	return error;
16420 }
16421 
16422 /**
16423  * lpfc_check_next_fcf_pri_level
16424  * phba pointer to the lpfc_hba struct for this port.
16425  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
16426  * routine when the rr_bmask is empty. The FCF indecies are put into the
16427  * rr_bmask based on their priority level. Starting from the highest priority
16428  * to the lowest. The most likely FCF candidate will be in the highest
16429  * priority group. When this routine is called it searches the fcf_pri list for
16430  * next lowest priority group and repopulates the rr_bmask with only those
16431  * fcf_indexes.
16432  * returns:
16433  * 1=success 0=failure
16434  **/
16435 static int
16436 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
16437 {
16438 	uint16_t next_fcf_pri;
16439 	uint16_t last_index;
16440 	struct lpfc_fcf_pri *fcf_pri;
16441 	int rc;
16442 	int ret = 0;
16443 
16444 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
16445 			LPFC_SLI4_FCF_TBL_INDX_MAX);
16446 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16447 			"3060 Last IDX %d\n", last_index);
16448 
16449 	/* Verify the priority list has 2 or more entries */
16450 	spin_lock_irq(&phba->hbalock);
16451 	if (list_empty(&phba->fcf.fcf_pri_list) ||
16452 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
16453 		spin_unlock_irq(&phba->hbalock);
16454 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16455 			"3061 Last IDX %d\n", last_index);
16456 		return 0; /* Empty rr list */
16457 	}
16458 	spin_unlock_irq(&phba->hbalock);
16459 
16460 	next_fcf_pri = 0;
16461 	/*
16462 	 * Clear the rr_bmask and set all of the bits that are at this
16463 	 * priority.
16464 	 */
16465 	memset(phba->fcf.fcf_rr_bmask, 0,
16466 			sizeof(*phba->fcf.fcf_rr_bmask));
16467 	spin_lock_irq(&phba->hbalock);
16468 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
16469 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
16470 			continue;
16471 		/*
16472 		 * the 1st priority that has not FLOGI failed
16473 		 * will be the highest.
16474 		 */
16475 		if (!next_fcf_pri)
16476 			next_fcf_pri = fcf_pri->fcf_rec.priority;
16477 		spin_unlock_irq(&phba->hbalock);
16478 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
16479 			rc = lpfc_sli4_fcf_rr_index_set(phba,
16480 						fcf_pri->fcf_rec.fcf_index);
16481 			if (rc)
16482 				return 0;
16483 		}
16484 		spin_lock_irq(&phba->hbalock);
16485 	}
16486 	/*
16487 	 * if next_fcf_pri was not set above and the list is not empty then
16488 	 * we have failed flogis on all of them. So reset flogi failed
16489 	 * and start at the beginning.
16490 	 */
16491 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
16492 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
16493 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
16494 			/*
16495 			 * the 1st priority that has not FLOGI failed
16496 			 * will be the highest.
16497 			 */
16498 			if (!next_fcf_pri)
16499 				next_fcf_pri = fcf_pri->fcf_rec.priority;
16500 			spin_unlock_irq(&phba->hbalock);
16501 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
16502 				rc = lpfc_sli4_fcf_rr_index_set(phba,
16503 						fcf_pri->fcf_rec.fcf_index);
16504 				if (rc)
16505 					return 0;
16506 			}
16507 			spin_lock_irq(&phba->hbalock);
16508 		}
16509 	} else
16510 		ret = 1;
16511 	spin_unlock_irq(&phba->hbalock);
16512 
16513 	return ret;
16514 }
16515 /**
16516  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
16517  * @phba: pointer to lpfc hba data structure.
16518  *
16519  * This routine is to get the next eligible FCF record index in a round
16520  * robin fashion. If the next eligible FCF record index equals to the
16521  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
16522  * shall be returned, otherwise, the next eligible FCF record's index
16523  * shall be returned.
16524  **/
16525 uint16_t
16526 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
16527 {
16528 	uint16_t next_fcf_index;
16529 
16530 initial_priority:
16531 	/* Search start from next bit of currently registered FCF index */
16532 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
16533 
16534 next_priority:
16535 	/* Determine the next fcf index to check */
16536 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
16537 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
16538 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
16539 				       next_fcf_index);
16540 
16541 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
16542 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
16543 		/*
16544 		 * If we have wrapped then we need to clear the bits that
16545 		 * have been tested so that we can detect when we should
16546 		 * change the priority level.
16547 		 */
16548 		next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
16549 					       LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
16550 	}
16551 
16552 
16553 	/* Check roundrobin failover list empty condition */
16554 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
16555 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
16556 		/*
16557 		 * If next fcf index is not found check if there are lower
16558 		 * Priority level fcf's in the fcf_priority list.
16559 		 * Set up the rr_bmask with all of the avaiable fcf bits
16560 		 * at that level and continue the selection process.
16561 		 */
16562 		if (lpfc_check_next_fcf_pri_level(phba))
16563 			goto initial_priority;
16564 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
16565 				"2844 No roundrobin failover FCF available\n");
16566 		if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX)
16567 			return LPFC_FCOE_FCF_NEXT_NONE;
16568 		else {
16569 			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
16570 				"3063 Only FCF available idx %d, flag %x\n",
16571 				next_fcf_index,
16572 			phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag);
16573 			return next_fcf_index;
16574 		}
16575 	}
16576 
16577 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
16578 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
16579 		LPFC_FCF_FLOGI_FAILED) {
16580 		if (list_is_singular(&phba->fcf.fcf_pri_list))
16581 			return LPFC_FCOE_FCF_NEXT_NONE;
16582 
16583 		goto next_priority;
16584 	}
16585 
16586 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16587 			"2845 Get next roundrobin failover FCF (x%x)\n",
16588 			next_fcf_index);
16589 
16590 	return next_fcf_index;
16591 }
16592 
16593 /**
16594  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
16595  * @phba: pointer to lpfc hba data structure.
16596  *
16597  * This routine sets the FCF record index in to 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 setting the bit.
16601  *
16602  * Returns 0 if the index bit successfully set, otherwise, it returns
16603  * -EINVAL.
16604  **/
16605 int
16606 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
16607 {
16608 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
16609 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16610 				"2610 FCF (x%x) reached driver's book "
16611 				"keeping dimension:x%x\n",
16612 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
16613 		return -EINVAL;
16614 	}
16615 	/* Set the eligible FCF record index bmask */
16616 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
16617 
16618 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16619 			"2790 Set FCF (x%x) to roundrobin FCF failover "
16620 			"bmask\n", fcf_index);
16621 
16622 	return 0;
16623 }
16624 
16625 /**
16626  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
16627  * @phba: pointer to lpfc hba data structure.
16628  *
16629  * This routine clears the FCF record index from the eligible bmask for
16630  * roundrobin failover search. It checks to make sure that the index
16631  * does not go beyond the range of the driver allocated bmask dimension
16632  * before clearing the bit.
16633  **/
16634 void
16635 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
16636 {
16637 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
16638 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
16639 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16640 				"2762 FCF (x%x) reached driver's book "
16641 				"keeping dimension:x%x\n",
16642 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
16643 		return;
16644 	}
16645 	/* Clear the eligible FCF record index bmask */
16646 	spin_lock_irq(&phba->hbalock);
16647 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
16648 				 list) {
16649 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
16650 			list_del_init(&fcf_pri->list);
16651 			break;
16652 		}
16653 	}
16654 	spin_unlock_irq(&phba->hbalock);
16655 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
16656 
16657 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16658 			"2791 Clear FCF (x%x) from roundrobin failover "
16659 			"bmask\n", fcf_index);
16660 }
16661 
16662 /**
16663  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
16664  * @phba: pointer to lpfc hba data structure.
16665  *
16666  * This routine is the completion routine for the rediscover FCF table mailbox
16667  * command. If the mailbox command returned failure, it will try to stop the
16668  * FCF rediscover wait timer.
16669  **/
16670 static void
16671 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
16672 {
16673 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
16674 	uint32_t shdr_status, shdr_add_status;
16675 
16676 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
16677 
16678 	shdr_status = bf_get(lpfc_mbox_hdr_status,
16679 			     &redisc_fcf->header.cfg_shdr.response);
16680 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
16681 			     &redisc_fcf->header.cfg_shdr.response);
16682 	if (shdr_status || shdr_add_status) {
16683 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
16684 				"2746 Requesting for FCF rediscovery failed "
16685 				"status x%x add_status x%x\n",
16686 				shdr_status, shdr_add_status);
16687 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
16688 			spin_lock_irq(&phba->hbalock);
16689 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
16690 			spin_unlock_irq(&phba->hbalock);
16691 			/*
16692 			 * CVL event triggered FCF rediscover request failed,
16693 			 * last resort to re-try current registered FCF entry.
16694 			 */
16695 			lpfc_retry_pport_discovery(phba);
16696 		} else {
16697 			spin_lock_irq(&phba->hbalock);
16698 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
16699 			spin_unlock_irq(&phba->hbalock);
16700 			/*
16701 			 * DEAD FCF event triggered FCF rediscover request
16702 			 * failed, last resort to fail over as a link down
16703 			 * to FCF registration.
16704 			 */
16705 			lpfc_sli4_fcf_dead_failthrough(phba);
16706 		}
16707 	} else {
16708 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
16709 				"2775 Start FCF rediscover quiescent timer\n");
16710 		/*
16711 		 * Start FCF rediscovery wait timer for pending FCF
16712 		 * before rescan FCF record table.
16713 		 */
16714 		lpfc_fcf_redisc_wait_start_timer(phba);
16715 	}
16716 
16717 	mempool_free(mbox, phba->mbox_mem_pool);
16718 }
16719 
16720 /**
16721  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
16722  * @phba: pointer to lpfc hba data structure.
16723  *
16724  * This routine is invoked to request for rediscovery of the entire FCF table
16725  * by the port.
16726  **/
16727 int
16728 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
16729 {
16730 	LPFC_MBOXQ_t *mbox;
16731 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
16732 	int rc, length;
16733 
16734 	/* Cancel retry delay timers to all vports before FCF rediscover */
16735 	lpfc_cancel_all_vport_retry_delay_timer(phba);
16736 
16737 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16738 	if (!mbox) {
16739 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16740 				"2745 Failed to allocate mbox for "
16741 				"requesting FCF rediscover.\n");
16742 		return -ENOMEM;
16743 	}
16744 
16745 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
16746 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16747 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16748 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
16749 			 length, LPFC_SLI4_MBX_EMBED);
16750 
16751 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
16752 	/* Set count to 0 for invalidating the entire FCF database */
16753 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
16754 
16755 	/* Issue the mailbox command asynchronously */
16756 	mbox->vport = phba->pport;
16757 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
16758 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
16759 
16760 	if (rc == MBX_NOT_FINISHED) {
16761 		mempool_free(mbox, phba->mbox_mem_pool);
16762 		return -EIO;
16763 	}
16764 	return 0;
16765 }
16766 
16767 /**
16768  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
16769  * @phba: pointer to lpfc hba data structure.
16770  *
16771  * This function is the failover routine as a last resort to the FCF DEAD
16772  * event when driver failed to perform fast FCF failover.
16773  **/
16774 void
16775 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
16776 {
16777 	uint32_t link_state;
16778 
16779 	/*
16780 	 * Last resort as FCF DEAD event failover will treat this as
16781 	 * a link down, but save the link state because we don't want
16782 	 * it to be changed to Link Down unless it is already down.
16783 	 */
16784 	link_state = phba->link_state;
16785 	lpfc_linkdown(phba);
16786 	phba->link_state = link_state;
16787 
16788 	/* Unregister FCF if no devices connected to it */
16789 	lpfc_unregister_unused_fcf(phba);
16790 }
16791 
16792 /**
16793  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
16794  * @phba: pointer to lpfc hba data structure.
16795  * @rgn23_data: pointer to configure region 23 data.
16796  *
16797  * This function gets SLI3 port configure region 23 data through memory dump
16798  * mailbox command. When it successfully retrieves data, the size of the data
16799  * will be returned, otherwise, 0 will be returned.
16800  **/
16801 static uint32_t
16802 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
16803 {
16804 	LPFC_MBOXQ_t *pmb = NULL;
16805 	MAILBOX_t *mb;
16806 	uint32_t offset = 0;
16807 	int rc;
16808 
16809 	if (!rgn23_data)
16810 		return 0;
16811 
16812 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16813 	if (!pmb) {
16814 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16815 				"2600 failed to allocate mailbox memory\n");
16816 		return 0;
16817 	}
16818 	mb = &pmb->u.mb;
16819 
16820 	do {
16821 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
16822 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
16823 
16824 		if (rc != MBX_SUCCESS) {
16825 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16826 					"2601 failed to read config "
16827 					"region 23, rc 0x%x Status 0x%x\n",
16828 					rc, mb->mbxStatus);
16829 			mb->un.varDmp.word_cnt = 0;
16830 		}
16831 		/*
16832 		 * dump mem may return a zero when finished or we got a
16833 		 * mailbox error, either way we are done.
16834 		 */
16835 		if (mb->un.varDmp.word_cnt == 0)
16836 			break;
16837 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
16838 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
16839 
16840 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
16841 				       rgn23_data + offset,
16842 				       mb->un.varDmp.word_cnt);
16843 		offset += mb->un.varDmp.word_cnt;
16844 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
16845 
16846 	mempool_free(pmb, phba->mbox_mem_pool);
16847 	return offset;
16848 }
16849 
16850 /**
16851  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
16852  * @phba: pointer to lpfc hba data structure.
16853  * @rgn23_data: pointer to configure region 23 data.
16854  *
16855  * This function gets SLI4 port configure region 23 data through memory dump
16856  * mailbox command. When it successfully retrieves data, the size of the data
16857  * will be returned, otherwise, 0 will be returned.
16858  **/
16859 static uint32_t
16860 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
16861 {
16862 	LPFC_MBOXQ_t *mboxq = NULL;
16863 	struct lpfc_dmabuf *mp = NULL;
16864 	struct lpfc_mqe *mqe;
16865 	uint32_t data_length = 0;
16866 	int rc;
16867 
16868 	if (!rgn23_data)
16869 		return 0;
16870 
16871 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16872 	if (!mboxq) {
16873 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16874 				"3105 failed to allocate mailbox memory\n");
16875 		return 0;
16876 	}
16877 
16878 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
16879 		goto out;
16880 	mqe = &mboxq->u.mqe;
16881 	mp = (struct lpfc_dmabuf *) mboxq->context1;
16882 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
16883 	if (rc)
16884 		goto out;
16885 	data_length = mqe->un.mb_words[5];
16886 	if (data_length == 0)
16887 		goto out;
16888 	if (data_length > DMP_RGN23_SIZE) {
16889 		data_length = 0;
16890 		goto out;
16891 	}
16892 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
16893 out:
16894 	mempool_free(mboxq, phba->mbox_mem_pool);
16895 	if (mp) {
16896 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
16897 		kfree(mp);
16898 	}
16899 	return data_length;
16900 }
16901 
16902 /**
16903  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
16904  * @phba: pointer to lpfc hba data structure.
16905  *
16906  * This function read region 23 and parse TLV for port status to
16907  * decide if the user disaled the port. If the TLV indicates the
16908  * port is disabled, the hba_flag is set accordingly.
16909  **/
16910 void
16911 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
16912 {
16913 	uint8_t *rgn23_data = NULL;
16914 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
16915 	uint32_t offset = 0;
16916 
16917 	/* Get adapter Region 23 data */
16918 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
16919 	if (!rgn23_data)
16920 		goto out;
16921 
16922 	if (phba->sli_rev < LPFC_SLI_REV4)
16923 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
16924 	else {
16925 		if_type = bf_get(lpfc_sli_intf_if_type,
16926 				 &phba->sli4_hba.sli_intf);
16927 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
16928 			goto out;
16929 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
16930 	}
16931 
16932 	if (!data_size)
16933 		goto out;
16934 
16935 	/* Check the region signature first */
16936 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
16937 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16938 			"2619 Config region 23 has bad signature\n");
16939 			goto out;
16940 	}
16941 	offset += 4;
16942 
16943 	/* Check the data structure version */
16944 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
16945 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16946 			"2620 Config region 23 has bad version\n");
16947 		goto out;
16948 	}
16949 	offset += 4;
16950 
16951 	/* Parse TLV entries in the region */
16952 	while (offset < data_size) {
16953 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
16954 			break;
16955 		/*
16956 		 * If the TLV is not driver specific TLV or driver id is
16957 		 * not linux driver id, skip the record.
16958 		 */
16959 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
16960 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
16961 		    (rgn23_data[offset + 3] != 0)) {
16962 			offset += rgn23_data[offset + 1] * 4 + 4;
16963 			continue;
16964 		}
16965 
16966 		/* Driver found a driver specific TLV in the config region */
16967 		sub_tlv_len = rgn23_data[offset + 1] * 4;
16968 		offset += 4;
16969 		tlv_offset = 0;
16970 
16971 		/*
16972 		 * Search for configured port state sub-TLV.
16973 		 */
16974 		while ((offset < data_size) &&
16975 			(tlv_offset < sub_tlv_len)) {
16976 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
16977 				offset += 4;
16978 				tlv_offset += 4;
16979 				break;
16980 			}
16981 			if (rgn23_data[offset] != PORT_STE_TYPE) {
16982 				offset += rgn23_data[offset + 1] * 4 + 4;
16983 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
16984 				continue;
16985 			}
16986 
16987 			/* This HBA contains PORT_STE configured */
16988 			if (!rgn23_data[offset + 2])
16989 				phba->hba_flag |= LINK_DISABLED;
16990 
16991 			goto out;
16992 		}
16993 	}
16994 
16995 out:
16996 	kfree(rgn23_data);
16997 	return;
16998 }
16999 
17000 /**
17001  * lpfc_wr_object - write an object to the firmware
17002  * @phba: HBA structure that indicates port to create a queue on.
17003  * @dmabuf_list: list of dmabufs to write to the port.
17004  * @size: the total byte value of the objects to write to the port.
17005  * @offset: the current offset to be used to start the transfer.
17006  *
17007  * This routine will create a wr_object mailbox command to send to the port.
17008  * the mailbox command will be constructed using the dma buffers described in
17009  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
17010  * BDEs that the imbedded mailbox can support. The @offset variable will be
17011  * used to indicate the starting offset of the transfer and will also return
17012  * the offset after the write object mailbox has completed. @size is used to
17013  * determine the end of the object and whether the eof bit should be set.
17014  *
17015  * Return 0 is successful and offset will contain the the new offset to use
17016  * for the next write.
17017  * Return negative value for error cases.
17018  **/
17019 int
17020 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
17021 	       uint32_t size, uint32_t *offset)
17022 {
17023 	struct lpfc_mbx_wr_object *wr_object;
17024 	LPFC_MBOXQ_t *mbox;
17025 	int rc = 0, i = 0;
17026 	uint32_t shdr_status, shdr_add_status;
17027 	uint32_t mbox_tmo;
17028 	union lpfc_sli4_cfg_shdr *shdr;
17029 	struct lpfc_dmabuf *dmabuf;
17030 	uint32_t written = 0;
17031 
17032 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17033 	if (!mbox)
17034 		return -ENOMEM;
17035 
17036 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17037 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
17038 			sizeof(struct lpfc_mbx_wr_object) -
17039 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
17040 
17041 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
17042 	wr_object->u.request.write_offset = *offset;
17043 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
17044 	wr_object->u.request.object_name[0] =
17045 		cpu_to_le32(wr_object->u.request.object_name[0]);
17046 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
17047 	list_for_each_entry(dmabuf, dmabuf_list, list) {
17048 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
17049 			break;
17050 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
17051 		wr_object->u.request.bde[i].addrHigh =
17052 			putPaddrHigh(dmabuf->phys);
17053 		if (written + SLI4_PAGE_SIZE >= size) {
17054 			wr_object->u.request.bde[i].tus.f.bdeSize =
17055 				(size - written);
17056 			written += (size - written);
17057 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
17058 		} else {
17059 			wr_object->u.request.bde[i].tus.f.bdeSize =
17060 				SLI4_PAGE_SIZE;
17061 			written += SLI4_PAGE_SIZE;
17062 		}
17063 		i++;
17064 	}
17065 	wr_object->u.request.bde_count = i;
17066 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
17067 	if (!phba->sli4_hba.intr_enable)
17068 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17069 	else {
17070 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17071 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17072 	}
17073 	/* The IOCTL status is embedded in the mailbox subheader. */
17074 	shdr = (union lpfc_sli4_cfg_shdr *) &wr_object->header.cfg_shdr;
17075 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17076 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17077 	if (rc != MBX_TIMEOUT)
17078 		mempool_free(mbox, phba->mbox_mem_pool);
17079 	if (shdr_status || shdr_add_status || rc) {
17080 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17081 				"3025 Write Object mailbox failed with "
17082 				"status x%x add_status x%x, mbx status x%x\n",
17083 				shdr_status, shdr_add_status, rc);
17084 		rc = -ENXIO;
17085 	} else
17086 		*offset += wr_object->u.response.actual_write_length;
17087 	return rc;
17088 }
17089 
17090 /**
17091  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
17092  * @vport: pointer to vport data structure.
17093  *
17094  * This function iterate through the mailboxq and clean up all REG_LOGIN
17095  * and REG_VPI mailbox commands associated with the vport. This function
17096  * is called when driver want to restart discovery of the vport due to
17097  * a Clear Virtual Link event.
17098  **/
17099 void
17100 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
17101 {
17102 	struct lpfc_hba *phba = vport->phba;
17103 	LPFC_MBOXQ_t *mb, *nextmb;
17104 	struct lpfc_dmabuf *mp;
17105 	struct lpfc_nodelist *ndlp;
17106 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
17107 	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
17108 	LIST_HEAD(mbox_cmd_list);
17109 	uint8_t restart_loop;
17110 
17111 	/* Clean up internally queued mailbox commands with the vport */
17112 	spin_lock_irq(&phba->hbalock);
17113 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
17114 		if (mb->vport != vport)
17115 			continue;
17116 
17117 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
17118 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
17119 			continue;
17120 
17121 		list_del(&mb->list);
17122 		list_add_tail(&mb->list, &mbox_cmd_list);
17123 	}
17124 	/* Clean up active mailbox command with the vport */
17125 	mb = phba->sli.mbox_active;
17126 	if (mb && (mb->vport == vport)) {
17127 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
17128 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
17129 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17130 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
17131 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->context2;
17132 			/* Put reference count for delayed processing */
17133 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
17134 			/* Unregister the RPI when mailbox complete */
17135 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
17136 		}
17137 	}
17138 	/* Cleanup any mailbox completions which are not yet processed */
17139 	do {
17140 		restart_loop = 0;
17141 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
17142 			/*
17143 			 * If this mailox is already processed or it is
17144 			 * for another vport ignore it.
17145 			 */
17146 			if ((mb->vport != vport) ||
17147 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
17148 				continue;
17149 
17150 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
17151 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
17152 				continue;
17153 
17154 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17155 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
17156 				ndlp = (struct lpfc_nodelist *)mb->context2;
17157 				/* Unregister the RPI when mailbox complete */
17158 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
17159 				restart_loop = 1;
17160 				spin_unlock_irq(&phba->hbalock);
17161 				spin_lock(shost->host_lock);
17162 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
17163 				spin_unlock(shost->host_lock);
17164 				spin_lock_irq(&phba->hbalock);
17165 				break;
17166 			}
17167 		}
17168 	} while (restart_loop);
17169 
17170 	spin_unlock_irq(&phba->hbalock);
17171 
17172 	/* Release the cleaned-up mailbox commands */
17173 	while (!list_empty(&mbox_cmd_list)) {
17174 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
17175 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
17176 			mp = (struct lpfc_dmabuf *) (mb->context1);
17177 			if (mp) {
17178 				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
17179 				kfree(mp);
17180 			}
17181 			ndlp = (struct lpfc_nodelist *) mb->context2;
17182 			mb->context2 = NULL;
17183 			if (ndlp) {
17184 				spin_lock(shost->host_lock);
17185 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
17186 				spin_unlock(shost->host_lock);
17187 				lpfc_nlp_put(ndlp);
17188 			}
17189 		}
17190 		mempool_free(mb, phba->mbox_mem_pool);
17191 	}
17192 
17193 	/* Release the ndlp with the cleaned-up active mailbox command */
17194 	if (act_mbx_ndlp) {
17195 		spin_lock(shost->host_lock);
17196 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
17197 		spin_unlock(shost->host_lock);
17198 		lpfc_nlp_put(act_mbx_ndlp);
17199 	}
17200 }
17201 
17202 /**
17203  * lpfc_drain_txq - Drain the txq
17204  * @phba: Pointer to HBA context object.
17205  *
17206  * This function attempt to submit IOCBs on the txq
17207  * to the adapter.  For SLI4 adapters, the txq contains
17208  * ELS IOCBs that have been deferred because the there
17209  * are no SGLs.  This congestion can occur with large
17210  * vport counts during node discovery.
17211  **/
17212 
17213 uint32_t
17214 lpfc_drain_txq(struct lpfc_hba *phba)
17215 {
17216 	LIST_HEAD(completions);
17217 	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
17218 	struct lpfc_iocbq *piocbq = NULL;
17219 	unsigned long iflags = 0;
17220 	char *fail_msg = NULL;
17221 	struct lpfc_sglq *sglq;
17222 	union lpfc_wqe wqe;
17223 	uint32_t txq_cnt = 0;
17224 
17225 	spin_lock_irqsave(&pring->ring_lock, iflags);
17226 	list_for_each_entry(piocbq, &pring->txq, list) {
17227 		txq_cnt++;
17228 	}
17229 
17230 	if (txq_cnt > pring->txq_max)
17231 		pring->txq_max = txq_cnt;
17232 
17233 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
17234 
17235 	while (!list_empty(&pring->txq)) {
17236 		spin_lock_irqsave(&pring->ring_lock, iflags);
17237 
17238 		piocbq = lpfc_sli_ringtx_get(phba, pring);
17239 		if (!piocbq) {
17240 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
17241 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17242 				"2823 txq empty and txq_cnt is %d\n ",
17243 				txq_cnt);
17244 			break;
17245 		}
17246 		sglq = __lpfc_sli_get_sglq(phba, piocbq);
17247 		if (!sglq) {
17248 			__lpfc_sli_ringtx_put(phba, pring, piocbq);
17249 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
17250 			break;
17251 		}
17252 		txq_cnt--;
17253 
17254 		/* The xri and iocb resources secured,
17255 		 * attempt to issue request
17256 		 */
17257 		piocbq->sli4_lxritag = sglq->sli4_lxritag;
17258 		piocbq->sli4_xritag = sglq->sli4_xritag;
17259 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
17260 			fail_msg = "to convert bpl to sgl";
17261 		else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
17262 			fail_msg = "to convert iocb to wqe";
17263 		else if (lpfc_sli4_wq_put(phba->sli4_hba.els_wq, &wqe))
17264 			fail_msg = " - Wq is full";
17265 		else
17266 			lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
17267 
17268 		if (fail_msg) {
17269 			/* Failed means we can't issue and need to cancel */
17270 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17271 					"2822 IOCB failed %s iotag 0x%x "
17272 					"xri 0x%x\n",
17273 					fail_msg,
17274 					piocbq->iotag, piocbq->sli4_xritag);
17275 			list_add_tail(&piocbq->list, &completions);
17276 		}
17277 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
17278 	}
17279 
17280 	/* Cancel all the IOCBs that cannot be issued */
17281 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
17282 				IOERR_SLI_ABORTED);
17283 
17284 	return txq_cnt;
17285 }
17286