• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /asuswrt-rt-n18u-9.0.0.4.380.2695/release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/scsi/lpfc/
1/*******************************************************************
2 * This file is part of the Emulex Linux Device Driver for         *
3 * Fibre Channel Host Bus Adapters.                                *
4 * Copyright (C) 2004-2009 Emulex.  All rights reserved.           *
5 * EMULEX and SLI are trademarks of Emulex.                        *
6 * www.emulex.com                                                  *
7 * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
8 *                                                                 *
9 * This program is free software; you can redistribute it and/or   *
10 * modify it under the terms of version 2 of the GNU General       *
11 * Public License as published by the Free Software Foundation.    *
12 * This program is distributed in the hope that it will be useful. *
13 * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
14 * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
15 * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
16 * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
17 * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
18 * more details, a copy of which can be found in the file COPYING  *
19 * included with this package.                                     *
20 *******************************************************************/
21
22#include <linux/blkdev.h>
23#include <linux/pci.h>
24#include <linux/interrupt.h>
25#include <linux/delay.h>
26#include <linux/slab.h>
27
28#include <scsi/scsi.h>
29#include <scsi/scsi_cmnd.h>
30#include <scsi/scsi_device.h>
31#include <scsi/scsi_host.h>
32#include <scsi/scsi_transport_fc.h>
33#include <scsi/fc/fc_fs.h>
34#include <linux/aer.h>
35
36#include "lpfc_hw4.h"
37#include "lpfc_hw.h"
38#include "lpfc_sli.h"
39#include "lpfc_sli4.h"
40#include "lpfc_nl.h"
41#include "lpfc_disc.h"
42#include "lpfc_scsi.h"
43#include "lpfc.h"
44#include "lpfc_crtn.h"
45#include "lpfc_logmsg.h"
46#include "lpfc_compat.h"
47#include "lpfc_debugfs.h"
48#include "lpfc_vport.h"
49
50/* There are only four IOCB completion types. */
51typedef enum _lpfc_iocb_type {
52	LPFC_UNKNOWN_IOCB,
53	LPFC_UNSOL_IOCB,
54	LPFC_SOL_IOCB,
55	LPFC_ABORT_IOCB
56} lpfc_iocb_type;
57
58
59/* Provide function prototypes local to this module. */
60static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
61				  uint32_t);
62static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
63			      uint8_t *, uint32_t *);
64static struct lpfc_iocbq *lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *,
65							 struct lpfc_iocbq *);
66static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
67				      struct hbq_dmabuf *);
68static IOCB_t *
69lpfc_get_iocb_from_iocbq(struct lpfc_iocbq *iocbq)
70{
71	return &iocbq->iocb;
72}
73
74/**
75 * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
76 * @q: The Work Queue to operate on.
77 * @wqe: The work Queue Entry to put on the Work queue.
78 *
79 * This routine will copy the contents of @wqe to the next available entry on
80 * the @q. This function will then ring the Work Queue Doorbell to signal the
81 * HBA to start processing the Work Queue Entry. This function returns 0 if
82 * successful. If no entries are available on @q then this function will return
83 * -ENOMEM.
84 * The caller is expected to hold the hbalock when calling this routine.
85 **/
86static uint32_t
87lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe *wqe)
88{
89	union lpfc_wqe *temp_wqe = q->qe[q->host_index].wqe;
90	struct lpfc_register doorbell;
91	uint32_t host_index;
92
93	/* If the host has not yet processed the next entry then we are done */
94	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
95		return -ENOMEM;
96	/* set consumption flag every once in a while */
97	if (!((q->host_index + 1) % LPFC_RELEASE_NOTIFICATION_INTERVAL))
98		bf_set(lpfc_wqe_gen_wqec, &wqe->generic, 1);
99
100	lpfc_sli_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
101
102	/* Update the host index before invoking device */
103	host_index = q->host_index;
104	q->host_index = ((q->host_index + 1) % q->entry_count);
105
106	/* Ring Doorbell */
107	doorbell.word0 = 0;
108	bf_set(lpfc_wq_doorbell_num_posted, &doorbell, 1);
109	bf_set(lpfc_wq_doorbell_index, &doorbell, host_index);
110	bf_set(lpfc_wq_doorbell_id, &doorbell, q->queue_id);
111	writel(doorbell.word0, q->phba->sli4_hba.WQDBregaddr);
112	readl(q->phba->sli4_hba.WQDBregaddr); /* Flush */
113
114	return 0;
115}
116
117/**
118 * lpfc_sli4_wq_release - Updates internal hba index for WQ
119 * @q: The Work Queue to operate on.
120 * @index: The index to advance the hba index to.
121 *
122 * This routine will update the HBA index of a queue to reflect consumption of
123 * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
124 * an entry the host calls this function to update the queue's internal
125 * pointers. This routine returns the number of entries that were consumed by
126 * the HBA.
127 **/
128static uint32_t
129lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
130{
131	uint32_t released = 0;
132
133	if (q->hba_index == index)
134		return 0;
135	do {
136		q->hba_index = ((q->hba_index + 1) % q->entry_count);
137		released++;
138	} while (q->hba_index != index);
139	return released;
140}
141
142/**
143 * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
144 * @q: The Mailbox Queue to operate on.
145 * @wqe: The Mailbox Queue Entry to put on the Work queue.
146 *
147 * This routine will copy the contents of @mqe to the next available entry on
148 * the @q. This function will then ring the Work Queue Doorbell to signal the
149 * HBA to start processing the Work Queue Entry. This function returns 0 if
150 * successful. If no entries are available on @q then this function will return
151 * -ENOMEM.
152 * The caller is expected to hold the hbalock when calling this routine.
153 **/
154static uint32_t
155lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
156{
157	struct lpfc_mqe *temp_mqe = q->qe[q->host_index].mqe;
158	struct lpfc_register doorbell;
159	uint32_t host_index;
160
161	/* If the host has not yet processed the next entry then we are done */
162	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
163		return -ENOMEM;
164	lpfc_sli_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
165	/* Save off the mailbox pointer for completion */
166	q->phba->mbox = (MAILBOX_t *)temp_mqe;
167
168	/* Update the host index before invoking device */
169	host_index = q->host_index;
170	q->host_index = ((q->host_index + 1) % q->entry_count);
171
172	/* Ring Doorbell */
173	doorbell.word0 = 0;
174	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
175	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
176	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
177	readl(q->phba->sli4_hba.MQDBregaddr); /* Flush */
178	return 0;
179}
180
181/**
182 * lpfc_sli4_mq_release - Updates internal hba index for MQ
183 * @q: The Mailbox Queue to operate on.
184 *
185 * This routine will update the HBA index of a queue to reflect consumption of
186 * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
187 * an entry the host calls this function to update the queue's internal
188 * pointers. This routine returns the number of entries that were consumed by
189 * the HBA.
190 **/
191static uint32_t
192lpfc_sli4_mq_release(struct lpfc_queue *q)
193{
194	/* Clear the mailbox pointer for completion */
195	q->phba->mbox = NULL;
196	q->hba_index = ((q->hba_index + 1) % q->entry_count);
197	return 1;
198}
199
200/**
201 * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
202 * @q: The Event Queue to get the first valid EQE from
203 *
204 * This routine will get the first valid Event Queue Entry from @q, update
205 * the queue's internal hba index, and return the EQE. If no valid EQEs are in
206 * the Queue (no more work to do), or the Queue is full of EQEs that have been
207 * processed, but not popped back to the HBA then this routine will return NULL.
208 **/
209static struct lpfc_eqe *
210lpfc_sli4_eq_get(struct lpfc_queue *q)
211{
212	struct lpfc_eqe *eqe = q->qe[q->hba_index].eqe;
213
214	/* If the next EQE is not valid then we are done */
215	if (!bf_get_le32(lpfc_eqe_valid, eqe))
216		return NULL;
217	/* If the host has not yet processed the next entry then we are done */
218	if (((q->hba_index + 1) % q->entry_count) == q->host_index)
219		return NULL;
220
221	q->hba_index = ((q->hba_index + 1) % q->entry_count);
222	return eqe;
223}
224
225/**
226 * lpfc_sli4_eq_release - Indicates the host has finished processing an EQ
227 * @q: The Event Queue that the host has completed processing for.
228 * @arm: Indicates whether the host wants to arms this CQ.
229 *
230 * This routine will mark all Event Queue Entries on @q, from the last
231 * known completed entry to the last entry that was processed, as completed
232 * by clearing the valid bit for each completion queue entry. Then it will
233 * notify the HBA, by ringing the doorbell, that the EQEs have been processed.
234 * The internal host index in the @q will be updated by this routine to indicate
235 * that the host has finished processing the entries. The @arm parameter
236 * indicates that the queue should be rearmed when ringing the doorbell.
237 *
238 * This function will return the number of EQEs that were popped.
239 **/
240uint32_t
241lpfc_sli4_eq_release(struct lpfc_queue *q, bool arm)
242{
243	uint32_t released = 0;
244	struct lpfc_eqe *temp_eqe;
245	struct lpfc_register doorbell;
246
247	/* while there are valid entries */
248	while (q->hba_index != q->host_index) {
249		temp_eqe = q->qe[q->host_index].eqe;
250		bf_set_le32(lpfc_eqe_valid, temp_eqe, 0);
251		released++;
252		q->host_index = ((q->host_index + 1) % q->entry_count);
253	}
254	if (unlikely(released == 0 && !arm))
255		return 0;
256
257	/* ring doorbell for number popped */
258	doorbell.word0 = 0;
259	if (arm) {
260		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
261		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
262	}
263	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, released);
264	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
265	bf_set(lpfc_eqcq_doorbell_eqid, &doorbell, q->queue_id);
266	writel(doorbell.word0, q->phba->sli4_hba.EQCQDBregaddr);
267	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
268	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
269		readl(q->phba->sli4_hba.EQCQDBregaddr);
270	return released;
271}
272
273/**
274 * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
275 * @q: The Completion Queue to get the first valid CQE from
276 *
277 * This routine will get the first valid Completion Queue Entry from @q, update
278 * the queue's internal hba index, and return the CQE. If no valid CQEs are in
279 * the Queue (no more work to do), or the Queue is full of CQEs that have been
280 * processed, but not popped back to the HBA then this routine will return NULL.
281 **/
282static struct lpfc_cqe *
283lpfc_sli4_cq_get(struct lpfc_queue *q)
284{
285	struct lpfc_cqe *cqe;
286
287	/* If the next CQE is not valid then we are done */
288	if (!bf_get_le32(lpfc_cqe_valid, q->qe[q->hba_index].cqe))
289		return NULL;
290	/* If the host has not yet processed the next entry then we are done */
291	if (((q->hba_index + 1) % q->entry_count) == q->host_index)
292		return NULL;
293
294	cqe = q->qe[q->hba_index].cqe;
295	q->hba_index = ((q->hba_index + 1) % q->entry_count);
296	return cqe;
297}
298
299/**
300 * lpfc_sli4_cq_release - Indicates the host has finished processing a CQ
301 * @q: The Completion Queue that the host has completed processing for.
302 * @arm: Indicates whether the host wants to arms this CQ.
303 *
304 * This routine will mark all Completion queue entries on @q, from the last
305 * known completed entry to the last entry that was processed, as completed
306 * by clearing the valid bit for each completion queue entry. Then it will
307 * notify the HBA, by ringing the doorbell, that the CQEs have been processed.
308 * The internal host index in the @q will be updated by this routine to indicate
309 * that the host has finished processing the entries. The @arm parameter
310 * indicates that the queue should be rearmed when ringing the doorbell.
311 *
312 * This function will return the number of CQEs that were released.
313 **/
314uint32_t
315lpfc_sli4_cq_release(struct lpfc_queue *q, bool arm)
316{
317	uint32_t released = 0;
318	struct lpfc_cqe *temp_qe;
319	struct lpfc_register doorbell;
320
321	/* while there are valid entries */
322	while (q->hba_index != q->host_index) {
323		temp_qe = q->qe[q->host_index].cqe;
324		bf_set_le32(lpfc_cqe_valid, temp_qe, 0);
325		released++;
326		q->host_index = ((q->host_index + 1) % q->entry_count);
327	}
328	if (unlikely(released == 0 && !arm))
329		return 0;
330
331	/* ring doorbell for number popped */
332	doorbell.word0 = 0;
333	if (arm)
334		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
335	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, released);
336	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
337	bf_set(lpfc_eqcq_doorbell_cqid, &doorbell, q->queue_id);
338	writel(doorbell.word0, q->phba->sli4_hba.EQCQDBregaddr);
339	return released;
340}
341
342/**
343 * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
344 * @q: The Header Receive Queue to operate on.
345 * @wqe: The Receive Queue Entry to put on the Receive queue.
346 *
347 * This routine will copy the contents of @wqe to the next available entry on
348 * the @q. This function will then ring the Receive Queue Doorbell to signal the
349 * HBA to start processing the Receive Queue Entry. This function returns the
350 * index that the rqe was copied to if successful. If no entries are available
351 * on @q then this function will return -ENOMEM.
352 * The caller is expected to hold the hbalock when calling this routine.
353 **/
354static int
355lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
356		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
357{
358	struct lpfc_rqe *temp_hrqe = hq->qe[hq->host_index].rqe;
359	struct lpfc_rqe *temp_drqe = dq->qe[dq->host_index].rqe;
360	struct lpfc_register doorbell;
361	int put_index = hq->host_index;
362
363	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
364		return -EINVAL;
365	if (hq->host_index != dq->host_index)
366		return -EINVAL;
367	/* If the host has not yet processed the next entry then we are done */
368	if (((hq->host_index + 1) % hq->entry_count) == hq->hba_index)
369		return -EBUSY;
370	lpfc_sli_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
371	lpfc_sli_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
372
373	/* Update the host index to point to the next slot */
374	hq->host_index = ((hq->host_index + 1) % hq->entry_count);
375	dq->host_index = ((dq->host_index + 1) % dq->entry_count);
376
377	/* Ring The Header Receive Queue Doorbell */
378	if (!(hq->host_index % LPFC_RQ_POST_BATCH)) {
379		doorbell.word0 = 0;
380		bf_set(lpfc_rq_doorbell_num_posted, &doorbell,
381		       LPFC_RQ_POST_BATCH);
382		bf_set(lpfc_rq_doorbell_id, &doorbell, hq->queue_id);
383		writel(doorbell.word0, hq->phba->sli4_hba.RQDBregaddr);
384	}
385	return put_index;
386}
387
388/**
389 * lpfc_sli4_rq_release - Updates internal hba index for RQ
390 * @q: The Header Receive Queue to operate on.
391 *
392 * This routine will update the HBA index of a queue to reflect consumption of
393 * one Receive Queue Entry by the HBA. When the HBA indicates that it has
394 * consumed an entry the host calls this function to update the queue's
395 * internal pointers. This routine returns the number of entries that were
396 * consumed by the HBA.
397 **/
398static uint32_t
399lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
400{
401	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
402		return 0;
403	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
404	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
405	return 1;
406}
407
408/**
409 * lpfc_cmd_iocb - Get next command iocb entry in the ring
410 * @phba: Pointer to HBA context object.
411 * @pring: Pointer to driver SLI ring object.
412 *
413 * This function returns pointer to next command iocb entry
414 * in the command ring. The caller must hold hbalock to prevent
415 * other threads consume the next command iocb.
416 * SLI-2/SLI-3 provide different sized iocbs.
417 **/
418static inline IOCB_t *
419lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
420{
421	return (IOCB_t *) (((char *) pring->cmdringaddr) +
422			   pring->cmdidx * phba->iocb_cmd_size);
423}
424
425/**
426 * lpfc_resp_iocb - Get next response iocb entry in the ring
427 * @phba: Pointer to HBA context object.
428 * @pring: Pointer to driver SLI ring object.
429 *
430 * This function returns pointer to next response iocb entry
431 * in the response ring. The caller must hold hbalock to make sure
432 * that no other thread consume the next response iocb.
433 * SLI-2/SLI-3 provide different sized iocbs.
434 **/
435static inline IOCB_t *
436lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
437{
438	return (IOCB_t *) (((char *) pring->rspringaddr) +
439			   pring->rspidx * phba->iocb_rsp_size);
440}
441
442/**
443 * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
444 * @phba: Pointer to HBA context object.
445 *
446 * This function is called with hbalock held. This function
447 * allocates a new driver iocb object from the iocb pool. If the
448 * allocation is successful, it returns pointer to the newly
449 * allocated iocb object else it returns NULL.
450 **/
451static struct lpfc_iocbq *
452__lpfc_sli_get_iocbq(struct lpfc_hba *phba)
453{
454	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
455	struct lpfc_iocbq * iocbq = NULL;
456
457	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
458
459	if (iocbq)
460		phba->iocb_cnt++;
461	if (phba->iocb_cnt > phba->iocb_max)
462		phba->iocb_max = phba->iocb_cnt;
463	return iocbq;
464}
465
466/**
467 * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
468 * @phba: Pointer to HBA context object.
469 * @xritag: XRI value.
470 *
471 * This function clears the sglq pointer from the array of acive
472 * sglq's. The xritag that is passed in is used to index into the
473 * array. Before the xritag can be used it needs to be adjusted
474 * by subtracting the xribase.
475 *
476 * Returns sglq ponter = success, NULL = Failure.
477 **/
478static struct lpfc_sglq *
479__lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
480{
481	uint16_t adj_xri;
482	struct lpfc_sglq *sglq;
483	adj_xri = xritag - phba->sli4_hba.max_cfg_param.xri_base;
484	if (adj_xri > phba->sli4_hba.max_cfg_param.max_xri)
485		return NULL;
486	sglq = phba->sli4_hba.lpfc_sglq_active_list[adj_xri];
487	phba->sli4_hba.lpfc_sglq_active_list[adj_xri] = NULL;
488	return sglq;
489}
490
491/**
492 * __lpfc_get_active_sglq - Get the active sglq for this XRI.
493 * @phba: Pointer to HBA context object.
494 * @xritag: XRI value.
495 *
496 * This function returns the sglq pointer from the array of acive
497 * sglq's. The xritag that is passed in is used to index into the
498 * array. Before the xritag can be used it needs to be adjusted
499 * by subtracting the xribase.
500 *
501 * Returns sglq ponter = success, NULL = Failure.
502 **/
503struct lpfc_sglq *
504__lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
505{
506	uint16_t adj_xri;
507	struct lpfc_sglq *sglq;
508	adj_xri = xritag - phba->sli4_hba.max_cfg_param.xri_base;
509	if (adj_xri > phba->sli4_hba.max_cfg_param.max_xri)
510		return NULL;
511	sglq =  phba->sli4_hba.lpfc_sglq_active_list[adj_xri];
512	return sglq;
513}
514
515/**
516 * __lpfc_sli_get_sglq - Allocates an iocb object from sgl pool
517 * @phba: Pointer to HBA context object.
518 *
519 * This function is called with hbalock held. This function
520 * Gets a new driver sglq object from the sglq list. If the
521 * list is not empty then it is successful, it returns pointer to the newly
522 * allocated sglq object else it returns NULL.
523 **/
524static struct lpfc_sglq *
525__lpfc_sli_get_sglq(struct lpfc_hba *phba)
526{
527	struct list_head *lpfc_sgl_list = &phba->sli4_hba.lpfc_sgl_list;
528	struct lpfc_sglq *sglq = NULL;
529	uint16_t adj_xri;
530	list_remove_head(lpfc_sgl_list, sglq, struct lpfc_sglq, list);
531	if (!sglq)
532		return NULL;
533	adj_xri = sglq->sli4_xritag - phba->sli4_hba.max_cfg_param.xri_base;
534	phba->sli4_hba.lpfc_sglq_active_list[adj_xri] = sglq;
535	sglq->state = SGL_ALLOCATED;
536	return sglq;
537}
538
539/**
540 * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
541 * @phba: Pointer to HBA context object.
542 *
543 * This function is called with no lock held. This function
544 * allocates a new driver iocb object from the iocb pool. If the
545 * allocation is successful, it returns pointer to the newly
546 * allocated iocb object else it returns NULL.
547 **/
548struct lpfc_iocbq *
549lpfc_sli_get_iocbq(struct lpfc_hba *phba)
550{
551	struct lpfc_iocbq * iocbq = NULL;
552	unsigned long iflags;
553
554	spin_lock_irqsave(&phba->hbalock, iflags);
555	iocbq = __lpfc_sli_get_iocbq(phba);
556	spin_unlock_irqrestore(&phba->hbalock, iflags);
557	return iocbq;
558}
559
560/**
561 * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
562 * @phba: Pointer to HBA context object.
563 * @iocbq: Pointer to driver iocb object.
564 *
565 * This function is called with hbalock held to release driver
566 * iocb object to the iocb pool. The iotag in the iocb object
567 * does not change for each use of the iocb object. This function
568 * clears all other fields of the iocb object when it is freed.
569 * The sqlq structure that holds the xritag and phys and virtual
570 * mappings for the scatter gather list is retrieved from the
571 * active array of sglq. The get of the sglq pointer also clears
572 * the entry in the array. If the status of the IO indiactes that
573 * this IO was aborted then the sglq entry it put on the
574 * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
575 * IO has good status or fails for any other reason then the sglq
576 * entry is added to the free list (lpfc_sgl_list).
577 **/
578static void
579__lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
580{
581	struct lpfc_sglq *sglq;
582	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
583	unsigned long iflag = 0;
584	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
585
586	if (iocbq->sli4_xritag == NO_XRI)
587		sglq = NULL;
588	else
589		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_xritag);
590	if (sglq)  {
591		if ((iocbq->iocb_flag & LPFC_EXCHANGE_BUSY) &&
592			(sglq->state != SGL_XRI_ABORTED)) {
593			spin_lock_irqsave(&phba->sli4_hba.abts_sgl_list_lock,
594					iflag);
595			list_add(&sglq->list,
596				&phba->sli4_hba.lpfc_abts_els_sgl_list);
597			spin_unlock_irqrestore(
598				&phba->sli4_hba.abts_sgl_list_lock, iflag);
599		} else {
600			sglq->state = SGL_FREED;
601			list_add(&sglq->list, &phba->sli4_hba.lpfc_sgl_list);
602
603			/* Check if TXQ queue needs to be serviced */
604			if (pring->txq_cnt)
605				lpfc_worker_wake_up(phba);
606		}
607	}
608
609
610	/*
611	 * Clean all volatile data fields, preserve iotag and node struct.
612	 */
613	memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
614	iocbq->sli4_xritag = NO_XRI;
615	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
616}
617
618
619/**
620 * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
621 * @phba: Pointer to HBA context object.
622 * @iocbq: Pointer to driver iocb object.
623 *
624 * This function is called with hbalock held to release driver
625 * iocb object to the iocb pool. The iotag in the iocb object
626 * does not change for each use of the iocb object. This function
627 * clears all other fields of the iocb object when it is freed.
628 **/
629static void
630__lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
631{
632	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
633
634	/*
635	 * Clean all volatile data fields, preserve iotag and node struct.
636	 */
637	memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
638	iocbq->sli4_xritag = NO_XRI;
639	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
640}
641
642/**
643 * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
644 * @phba: Pointer to HBA context object.
645 * @iocbq: Pointer to driver iocb object.
646 *
647 * This function is called with hbalock held to release driver
648 * iocb object to the iocb pool. The iotag in the iocb object
649 * does not change for each use of the iocb object. This function
650 * clears all other fields of the iocb object when it is freed.
651 **/
652static void
653__lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
654{
655	phba->__lpfc_sli_release_iocbq(phba, iocbq);
656	phba->iocb_cnt--;
657}
658
659/**
660 * lpfc_sli_release_iocbq - Release iocb to the iocb pool
661 * @phba: Pointer to HBA context object.
662 * @iocbq: Pointer to driver iocb object.
663 *
664 * This function is called with no lock held to release the iocb to
665 * iocb pool.
666 **/
667void
668lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
669{
670	unsigned long iflags;
671
672	/*
673	 * Clean all volatile data fields, preserve iotag and node struct.
674	 */
675	spin_lock_irqsave(&phba->hbalock, iflags);
676	__lpfc_sli_release_iocbq(phba, iocbq);
677	spin_unlock_irqrestore(&phba->hbalock, iflags);
678}
679
680/**
681 * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
682 * @phba: Pointer to HBA context object.
683 * @iocblist: List of IOCBs.
684 * @ulpstatus: ULP status in IOCB command field.
685 * @ulpWord4: ULP word-4 in IOCB command field.
686 *
687 * This function is called with a list of IOCBs to cancel. It cancels the IOCB
688 * on the list by invoking the complete callback function associated with the
689 * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
690 * fields.
691 **/
692void
693lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
694		      uint32_t ulpstatus, uint32_t ulpWord4)
695{
696	struct lpfc_iocbq *piocb;
697
698	while (!list_empty(iocblist)) {
699		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
700
701		if (!piocb->iocb_cmpl)
702			lpfc_sli_release_iocbq(phba, piocb);
703		else {
704			piocb->iocb.ulpStatus = ulpstatus;
705			piocb->iocb.un.ulpWord[4] = ulpWord4;
706			(piocb->iocb_cmpl) (phba, piocb, piocb);
707		}
708	}
709	return;
710}
711
712/**
713 * lpfc_sli_iocb_cmd_type - Get the iocb type
714 * @iocb_cmnd: iocb command code.
715 *
716 * This function is called by ring event handler function to get the iocb type.
717 * This function translates the iocb command to an iocb command type used to
718 * decide the final disposition of each completed IOCB.
719 * The function returns
720 * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
721 * LPFC_SOL_IOCB     if it is a solicited iocb completion
722 * LPFC_ABORT_IOCB   if it is an abort iocb
723 * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
724 *
725 * The caller is not required to hold any lock.
726 **/
727static lpfc_iocb_type
728lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
729{
730	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
731
732	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
733		return 0;
734
735	switch (iocb_cmnd) {
736	case CMD_XMIT_SEQUENCE_CR:
737	case CMD_XMIT_SEQUENCE_CX:
738	case CMD_XMIT_BCAST_CN:
739	case CMD_XMIT_BCAST_CX:
740	case CMD_ELS_REQUEST_CR:
741	case CMD_ELS_REQUEST_CX:
742	case CMD_CREATE_XRI_CR:
743	case CMD_CREATE_XRI_CX:
744	case CMD_GET_RPI_CN:
745	case CMD_XMIT_ELS_RSP_CX:
746	case CMD_GET_RPI_CR:
747	case CMD_FCP_IWRITE_CR:
748	case CMD_FCP_IWRITE_CX:
749	case CMD_FCP_IREAD_CR:
750	case CMD_FCP_IREAD_CX:
751	case CMD_FCP_ICMND_CR:
752	case CMD_FCP_ICMND_CX:
753	case CMD_FCP_TSEND_CX:
754	case CMD_FCP_TRSP_CX:
755	case CMD_FCP_TRECEIVE_CX:
756	case CMD_FCP_AUTO_TRSP_CX:
757	case CMD_ADAPTER_MSG:
758	case CMD_ADAPTER_DUMP:
759	case CMD_XMIT_SEQUENCE64_CR:
760	case CMD_XMIT_SEQUENCE64_CX:
761	case CMD_XMIT_BCAST64_CN:
762	case CMD_XMIT_BCAST64_CX:
763	case CMD_ELS_REQUEST64_CR:
764	case CMD_ELS_REQUEST64_CX:
765	case CMD_FCP_IWRITE64_CR:
766	case CMD_FCP_IWRITE64_CX:
767	case CMD_FCP_IREAD64_CR:
768	case CMD_FCP_IREAD64_CX:
769	case CMD_FCP_ICMND64_CR:
770	case CMD_FCP_ICMND64_CX:
771	case CMD_FCP_TSEND64_CX:
772	case CMD_FCP_TRSP64_CX:
773	case CMD_FCP_TRECEIVE64_CX:
774	case CMD_GEN_REQUEST64_CR:
775	case CMD_GEN_REQUEST64_CX:
776	case CMD_XMIT_ELS_RSP64_CX:
777	case DSSCMD_IWRITE64_CR:
778	case DSSCMD_IWRITE64_CX:
779	case DSSCMD_IREAD64_CR:
780	case DSSCMD_IREAD64_CX:
781		type = LPFC_SOL_IOCB;
782		break;
783	case CMD_ABORT_XRI_CN:
784	case CMD_ABORT_XRI_CX:
785	case CMD_CLOSE_XRI_CN:
786	case CMD_CLOSE_XRI_CX:
787	case CMD_XRI_ABORTED_CX:
788	case CMD_ABORT_MXRI64_CN:
789	case CMD_XMIT_BLS_RSP64_CX:
790		type = LPFC_ABORT_IOCB;
791		break;
792	case CMD_RCV_SEQUENCE_CX:
793	case CMD_RCV_ELS_REQ_CX:
794	case CMD_RCV_SEQUENCE64_CX:
795	case CMD_RCV_ELS_REQ64_CX:
796	case CMD_ASYNC_STATUS:
797	case CMD_IOCB_RCV_SEQ64_CX:
798	case CMD_IOCB_RCV_ELS64_CX:
799	case CMD_IOCB_RCV_CONT64_CX:
800	case CMD_IOCB_RET_XRI64_CX:
801		type = LPFC_UNSOL_IOCB;
802		break;
803	case CMD_IOCB_XMIT_MSEQ64_CR:
804	case CMD_IOCB_XMIT_MSEQ64_CX:
805	case CMD_IOCB_RCV_SEQ_LIST64_CX:
806	case CMD_IOCB_RCV_ELS_LIST64_CX:
807	case CMD_IOCB_CLOSE_EXTENDED_CN:
808	case CMD_IOCB_ABORT_EXTENDED_CN:
809	case CMD_IOCB_RET_HBQE64_CN:
810	case CMD_IOCB_FCP_IBIDIR64_CR:
811	case CMD_IOCB_FCP_IBIDIR64_CX:
812	case CMD_IOCB_FCP_ITASKMGT64_CX:
813	case CMD_IOCB_LOGENTRY_CN:
814	case CMD_IOCB_LOGENTRY_ASYNC_CN:
815		printk("%s - Unhandled SLI-3 Command x%x\n",
816				__func__, iocb_cmnd);
817		type = LPFC_UNKNOWN_IOCB;
818		break;
819	default:
820		type = LPFC_UNKNOWN_IOCB;
821		break;
822	}
823
824	return type;
825}
826
827/**
828 * lpfc_sli_ring_map - Issue config_ring mbox for all rings
829 * @phba: Pointer to HBA context object.
830 *
831 * This function is called from SLI initialization code
832 * to configure every ring of the HBA's SLI interface. The
833 * caller is not required to hold any lock. This function issues
834 * a config_ring mailbox command for each ring.
835 * This function returns zero if successful else returns a negative
836 * error code.
837 **/
838static int
839lpfc_sli_ring_map(struct lpfc_hba *phba)
840{
841	struct lpfc_sli *psli = &phba->sli;
842	LPFC_MBOXQ_t *pmb;
843	MAILBOX_t *pmbox;
844	int i, rc, ret = 0;
845
846	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
847	if (!pmb)
848		return -ENOMEM;
849	pmbox = &pmb->u.mb;
850	phba->link_state = LPFC_INIT_MBX_CMDS;
851	for (i = 0; i < psli->num_rings; i++) {
852		lpfc_config_ring(phba, i, pmb);
853		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
854		if (rc != MBX_SUCCESS) {
855			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
856					"0446 Adapter failed to init (%d), "
857					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
858					"ring %d\n",
859					rc, pmbox->mbxCommand,
860					pmbox->mbxStatus, i);
861			phba->link_state = LPFC_HBA_ERROR;
862			ret = -ENXIO;
863			break;
864		}
865	}
866	mempool_free(pmb, phba->mbox_mem_pool);
867	return ret;
868}
869
870/**
871 * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
872 * @phba: Pointer to HBA context object.
873 * @pring: Pointer to driver SLI ring object.
874 * @piocb: Pointer to the driver iocb object.
875 *
876 * This function is called with hbalock held. The function adds the
877 * new iocb to txcmplq of the given ring. This function always returns
878 * 0. If this function is called for ELS ring, this function checks if
879 * there is a vport associated with the ELS command. This function also
880 * starts els_tmofunc timer if this is an ELS command.
881 **/
882static int
883lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
884			struct lpfc_iocbq *piocb)
885{
886	list_add_tail(&piocb->list, &pring->txcmplq);
887	piocb->iocb_flag |= LPFC_IO_ON_Q;
888	pring->txcmplq_cnt++;
889	if (pring->txcmplq_cnt > pring->txcmplq_max)
890		pring->txcmplq_max = pring->txcmplq_cnt;
891
892	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
893	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
894	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
895		if (!piocb->vport)
896			BUG();
897		else
898			mod_timer(&piocb->vport->els_tmofunc,
899				  jiffies + HZ * (phba->fc_ratov << 1));
900	}
901
902
903	return 0;
904}
905
906/**
907 * lpfc_sli_ringtx_get - Get first element of the txq
908 * @phba: Pointer to HBA context object.
909 * @pring: Pointer to driver SLI ring object.
910 *
911 * This function is called with hbalock held to get next
912 * iocb in txq of the given ring. If there is any iocb in
913 * the txq, the function returns first iocb in the list after
914 * removing the iocb from the list, else it returns NULL.
915 **/
916struct lpfc_iocbq *
917lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
918{
919	struct lpfc_iocbq *cmd_iocb;
920
921	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
922	if (cmd_iocb != NULL)
923		pring->txq_cnt--;
924	return cmd_iocb;
925}
926
927/**
928 * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
929 * @phba: Pointer to HBA context object.
930 * @pring: Pointer to driver SLI ring object.
931 *
932 * This function is called with hbalock held and the caller must post the
933 * iocb without releasing the lock. If the caller releases the lock,
934 * iocb slot returned by the function is not guaranteed to be available.
935 * The function returns pointer to the next available iocb slot if there
936 * is available slot in the ring, else it returns NULL.
937 * If the get index of the ring is ahead of the put index, the function
938 * will post an error attention event to the worker thread to take the
939 * HBA to offline state.
940 **/
941static IOCB_t *
942lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
943{
944	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
945	uint32_t  max_cmd_idx = pring->numCiocb;
946	if ((pring->next_cmdidx == pring->cmdidx) &&
947	   (++pring->next_cmdidx >= max_cmd_idx))
948		pring->next_cmdidx = 0;
949
950	if (unlikely(pring->local_getidx == pring->next_cmdidx)) {
951
952		pring->local_getidx = le32_to_cpu(pgp->cmdGetInx);
953
954		if (unlikely(pring->local_getidx >= max_cmd_idx)) {
955			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
956					"0315 Ring %d issue: portCmdGet %d "
957					"is bigger than cmd ring %d\n",
958					pring->ringno,
959					pring->local_getidx, max_cmd_idx);
960
961			phba->link_state = LPFC_HBA_ERROR;
962			/*
963			 * All error attention handlers are posted to
964			 * worker thread
965			 */
966			phba->work_ha |= HA_ERATT;
967			phba->work_hs = HS_FFER3;
968
969			lpfc_worker_wake_up(phba);
970
971			return NULL;
972		}
973
974		if (pring->local_getidx == pring->next_cmdidx)
975			return NULL;
976	}
977
978	return lpfc_cmd_iocb(phba, pring);
979}
980
981/**
982 * lpfc_sli_next_iotag - Get an iotag for the iocb
983 * @phba: Pointer to HBA context object.
984 * @iocbq: Pointer to driver iocb object.
985 *
986 * This function gets an iotag for the iocb. If there is no unused iotag and
987 * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
988 * array and assigns a new iotag.
989 * The function returns the allocated iotag if successful, else returns zero.
990 * Zero is not a valid iotag.
991 * The caller is not required to hold any lock.
992 **/
993uint16_t
994lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
995{
996	struct lpfc_iocbq **new_arr;
997	struct lpfc_iocbq **old_arr;
998	size_t new_len;
999	struct lpfc_sli *psli = &phba->sli;
1000	uint16_t iotag;
1001
1002	spin_lock_irq(&phba->hbalock);
1003	iotag = psli->last_iotag;
1004	if(++iotag < psli->iocbq_lookup_len) {
1005		psli->last_iotag = iotag;
1006		psli->iocbq_lookup[iotag] = iocbq;
1007		spin_unlock_irq(&phba->hbalock);
1008		iocbq->iotag = iotag;
1009		return iotag;
1010	} else if (psli->iocbq_lookup_len < (0xffff
1011					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
1012		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
1013		spin_unlock_irq(&phba->hbalock);
1014		new_arr = kzalloc(new_len * sizeof (struct lpfc_iocbq *),
1015				  GFP_KERNEL);
1016		if (new_arr) {
1017			spin_lock_irq(&phba->hbalock);
1018			old_arr = psli->iocbq_lookup;
1019			if (new_len <= psli->iocbq_lookup_len) {
1020				/* highly unprobable case */
1021				kfree(new_arr);
1022				iotag = psli->last_iotag;
1023				if(++iotag < psli->iocbq_lookup_len) {
1024					psli->last_iotag = iotag;
1025					psli->iocbq_lookup[iotag] = iocbq;
1026					spin_unlock_irq(&phba->hbalock);
1027					iocbq->iotag = iotag;
1028					return iotag;
1029				}
1030				spin_unlock_irq(&phba->hbalock);
1031				return 0;
1032			}
1033			if (psli->iocbq_lookup)
1034				memcpy(new_arr, old_arr,
1035				       ((psli->last_iotag  + 1) *
1036					sizeof (struct lpfc_iocbq *)));
1037			psli->iocbq_lookup = new_arr;
1038			psli->iocbq_lookup_len = new_len;
1039			psli->last_iotag = iotag;
1040			psli->iocbq_lookup[iotag] = iocbq;
1041			spin_unlock_irq(&phba->hbalock);
1042			iocbq->iotag = iotag;
1043			kfree(old_arr);
1044			return iotag;
1045		}
1046	} else
1047		spin_unlock_irq(&phba->hbalock);
1048
1049	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
1050			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
1051			psli->last_iotag);
1052
1053	return 0;
1054}
1055
1056/**
1057 * lpfc_sli_submit_iocb - Submit an iocb to the firmware
1058 * @phba: Pointer to HBA context object.
1059 * @pring: Pointer to driver SLI ring object.
1060 * @iocb: Pointer to iocb slot in the ring.
1061 * @nextiocb: Pointer to driver iocb object which need to be
1062 *            posted to firmware.
1063 *
1064 * This function is called with hbalock held to post a new iocb to
1065 * the firmware. This function copies the new iocb to ring iocb slot and
1066 * updates the ring pointers. It adds the new iocb to txcmplq if there is
1067 * a completion call back for this iocb else the function will free the
1068 * iocb object.
1069 **/
1070static void
1071lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1072		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
1073{
1074	/*
1075	 * Set up an iotag
1076	 */
1077	nextiocb->iocb.ulpIoTag = (nextiocb->iocb_cmpl) ? nextiocb->iotag : 0;
1078
1079
1080	if (pring->ringno == LPFC_ELS_RING) {
1081		lpfc_debugfs_slow_ring_trc(phba,
1082			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
1083			*(((uint32_t *) &nextiocb->iocb) + 4),
1084			*(((uint32_t *) &nextiocb->iocb) + 6),
1085			*(((uint32_t *) &nextiocb->iocb) + 7));
1086	}
1087
1088	/*
1089	 * Issue iocb command to adapter
1090	 */
1091	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
1092	wmb();
1093	pring->stats.iocb_cmd++;
1094
1095	/*
1096	 * If there is no completion routine to call, we can release the
1097	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
1098	 * that have no rsp ring completion, iocb_cmpl MUST be NULL.
1099	 */
1100	if (nextiocb->iocb_cmpl)
1101		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
1102	else
1103		__lpfc_sli_release_iocbq(phba, nextiocb);
1104
1105	/*
1106	 * Let the HBA know what IOCB slot will be the next one the
1107	 * driver will put a command into.
1108	 */
1109	pring->cmdidx = pring->next_cmdidx;
1110	writel(pring->cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
1111}
1112
1113/**
1114 * lpfc_sli_update_full_ring - Update the chip attention register
1115 * @phba: Pointer to HBA context object.
1116 * @pring: Pointer to driver SLI ring object.
1117 *
1118 * The caller is not required to hold any lock for calling this function.
1119 * This function updates the chip attention bits for the ring to inform firmware
1120 * that there are pending work to be done for this ring and requests an
1121 * interrupt when there is space available in the ring. This function is
1122 * called when the driver is unable to post more iocbs to the ring due
1123 * to unavailability of space in the ring.
1124 **/
1125static void
1126lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1127{
1128	int ringno = pring->ringno;
1129
1130	pring->flag |= LPFC_CALL_RING_AVAILABLE;
1131
1132	wmb();
1133
1134	/*
1135	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
1136	 * The HBA will tell us when an IOCB entry is available.
1137	 */
1138	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
1139	readl(phba->CAregaddr); /* flush */
1140
1141	pring->stats.iocb_cmd_full++;
1142}
1143
1144/**
1145 * lpfc_sli_update_ring - Update chip attention register
1146 * @phba: Pointer to HBA context object.
1147 * @pring: Pointer to driver SLI ring object.
1148 *
1149 * This function updates the chip attention register bit for the
1150 * given ring to inform HBA that there is more work to be done
1151 * in this ring. The caller is not required to hold any lock.
1152 **/
1153static void
1154lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1155{
1156	int ringno = pring->ringno;
1157
1158	/*
1159	 * Tell the HBA that there is work to do in this ring.
1160	 */
1161	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
1162		wmb();
1163		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
1164		readl(phba->CAregaddr); /* flush */
1165	}
1166}
1167
1168/**
1169 * lpfc_sli_resume_iocb - Process iocbs in the txq
1170 * @phba: Pointer to HBA context object.
1171 * @pring: Pointer to driver SLI ring object.
1172 *
1173 * This function is called with hbalock held to post pending iocbs
1174 * in the txq to the firmware. This function is called when driver
1175 * detects space available in the ring.
1176 **/
1177static void
1178lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1179{
1180	IOCB_t *iocb;
1181	struct lpfc_iocbq *nextiocb;
1182
1183	/*
1184	 * Check to see if:
1185	 *  (a) there is anything on the txq to send
1186	 *  (b) link is up
1187	 *  (c) link attention events can be processed (fcp ring only)
1188	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
1189	 */
1190	if (pring->txq_cnt &&
1191	    lpfc_is_link_up(phba) &&
1192	    (pring->ringno != phba->sli.fcp_ring ||
1193	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
1194
1195		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
1196		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
1197			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
1198
1199		if (iocb)
1200			lpfc_sli_update_ring(phba, pring);
1201		else
1202			lpfc_sli_update_full_ring(phba, pring);
1203	}
1204
1205	return;
1206}
1207
1208/**
1209 * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
1210 * @phba: Pointer to HBA context object.
1211 * @hbqno: HBQ number.
1212 *
1213 * This function is called with hbalock held to get the next
1214 * available slot for the given HBQ. If there is free slot
1215 * available for the HBQ it will return pointer to the next available
1216 * HBQ entry else it will return NULL.
1217 **/
1218static struct lpfc_hbq_entry *
1219lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
1220{
1221	struct hbq_s *hbqp = &phba->hbqs[hbqno];
1222
1223	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
1224	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
1225		hbqp->next_hbqPutIdx = 0;
1226
1227	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
1228		uint32_t raw_index = phba->hbq_get[hbqno];
1229		uint32_t getidx = le32_to_cpu(raw_index);
1230
1231		hbqp->local_hbqGetIdx = getidx;
1232
1233		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
1234			lpfc_printf_log(phba, KERN_ERR,
1235					LOG_SLI | LOG_VPORT,
1236					"1802 HBQ %d: local_hbqGetIdx "
1237					"%u is > than hbqp->entry_count %u\n",
1238					hbqno, hbqp->local_hbqGetIdx,
1239					hbqp->entry_count);
1240
1241			phba->link_state = LPFC_HBA_ERROR;
1242			return NULL;
1243		}
1244
1245		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
1246			return NULL;
1247	}
1248
1249	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
1250			hbqp->hbqPutIdx;
1251}
1252
1253/**
1254 * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
1255 * @phba: Pointer to HBA context object.
1256 *
1257 * This function is called with no lock held to free all the
1258 * hbq buffers while uninitializing the SLI interface. It also
1259 * frees the HBQ buffers returned by the firmware but not yet
1260 * processed by the upper layers.
1261 **/
1262void
1263lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
1264{
1265	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
1266	struct hbq_dmabuf *hbq_buf;
1267	unsigned long flags;
1268	int i, hbq_count;
1269	uint32_t hbqno;
1270
1271	hbq_count = lpfc_sli_hbq_count();
1272	/* Return all memory used by all HBQs */
1273	spin_lock_irqsave(&phba->hbalock, flags);
1274	for (i = 0; i < hbq_count; ++i) {
1275		list_for_each_entry_safe(dmabuf, next_dmabuf,
1276				&phba->hbqs[i].hbq_buffer_list, list) {
1277			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
1278			list_del(&hbq_buf->dbuf.list);
1279			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
1280		}
1281		phba->hbqs[i].buffer_count = 0;
1282	}
1283	/* Return all HBQ buffer that are in-fly */
1284	list_for_each_entry_safe(dmabuf, next_dmabuf, &phba->rb_pend_list,
1285				 list) {
1286		hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
1287		list_del(&hbq_buf->dbuf.list);
1288		if (hbq_buf->tag == -1) {
1289			(phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer)
1290				(phba, hbq_buf);
1291		} else {
1292			hbqno = hbq_buf->tag >> 16;
1293			if (hbqno >= LPFC_MAX_HBQS)
1294				(phba->hbqs[LPFC_ELS_HBQ].hbq_free_buffer)
1295					(phba, hbq_buf);
1296			else
1297				(phba->hbqs[hbqno].hbq_free_buffer)(phba,
1298					hbq_buf);
1299		}
1300	}
1301
1302	/* Mark the HBQs not in use */
1303	phba->hbq_in_use = 0;
1304	spin_unlock_irqrestore(&phba->hbalock, flags);
1305}
1306
1307/**
1308 * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
1309 * @phba: Pointer to HBA context object.
1310 * @hbqno: HBQ number.
1311 * @hbq_buf: Pointer to HBQ buffer.
1312 *
1313 * This function is called with the hbalock held to post a
1314 * hbq buffer to the firmware. If the function finds an empty
1315 * slot in the HBQ, it will post the buffer. The function will return
1316 * pointer to the hbq entry if it successfully post the buffer
1317 * else it will return NULL.
1318 **/
1319static int
1320lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
1321			 struct hbq_dmabuf *hbq_buf)
1322{
1323	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
1324}
1325
1326/**
1327 * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
1328 * @phba: Pointer to HBA context object.
1329 * @hbqno: HBQ number.
1330 * @hbq_buf: Pointer to HBQ buffer.
1331 *
1332 * This function is called with the hbalock held to post a hbq buffer to the
1333 * firmware. If the function finds an empty slot in the HBQ, it will post the
1334 * buffer and place it on the hbq_buffer_list. The function will return zero if
1335 * it successfully post the buffer else it will return an error.
1336 **/
1337static int
1338lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
1339			    struct hbq_dmabuf *hbq_buf)
1340{
1341	struct lpfc_hbq_entry *hbqe;
1342	dma_addr_t physaddr = hbq_buf->dbuf.phys;
1343
1344	/* Get next HBQ entry slot to use */
1345	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
1346	if (hbqe) {
1347		struct hbq_s *hbqp = &phba->hbqs[hbqno];
1348
1349		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
1350		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
1351		hbqe->bde.tus.f.bdeSize = hbq_buf->size;
1352		hbqe->bde.tus.f.bdeFlags = 0;
1353		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
1354		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
1355				/* Sync SLIM */
1356		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
1357		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
1358				/* flush */
1359		readl(phba->hbq_put + hbqno);
1360		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
1361		return 0;
1362	} else
1363		return -ENOMEM;
1364}
1365
1366/**
1367 * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
1368 * @phba: Pointer to HBA context object.
1369 * @hbqno: HBQ number.
1370 * @hbq_buf: Pointer to HBQ buffer.
1371 *
1372 * This function is called with the hbalock held to post an RQE to the SLI4
1373 * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
1374 * the hbq_buffer_list and return zero, otherwise it will return an error.
1375 **/
1376static int
1377lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
1378			    struct hbq_dmabuf *hbq_buf)
1379{
1380	int rc;
1381	struct lpfc_rqe hrqe;
1382	struct lpfc_rqe drqe;
1383
1384	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
1385	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
1386	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
1387	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
1388	rc = lpfc_sli4_rq_put(phba->sli4_hba.hdr_rq, phba->sli4_hba.dat_rq,
1389			      &hrqe, &drqe);
1390	if (rc < 0)
1391		return rc;
1392	hbq_buf->tag = rc;
1393	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
1394	return 0;
1395}
1396
1397/* HBQ for ELS and CT traffic. */
1398static struct lpfc_hbq_init lpfc_els_hbq = {
1399	.rn = 1,
1400	.entry_count = 256,
1401	.mask_count = 0,
1402	.profile = 0,
1403	.ring_mask = (1 << LPFC_ELS_RING),
1404	.buffer_count = 0,
1405	.init_count = 40,
1406	.add_count = 40,
1407};
1408
1409/* HBQ for the extra ring if needed */
1410static struct lpfc_hbq_init lpfc_extra_hbq = {
1411	.rn = 1,
1412	.entry_count = 200,
1413	.mask_count = 0,
1414	.profile = 0,
1415	.ring_mask = (1 << LPFC_EXTRA_RING),
1416	.buffer_count = 0,
1417	.init_count = 0,
1418	.add_count = 5,
1419};
1420
1421/* Array of HBQs */
1422struct lpfc_hbq_init *lpfc_hbq_defs[] = {
1423	&lpfc_els_hbq,
1424	&lpfc_extra_hbq,
1425};
1426
1427/**
1428 * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
1429 * @phba: Pointer to HBA context object.
1430 * @hbqno: HBQ number.
1431 * @count: Number of HBQ buffers to be posted.
1432 *
1433 * This function is called with no lock held to post more hbq buffers to the
1434 * given HBQ. The function returns the number of HBQ buffers successfully
1435 * posted.
1436 **/
1437static int
1438lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
1439{
1440	uint32_t i, posted = 0;
1441	unsigned long flags;
1442	struct hbq_dmabuf *hbq_buffer;
1443	LIST_HEAD(hbq_buf_list);
1444	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
1445		return 0;
1446
1447	if ((phba->hbqs[hbqno].buffer_count + count) >
1448	    lpfc_hbq_defs[hbqno]->entry_count)
1449		count = lpfc_hbq_defs[hbqno]->entry_count -
1450					phba->hbqs[hbqno].buffer_count;
1451	if (!count)
1452		return 0;
1453	/* Allocate HBQ entries */
1454	for (i = 0; i < count; i++) {
1455		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
1456		if (!hbq_buffer)
1457			break;
1458		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
1459	}
1460	/* Check whether HBQ is still in use */
1461	spin_lock_irqsave(&phba->hbalock, flags);
1462	if (!phba->hbq_in_use)
1463		goto err;
1464	while (!list_empty(&hbq_buf_list)) {
1465		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
1466				 dbuf.list);
1467		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
1468				      (hbqno << 16));
1469		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
1470			phba->hbqs[hbqno].buffer_count++;
1471			posted++;
1472		} else
1473			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
1474	}
1475	spin_unlock_irqrestore(&phba->hbalock, flags);
1476	return posted;
1477err:
1478	spin_unlock_irqrestore(&phba->hbalock, flags);
1479	while (!list_empty(&hbq_buf_list)) {
1480		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
1481				 dbuf.list);
1482		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
1483	}
1484	return 0;
1485}
1486
1487/**
1488 * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
1489 * @phba: Pointer to HBA context object.
1490 * @qno: HBQ number.
1491 *
1492 * This function posts more buffers to the HBQ. This function
1493 * is called with no lock held. The function returns the number of HBQ entries
1494 * successfully allocated.
1495 **/
1496int
1497lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
1498{
1499	if (phba->sli_rev == LPFC_SLI_REV4)
1500		return 0;
1501	else
1502		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
1503					 lpfc_hbq_defs[qno]->add_count);
1504}
1505
1506/**
1507 * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
1508 * @phba: Pointer to HBA context object.
1509 * @qno:  HBQ queue number.
1510 *
1511 * This function is called from SLI initialization code path with
1512 * no lock held to post initial HBQ buffers to firmware. The
1513 * function returns the number of HBQ entries successfully allocated.
1514 **/
1515static int
1516lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
1517{
1518	if (phba->sli_rev == LPFC_SLI_REV4)
1519		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
1520					 lpfc_hbq_defs[qno]->entry_count);
1521	else
1522		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
1523					 lpfc_hbq_defs[qno]->init_count);
1524}
1525
1526/**
1527 * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
1528 * @phba: Pointer to HBA context object.
1529 * @hbqno: HBQ number.
1530 *
1531 * This function removes the first hbq buffer on an hbq list and returns a
1532 * pointer to that buffer. If it finds no buffers on the list it returns NULL.
1533 **/
1534static struct hbq_dmabuf *
1535lpfc_sli_hbqbuf_get(struct list_head *rb_list)
1536{
1537	struct lpfc_dmabuf *d_buf;
1538
1539	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
1540	if (!d_buf)
1541		return NULL;
1542	return container_of(d_buf, struct hbq_dmabuf, dbuf);
1543}
1544
1545/**
1546 * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
1547 * @phba: Pointer to HBA context object.
1548 * @tag: Tag of the hbq buffer.
1549 *
1550 * This function is called with hbalock held. This function searches
1551 * for the hbq buffer associated with the given tag in the hbq buffer
1552 * list. If it finds the hbq buffer, it returns the hbq_buffer other wise
1553 * it returns NULL.
1554 **/
1555static struct hbq_dmabuf *
1556lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
1557{
1558	struct lpfc_dmabuf *d_buf;
1559	struct hbq_dmabuf *hbq_buf;
1560	uint32_t hbqno;
1561
1562	hbqno = tag >> 16;
1563	if (hbqno >= LPFC_MAX_HBQS)
1564		return NULL;
1565
1566	spin_lock_irq(&phba->hbalock);
1567	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
1568		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
1569		if (hbq_buf->tag == tag) {
1570			spin_unlock_irq(&phba->hbalock);
1571			return hbq_buf;
1572		}
1573	}
1574	spin_unlock_irq(&phba->hbalock);
1575	lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_VPORT,
1576			"1803 Bad hbq tag. Data: x%x x%x\n",
1577			tag, phba->hbqs[tag >> 16].buffer_count);
1578	return NULL;
1579}
1580
1581/**
1582 * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
1583 * @phba: Pointer to HBA context object.
1584 * @hbq_buffer: Pointer to HBQ buffer.
1585 *
1586 * This function is called with hbalock. This function gives back
1587 * the hbq buffer to firmware. If the HBQ does not have space to
1588 * post the buffer, it will free the buffer.
1589 **/
1590void
1591lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
1592{
1593	uint32_t hbqno;
1594
1595	if (hbq_buffer) {
1596		hbqno = hbq_buffer->tag >> 16;
1597		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
1598			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
1599	}
1600}
1601
1602/**
1603 * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
1604 * @mbxCommand: mailbox command code.
1605 *
1606 * This function is called by the mailbox event handler function to verify
1607 * that the completed mailbox command is a legitimate mailbox command. If the
1608 * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
1609 * and the mailbox event handler will take the HBA offline.
1610 **/
1611static int
1612lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
1613{
1614	uint8_t ret;
1615
1616	switch (mbxCommand) {
1617	case MBX_LOAD_SM:
1618	case MBX_READ_NV:
1619	case MBX_WRITE_NV:
1620	case MBX_WRITE_VPARMS:
1621	case MBX_RUN_BIU_DIAG:
1622	case MBX_INIT_LINK:
1623	case MBX_DOWN_LINK:
1624	case MBX_CONFIG_LINK:
1625	case MBX_CONFIG_RING:
1626	case MBX_RESET_RING:
1627	case MBX_READ_CONFIG:
1628	case MBX_READ_RCONFIG:
1629	case MBX_READ_SPARM:
1630	case MBX_READ_STATUS:
1631	case MBX_READ_RPI:
1632	case MBX_READ_XRI:
1633	case MBX_READ_REV:
1634	case MBX_READ_LNK_STAT:
1635	case MBX_REG_LOGIN:
1636	case MBX_UNREG_LOGIN:
1637	case MBX_READ_LA:
1638	case MBX_CLEAR_LA:
1639	case MBX_DUMP_MEMORY:
1640	case MBX_DUMP_CONTEXT:
1641	case MBX_RUN_DIAGS:
1642	case MBX_RESTART:
1643	case MBX_UPDATE_CFG:
1644	case MBX_DOWN_LOAD:
1645	case MBX_DEL_LD_ENTRY:
1646	case MBX_RUN_PROGRAM:
1647	case MBX_SET_MASK:
1648	case MBX_SET_VARIABLE:
1649	case MBX_UNREG_D_ID:
1650	case MBX_KILL_BOARD:
1651	case MBX_CONFIG_FARP:
1652	case MBX_BEACON:
1653	case MBX_LOAD_AREA:
1654	case MBX_RUN_BIU_DIAG64:
1655	case MBX_CONFIG_PORT:
1656	case MBX_READ_SPARM64:
1657	case MBX_READ_RPI64:
1658	case MBX_REG_LOGIN64:
1659	case MBX_READ_LA64:
1660	case MBX_WRITE_WWN:
1661	case MBX_SET_DEBUG:
1662	case MBX_LOAD_EXP_ROM:
1663	case MBX_ASYNCEVT_ENABLE:
1664	case MBX_REG_VPI:
1665	case MBX_UNREG_VPI:
1666	case MBX_HEARTBEAT:
1667	case MBX_PORT_CAPABILITIES:
1668	case MBX_PORT_IOV_CONTROL:
1669	case MBX_SLI4_CONFIG:
1670	case MBX_SLI4_REQ_FTRS:
1671	case MBX_REG_FCFI:
1672	case MBX_UNREG_FCFI:
1673	case MBX_REG_VFI:
1674	case MBX_UNREG_VFI:
1675	case MBX_INIT_VPI:
1676	case MBX_INIT_VFI:
1677	case MBX_RESUME_RPI:
1678	case MBX_READ_EVENT_LOG_STATUS:
1679	case MBX_READ_EVENT_LOG:
1680		ret = mbxCommand;
1681		break;
1682	default:
1683		ret = MBX_SHUTDOWN;
1684		break;
1685	}
1686	return ret;
1687}
1688
1689/**
1690 * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
1691 * @phba: Pointer to HBA context object.
1692 * @pmboxq: Pointer to mailbox command.
1693 *
1694 * This is completion handler function for mailbox commands issued from
1695 * lpfc_sli_issue_mbox_wait function. This function is called by the
1696 * mailbox event handler function with no lock held. This function
1697 * will wake up thread waiting on the wait queue pointed by context1
1698 * of the mailbox.
1699 **/
1700void
1701lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
1702{
1703	wait_queue_head_t *pdone_q;
1704	unsigned long drvr_flag;
1705
1706	/*
1707	 * If pdone_q is empty, the driver thread gave up waiting and
1708	 * continued running.
1709	 */
1710	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
1711	spin_lock_irqsave(&phba->hbalock, drvr_flag);
1712	pdone_q = (wait_queue_head_t *) pmboxq->context1;
1713	if (pdone_q)
1714		wake_up_interruptible(pdone_q);
1715	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
1716	return;
1717}
1718
1719
1720/**
1721 * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
1722 * @phba: Pointer to HBA context object.
1723 * @pmb: Pointer to mailbox object.
1724 *
1725 * This function is the default mailbox completion handler. It
1726 * frees the memory resources associated with the completed mailbox
1727 * command. If the completed command is a REG_LOGIN mailbox command,
1728 * this function will issue a UREG_LOGIN to re-claim the RPI.
1729 **/
1730void
1731lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
1732{
1733	struct lpfc_dmabuf *mp;
1734	uint16_t rpi, vpi;
1735	int rc;
1736	struct lpfc_vport  *vport = pmb->vport;
1737
1738	mp = (struct lpfc_dmabuf *) (pmb->context1);
1739
1740	if (mp) {
1741		lpfc_mbuf_free(phba, mp->virt, mp->phys);
1742		kfree(mp);
1743	}
1744
1745	if ((pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) &&
1746	    (phba->sli_rev == LPFC_SLI_REV4))
1747		lpfc_sli4_free_rpi(phba, pmb->u.mb.un.varUnregLogin.rpi);
1748
1749	/*
1750	 * If a REG_LOGIN succeeded  after node is destroyed or node
1751	 * is in re-discovery driver need to cleanup the RPI.
1752	 */
1753	if (!(phba->pport->load_flag & FC_UNLOADING) &&
1754	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
1755	    !pmb->u.mb.mbxStatus) {
1756		rpi = pmb->u.mb.un.varWords[0];
1757		vpi = pmb->u.mb.un.varRegLogin.vpi - phba->vpi_base;
1758		lpfc_unreg_login(phba, vpi, rpi, pmb);
1759		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
1760		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
1761		if (rc != MBX_NOT_FINISHED)
1762			return;
1763	}
1764
1765	/* Unreg VPI, if the REG_VPI succeed after VLink failure */
1766	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
1767		!(phba->pport->load_flag & FC_UNLOADING) &&
1768		!pmb->u.mb.mbxStatus) {
1769		lpfc_unreg_vpi(phba, pmb->u.mb.un.varRegVpi.vpi, pmb);
1770		pmb->vport = vport;
1771		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
1772		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
1773		if (rc != MBX_NOT_FINISHED)
1774			return;
1775	}
1776
1777	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
1778		lpfc_sli4_mbox_cmd_free(phba, pmb);
1779	else
1780		mempool_free(pmb, phba->mbox_mem_pool);
1781}
1782
1783/**
1784 * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
1785 * @phba: Pointer to HBA context object.
1786 *
1787 * This function is called with no lock held. This function processes all
1788 * the completed mailbox commands and gives it to upper layers. The interrupt
1789 * service routine processes mailbox completion interrupt and adds completed
1790 * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
1791 * Worker thread call lpfc_sli_handle_mb_event, which will return the
1792 * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
1793 * function returns the mailbox commands to the upper layer by calling the
1794 * completion handler function of each mailbox.
1795 **/
1796int
1797lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
1798{
1799	MAILBOX_t *pmbox;
1800	LPFC_MBOXQ_t *pmb;
1801	int rc;
1802	LIST_HEAD(cmplq);
1803
1804	phba->sli.slistat.mbox_event++;
1805
1806	/* Get all completed mailboxe buffers into the cmplq */
1807	spin_lock_irq(&phba->hbalock);
1808	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
1809	spin_unlock_irq(&phba->hbalock);
1810
1811	/* Get a Mailbox buffer to setup mailbox commands for callback */
1812	do {
1813		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
1814		if (pmb == NULL)
1815			break;
1816
1817		pmbox = &pmb->u.mb;
1818
1819		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
1820			if (pmb->vport) {
1821				lpfc_debugfs_disc_trc(pmb->vport,
1822					LPFC_DISC_TRC_MBOX_VPORT,
1823					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
1824					(uint32_t)pmbox->mbxCommand,
1825					pmbox->un.varWords[0],
1826					pmbox->un.varWords[1]);
1827			}
1828			else {
1829				lpfc_debugfs_disc_trc(phba->pport,
1830					LPFC_DISC_TRC_MBOX,
1831					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
1832					(uint32_t)pmbox->mbxCommand,
1833					pmbox->un.varWords[0],
1834					pmbox->un.varWords[1]);
1835			}
1836		}
1837
1838		/*
1839		 * It is a fatal error if unknown mbox command completion.
1840		 */
1841		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
1842		    MBX_SHUTDOWN) {
1843			/* Unknown mailbox command compl */
1844			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
1845					"(%d):0323 Unknown Mailbox command "
1846					"x%x (x%x) Cmpl\n",
1847					pmb->vport ? pmb->vport->vpi : 0,
1848					pmbox->mbxCommand,
1849					lpfc_sli4_mbox_opcode_get(phba, pmb));
1850			phba->link_state = LPFC_HBA_ERROR;
1851			phba->work_hs = HS_FFER3;
1852			lpfc_handle_eratt(phba);
1853			continue;
1854		}
1855
1856		if (pmbox->mbxStatus) {
1857			phba->sli.slistat.mbox_stat_err++;
1858			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
1859				/* Mbox cmd cmpl error - RETRYing */
1860				lpfc_printf_log(phba, KERN_INFO,
1861						LOG_MBOX | LOG_SLI,
1862						"(%d):0305 Mbox cmd cmpl "
1863						"error - RETRYing Data: x%x "
1864						"(x%x) x%x x%x x%x\n",
1865						pmb->vport ? pmb->vport->vpi :0,
1866						pmbox->mbxCommand,
1867						lpfc_sli4_mbox_opcode_get(phba,
1868									  pmb),
1869						pmbox->mbxStatus,
1870						pmbox->un.varWords[0],
1871						pmb->vport->port_state);
1872				pmbox->mbxStatus = 0;
1873				pmbox->mbxOwner = OWN_HOST;
1874				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
1875				if (rc != MBX_NOT_FINISHED)
1876					continue;
1877			}
1878		}
1879
1880		/* Mailbox cmd <cmd> Cmpl <cmpl> */
1881		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
1882				"(%d):0307 Mailbox cmd x%x (x%x) Cmpl x%p "
1883				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x\n",
1884				pmb->vport ? pmb->vport->vpi : 0,
1885				pmbox->mbxCommand,
1886				lpfc_sli4_mbox_opcode_get(phba, pmb),
1887				pmb->mbox_cmpl,
1888				*((uint32_t *) pmbox),
1889				pmbox->un.varWords[0],
1890				pmbox->un.varWords[1],
1891				pmbox->un.varWords[2],
1892				pmbox->un.varWords[3],
1893				pmbox->un.varWords[4],
1894				pmbox->un.varWords[5],
1895				pmbox->un.varWords[6],
1896				pmbox->un.varWords[7]);
1897
1898		if (pmb->mbox_cmpl)
1899			pmb->mbox_cmpl(phba,pmb);
1900	} while (1);
1901	return 0;
1902}
1903
1904/**
1905 * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
1906 * @phba: Pointer to HBA context object.
1907 * @pring: Pointer to driver SLI ring object.
1908 * @tag: buffer tag.
1909 *
1910 * This function is called with no lock held. When QUE_BUFTAG_BIT bit
1911 * is set in the tag the buffer is posted for a particular exchange,
1912 * the function will return the buffer without replacing the buffer.
1913 * If the buffer is for unsolicited ELS or CT traffic, this function
1914 * returns the buffer and also posts another buffer to the firmware.
1915 **/
1916static struct lpfc_dmabuf *
1917lpfc_sli_get_buff(struct lpfc_hba *phba,
1918		  struct lpfc_sli_ring *pring,
1919		  uint32_t tag)
1920{
1921	struct hbq_dmabuf *hbq_entry;
1922
1923	if (tag & QUE_BUFTAG_BIT)
1924		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
1925	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
1926	if (!hbq_entry)
1927		return NULL;
1928	return &hbq_entry->dbuf;
1929}
1930
1931/**
1932 * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
1933 * @phba: Pointer to HBA context object.
1934 * @pring: Pointer to driver SLI ring object.
1935 * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
1936 * @fch_r_ctl: the r_ctl for the first frame of the sequence.
1937 * @fch_type: the type for the first frame of the sequence.
1938 *
1939 * This function is called with no lock held. This function uses the r_ctl and
1940 * type of the received sequence to find the correct callback function to call
1941 * to process the sequence.
1942 **/
1943static int
1944lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1945			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
1946			 uint32_t fch_type)
1947{
1948	int i;
1949
1950	/* unSolicited Responses */
1951	if (pring->prt[0].profile) {
1952		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
1953			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
1954									saveq);
1955		return 1;
1956	}
1957	/* We must search, based on rctl / type
1958	   for the right routine */
1959	for (i = 0; i < pring->num_mask; i++) {
1960		if ((pring->prt[i].rctl == fch_r_ctl) &&
1961		    (pring->prt[i].type == fch_type)) {
1962			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
1963				(pring->prt[i].lpfc_sli_rcv_unsol_event)
1964						(phba, pring, saveq);
1965			return 1;
1966		}
1967	}
1968	return 0;
1969}
1970
1971/**
1972 * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
1973 * @phba: Pointer to HBA context object.
1974 * @pring: Pointer to driver SLI ring object.
1975 * @saveq: Pointer to the unsolicited iocb.
1976 *
1977 * This function is called with no lock held by the ring event handler
1978 * when there is an unsolicited iocb posted to the response ring by the
1979 * firmware. This function gets the buffer associated with the iocbs
1980 * and calls the event handler for the ring. This function handles both
1981 * qring buffers and hbq buffers.
1982 * When the function returns 1 the caller can free the iocb object otherwise
1983 * upper layer functions will free the iocb objects.
1984 **/
1985static int
1986lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1987			    struct lpfc_iocbq *saveq)
1988{
1989	IOCB_t           * irsp;
1990	WORD5            * w5p;
1991	uint32_t           Rctl, Type;
1992	uint32_t           match;
1993	struct lpfc_iocbq *iocbq;
1994	struct lpfc_dmabuf *dmzbuf;
1995
1996	match = 0;
1997	irsp = &(saveq->iocb);
1998
1999	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
2000		if (pring->lpfc_sli_rcv_async_status)
2001			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
2002		else
2003			lpfc_printf_log(phba,
2004					KERN_WARNING,
2005					LOG_SLI,
2006					"0316 Ring %d handler: unexpected "
2007					"ASYNC_STATUS iocb received evt_code "
2008					"0x%x\n",
2009					pring->ringno,
2010					irsp->un.asyncstat.evt_code);
2011		return 1;
2012	}
2013
2014	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
2015		(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
2016		if (irsp->ulpBdeCount > 0) {
2017			dmzbuf = lpfc_sli_get_buff(phba, pring,
2018					irsp->un.ulpWord[3]);
2019			lpfc_in_buf_free(phba, dmzbuf);
2020		}
2021
2022		if (irsp->ulpBdeCount > 1) {
2023			dmzbuf = lpfc_sli_get_buff(phba, pring,
2024					irsp->unsli3.sli3Words[3]);
2025			lpfc_in_buf_free(phba, dmzbuf);
2026		}
2027
2028		if (irsp->ulpBdeCount > 2) {
2029			dmzbuf = lpfc_sli_get_buff(phba, pring,
2030				irsp->unsli3.sli3Words[7]);
2031			lpfc_in_buf_free(phba, dmzbuf);
2032		}
2033
2034		return 1;
2035	}
2036
2037	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
2038		if (irsp->ulpBdeCount != 0) {
2039			saveq->context2 = lpfc_sli_get_buff(phba, pring,
2040						irsp->un.ulpWord[3]);
2041			if (!saveq->context2)
2042				lpfc_printf_log(phba,
2043					KERN_ERR,
2044					LOG_SLI,
2045					"0341 Ring %d Cannot find buffer for "
2046					"an unsolicited iocb. tag 0x%x\n",
2047					pring->ringno,
2048					irsp->un.ulpWord[3]);
2049		}
2050		if (irsp->ulpBdeCount == 2) {
2051			saveq->context3 = lpfc_sli_get_buff(phba, pring,
2052						irsp->unsli3.sli3Words[7]);
2053			if (!saveq->context3)
2054				lpfc_printf_log(phba,
2055					KERN_ERR,
2056					LOG_SLI,
2057					"0342 Ring %d Cannot find buffer for an"
2058					" unsolicited iocb. tag 0x%x\n",
2059					pring->ringno,
2060					irsp->unsli3.sli3Words[7]);
2061		}
2062		list_for_each_entry(iocbq, &saveq->list, list) {
2063			irsp = &(iocbq->iocb);
2064			if (irsp->ulpBdeCount != 0) {
2065				iocbq->context2 = lpfc_sli_get_buff(phba, pring,
2066							irsp->un.ulpWord[3]);
2067				if (!iocbq->context2)
2068					lpfc_printf_log(phba,
2069						KERN_ERR,
2070						LOG_SLI,
2071						"0343 Ring %d Cannot find "
2072						"buffer for an unsolicited iocb"
2073						". tag 0x%x\n", pring->ringno,
2074						irsp->un.ulpWord[3]);
2075			}
2076			if (irsp->ulpBdeCount == 2) {
2077				iocbq->context3 = lpfc_sli_get_buff(phba, pring,
2078						irsp->unsli3.sli3Words[7]);
2079				if (!iocbq->context3)
2080					lpfc_printf_log(phba,
2081						KERN_ERR,
2082						LOG_SLI,
2083						"0344 Ring %d Cannot find "
2084						"buffer for an unsolicited "
2085						"iocb. tag 0x%x\n",
2086						pring->ringno,
2087						irsp->unsli3.sli3Words[7]);
2088			}
2089		}
2090	}
2091	if (irsp->ulpBdeCount != 0 &&
2092	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
2093	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
2094		int found = 0;
2095
2096		/* search continue save q for same XRI */
2097		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
2098			if (iocbq->iocb.ulpContext == saveq->iocb.ulpContext) {
2099				list_add_tail(&saveq->list, &iocbq->list);
2100				found = 1;
2101				break;
2102			}
2103		}
2104		if (!found)
2105			list_add_tail(&saveq->clist,
2106				      &pring->iocb_continue_saveq);
2107		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
2108			list_del_init(&iocbq->clist);
2109			saveq = iocbq;
2110			irsp = &(saveq->iocb);
2111		} else
2112			return 0;
2113	}
2114	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
2115	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
2116	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
2117		Rctl = FC_RCTL_ELS_REQ;
2118		Type = FC_TYPE_ELS;
2119	} else {
2120		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
2121		Rctl = w5p->hcsw.Rctl;
2122		Type = w5p->hcsw.Type;
2123
2124		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
2125			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
2126			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
2127			Rctl = FC_RCTL_ELS_REQ;
2128			Type = FC_TYPE_ELS;
2129			w5p->hcsw.Rctl = Rctl;
2130			w5p->hcsw.Type = Type;
2131		}
2132	}
2133
2134	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
2135		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2136				"0313 Ring %d handler: unexpected Rctl x%x "
2137				"Type x%x received\n",
2138				pring->ringno, Rctl, Type);
2139
2140	return 1;
2141}
2142
2143/**
2144 * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
2145 * @phba: Pointer to HBA context object.
2146 * @pring: Pointer to driver SLI ring object.
2147 * @prspiocb: Pointer to response iocb object.
2148 *
2149 * This function looks up the iocb_lookup table to get the command iocb
2150 * corresponding to the given response iocb using the iotag of the
2151 * response iocb. This function is called with the hbalock held.
2152 * This function returns the command iocb object if it finds the command
2153 * iocb else returns NULL.
2154 **/
2155static struct lpfc_iocbq *
2156lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
2157		      struct lpfc_sli_ring *pring,
2158		      struct lpfc_iocbq *prspiocb)
2159{
2160	struct lpfc_iocbq *cmd_iocb = NULL;
2161	uint16_t iotag;
2162
2163	iotag = prspiocb->iocb.ulpIoTag;
2164
2165	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
2166		cmd_iocb = phba->sli.iocbq_lookup[iotag];
2167		list_del_init(&cmd_iocb->list);
2168		if (cmd_iocb->iocb_flag & LPFC_IO_ON_Q) {
2169			pring->txcmplq_cnt--;
2170			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_Q;
2171		}
2172		return cmd_iocb;
2173	}
2174
2175	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2176			"0317 iotag x%x is out off "
2177			"range: max iotag x%x wd0 x%x\n",
2178			iotag, phba->sli.last_iotag,
2179			*(((uint32_t *) &prspiocb->iocb) + 7));
2180	return NULL;
2181}
2182
2183/**
2184 * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
2185 * @phba: Pointer to HBA context object.
2186 * @pring: Pointer to driver SLI ring object.
2187 * @iotag: IOCB tag.
2188 *
2189 * This function looks up the iocb_lookup table to get the command iocb
2190 * corresponding to the given iotag. This function is called with the
2191 * hbalock held.
2192 * This function returns the command iocb object if it finds the command
2193 * iocb else returns NULL.
2194 **/
2195static struct lpfc_iocbq *
2196lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
2197			     struct lpfc_sli_ring *pring, uint16_t iotag)
2198{
2199	struct lpfc_iocbq *cmd_iocb;
2200
2201	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
2202		cmd_iocb = phba->sli.iocbq_lookup[iotag];
2203		list_del_init(&cmd_iocb->list);
2204		if (cmd_iocb->iocb_flag & LPFC_IO_ON_Q) {
2205			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_Q;
2206			pring->txcmplq_cnt--;
2207		}
2208		return cmd_iocb;
2209	}
2210
2211	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2212			"0372 iotag x%x is out off range: max iotag (x%x)\n",
2213			iotag, phba->sli.last_iotag);
2214	return NULL;
2215}
2216
2217/**
2218 * lpfc_sli_process_sol_iocb - process solicited iocb completion
2219 * @phba: Pointer to HBA context object.
2220 * @pring: Pointer to driver SLI ring object.
2221 * @saveq: Pointer to the response iocb to be processed.
2222 *
2223 * This function is called by the ring event handler for non-fcp
2224 * rings when there is a new response iocb in the response ring.
2225 * The caller is not required to hold any locks. This function
2226 * gets the command iocb associated with the response iocb and
2227 * calls the completion handler for the command iocb. If there
2228 * is no completion handler, the function will free the resources
2229 * associated with command iocb. If the response iocb is for
2230 * an already aborted command iocb, the status of the completion
2231 * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
2232 * This function always returns 1.
2233 **/
2234static int
2235lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2236			  struct lpfc_iocbq *saveq)
2237{
2238	struct lpfc_iocbq *cmdiocbp;
2239	int rc = 1;
2240	unsigned long iflag;
2241
2242	/* Based on the iotag field, get the cmd IOCB from the txcmplq */
2243	spin_lock_irqsave(&phba->hbalock, iflag);
2244	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
2245	spin_unlock_irqrestore(&phba->hbalock, iflag);
2246
2247	if (cmdiocbp) {
2248		if (cmdiocbp->iocb_cmpl) {
2249			/*
2250			 * If an ELS command failed send an event to mgmt
2251			 * application.
2252			 */
2253			if (saveq->iocb.ulpStatus &&
2254			     (pring->ringno == LPFC_ELS_RING) &&
2255			     (cmdiocbp->iocb.ulpCommand ==
2256				CMD_ELS_REQUEST64_CR))
2257				lpfc_send_els_failure_event(phba,
2258					cmdiocbp, saveq);
2259
2260			/*
2261			 * Post all ELS completions to the worker thread.
2262			 * All other are passed to the completion callback.
2263			 */
2264			if (pring->ringno == LPFC_ELS_RING) {
2265				if ((phba->sli_rev < LPFC_SLI_REV4) &&
2266				    (cmdiocbp->iocb_flag &
2267							LPFC_DRIVER_ABORTED)) {
2268					spin_lock_irqsave(&phba->hbalock,
2269							  iflag);
2270					cmdiocbp->iocb_flag &=
2271						~LPFC_DRIVER_ABORTED;
2272					spin_unlock_irqrestore(&phba->hbalock,
2273							       iflag);
2274					saveq->iocb.ulpStatus =
2275						IOSTAT_LOCAL_REJECT;
2276					saveq->iocb.un.ulpWord[4] =
2277						IOERR_SLI_ABORTED;
2278
2279					/* Firmware could still be in progress
2280					 * of DMAing payload, so don't free data
2281					 * buffer till after a hbeat.
2282					 */
2283					spin_lock_irqsave(&phba->hbalock,
2284							  iflag);
2285					saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
2286					spin_unlock_irqrestore(&phba->hbalock,
2287							       iflag);
2288				}
2289				if (phba->sli_rev == LPFC_SLI_REV4) {
2290					if (saveq->iocb_flag &
2291					    LPFC_EXCHANGE_BUSY) {
2292						/* Set cmdiocb flag for the
2293						 * exchange busy so sgl (xri)
2294						 * will not be released until
2295						 * the abort xri is received
2296						 * from hba.
2297						 */
2298						spin_lock_irqsave(
2299							&phba->hbalock, iflag);
2300						cmdiocbp->iocb_flag |=
2301							LPFC_EXCHANGE_BUSY;
2302						spin_unlock_irqrestore(
2303							&phba->hbalock, iflag);
2304					}
2305					if (cmdiocbp->iocb_flag &
2306					    LPFC_DRIVER_ABORTED) {
2307						/*
2308						 * Clear LPFC_DRIVER_ABORTED
2309						 * bit in case it was driver
2310						 * initiated abort.
2311						 */
2312						spin_lock_irqsave(
2313							&phba->hbalock, iflag);
2314						cmdiocbp->iocb_flag &=
2315							~LPFC_DRIVER_ABORTED;
2316						spin_unlock_irqrestore(
2317							&phba->hbalock, iflag);
2318						cmdiocbp->iocb.ulpStatus =
2319							IOSTAT_LOCAL_REJECT;
2320						cmdiocbp->iocb.un.ulpWord[4] =
2321							IOERR_ABORT_REQUESTED;
2322						/*
2323						 * For SLI4, irsiocb contains
2324						 * NO_XRI in sli_xritag, it
2325						 * shall not affect releasing
2326						 * sgl (xri) process.
2327						 */
2328						saveq->iocb.ulpStatus =
2329							IOSTAT_LOCAL_REJECT;
2330						saveq->iocb.un.ulpWord[4] =
2331							IOERR_SLI_ABORTED;
2332						spin_lock_irqsave(
2333							&phba->hbalock, iflag);
2334						saveq->iocb_flag |=
2335							LPFC_DELAY_MEM_FREE;
2336						spin_unlock_irqrestore(
2337							&phba->hbalock, iflag);
2338					}
2339				}
2340			}
2341			(cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
2342		} else
2343			lpfc_sli_release_iocbq(phba, cmdiocbp);
2344	} else {
2345		/*
2346		 * Unknown initiating command based on the response iotag.
2347		 * This could be the case on the ELS ring because of
2348		 * lpfc_els_abort().
2349		 */
2350		if (pring->ringno != LPFC_ELS_RING) {
2351			/*
2352			 * Ring <ringno> handler: unexpected completion IoTag
2353			 * <IoTag>
2354			 */
2355			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2356					 "0322 Ring %d handler: "
2357					 "unexpected completion IoTag x%x "
2358					 "Data: x%x x%x x%x x%x\n",
2359					 pring->ringno,
2360					 saveq->iocb.ulpIoTag,
2361					 saveq->iocb.ulpStatus,
2362					 saveq->iocb.un.ulpWord[4],
2363					 saveq->iocb.ulpCommand,
2364					 saveq->iocb.ulpContext);
2365		}
2366	}
2367
2368	return rc;
2369}
2370
2371/**
2372 * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
2373 * @phba: Pointer to HBA context object.
2374 * @pring: Pointer to driver SLI ring object.
2375 *
2376 * This function is called from the iocb ring event handlers when
2377 * put pointer is ahead of the get pointer for a ring. This function signal
2378 * an error attention condition to the worker thread and the worker
2379 * thread will transition the HBA to offline state.
2380 **/
2381static void
2382lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2383{
2384	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2385	/*
2386	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
2387	 * rsp ring <portRspMax>
2388	 */
2389	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2390			"0312 Ring %d handler: portRspPut %d "
2391			"is bigger than rsp ring %d\n",
2392			pring->ringno, le32_to_cpu(pgp->rspPutInx),
2393			pring->numRiocb);
2394
2395	phba->link_state = LPFC_HBA_ERROR;
2396
2397	/*
2398	 * All error attention handlers are posted to
2399	 * worker thread
2400	 */
2401	phba->work_ha |= HA_ERATT;
2402	phba->work_hs = HS_FFER3;
2403
2404	lpfc_worker_wake_up(phba);
2405
2406	return;
2407}
2408
2409/**
2410 * lpfc_poll_eratt - Error attention polling timer timeout handler
2411 * @ptr: Pointer to address of HBA context object.
2412 *
2413 * This function is invoked by the Error Attention polling timer when the
2414 * timer times out. It will check the SLI Error Attention register for
2415 * possible attention events. If so, it will post an Error Attention event
2416 * and wake up worker thread to process it. Otherwise, it will set up the
2417 * Error Attention polling timer for the next poll.
2418 **/
2419void lpfc_poll_eratt(unsigned long ptr)
2420{
2421	struct lpfc_hba *phba;
2422	uint32_t eratt = 0;
2423
2424	phba = (struct lpfc_hba *)ptr;
2425
2426	/* Check chip HA register for error event */
2427	eratt = lpfc_sli_check_eratt(phba);
2428
2429	if (eratt)
2430		/* Tell the worker thread there is work to do */
2431		lpfc_worker_wake_up(phba);
2432	else
2433		/* Restart the timer for next eratt poll */
2434		mod_timer(&phba->eratt_poll, jiffies +
2435					HZ * LPFC_ERATT_POLL_INTERVAL);
2436	return;
2437}
2438
2439
2440/**
2441 * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
2442 * @phba: Pointer to HBA context object.
2443 * @pring: Pointer to driver SLI ring object.
2444 * @mask: Host attention register mask for this ring.
2445 *
2446 * This function is called from the interrupt context when there is a ring
2447 * event for the fcp ring. The caller does not hold any lock.
2448 * The function processes each response iocb in the response ring until it
2449 * finds an iocb with LE bit set and chains all the iocbs upto the iocb with
2450 * LE bit set. The function will call the completion handler of the command iocb
2451 * if the response iocb indicates a completion for a command iocb or it is
2452 * an abort completion. The function will call lpfc_sli_process_unsol_iocb
2453 * function if this is an unsolicited iocb.
2454 * This routine presumes LPFC_FCP_RING handling and doesn't bother
2455 * to check it explicitly.
2456 */
2457int
2458lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
2459				struct lpfc_sli_ring *pring, uint32_t mask)
2460{
2461	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2462	IOCB_t *irsp = NULL;
2463	IOCB_t *entry = NULL;
2464	struct lpfc_iocbq *cmdiocbq = NULL;
2465	struct lpfc_iocbq rspiocbq;
2466	uint32_t status;
2467	uint32_t portRspPut, portRspMax;
2468	int rc = 1;
2469	lpfc_iocb_type type;
2470	unsigned long iflag;
2471	uint32_t rsp_cmpl = 0;
2472
2473	spin_lock_irqsave(&phba->hbalock, iflag);
2474	pring->stats.iocb_event++;
2475
2476	/*
2477	 * The next available response entry should never exceed the maximum
2478	 * entries.  If it does, treat it as an adapter hardware error.
2479	 */
2480	portRspMax = pring->numRiocb;
2481	portRspPut = le32_to_cpu(pgp->rspPutInx);
2482	if (unlikely(portRspPut >= portRspMax)) {
2483		lpfc_sli_rsp_pointers_error(phba, pring);
2484		spin_unlock_irqrestore(&phba->hbalock, iflag);
2485		return 1;
2486	}
2487	if (phba->fcp_ring_in_use) {
2488		spin_unlock_irqrestore(&phba->hbalock, iflag);
2489		return 1;
2490	} else
2491		phba->fcp_ring_in_use = 1;
2492
2493	rmb();
2494	while (pring->rspidx != portRspPut) {
2495		/*
2496		 * Fetch an entry off the ring and copy it into a local data
2497		 * structure.  The copy involves a byte-swap since the
2498		 * network byte order and pci byte orders are different.
2499		 */
2500		entry = lpfc_resp_iocb(phba, pring);
2501		phba->last_completion_time = jiffies;
2502
2503		if (++pring->rspidx >= portRspMax)
2504			pring->rspidx = 0;
2505
2506		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
2507				      (uint32_t *) &rspiocbq.iocb,
2508				      phba->iocb_rsp_size);
2509		INIT_LIST_HEAD(&(rspiocbq.list));
2510		irsp = &rspiocbq.iocb;
2511
2512		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
2513		pring->stats.iocb_rsp++;
2514		rsp_cmpl++;
2515
2516		if (unlikely(irsp->ulpStatus)) {
2517			/*
2518			 * If resource errors reported from HBA, reduce
2519			 * queuedepths of the SCSI device.
2520			 */
2521			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
2522				(irsp->un.ulpWord[4] == IOERR_NO_RESOURCES)) {
2523				spin_unlock_irqrestore(&phba->hbalock, iflag);
2524				phba->lpfc_rampdown_queue_depth(phba);
2525				spin_lock_irqsave(&phba->hbalock, iflag);
2526			}
2527
2528			/* Rsp ring <ringno> error: IOCB */
2529			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2530					"0336 Rsp Ring %d error: IOCB Data: "
2531					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
2532					pring->ringno,
2533					irsp->un.ulpWord[0],
2534					irsp->un.ulpWord[1],
2535					irsp->un.ulpWord[2],
2536					irsp->un.ulpWord[3],
2537					irsp->un.ulpWord[4],
2538					irsp->un.ulpWord[5],
2539					*(uint32_t *)&irsp->un1,
2540					*((uint32_t *)&irsp->un1 + 1));
2541		}
2542
2543		switch (type) {
2544		case LPFC_ABORT_IOCB:
2545		case LPFC_SOL_IOCB:
2546			/*
2547			 * Idle exchange closed via ABTS from port.  No iocb
2548			 * resources need to be recovered.
2549			 */
2550			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
2551				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
2552						"0333 IOCB cmd 0x%x"
2553						" processed. Skipping"
2554						" completion\n",
2555						irsp->ulpCommand);
2556				break;
2557			}
2558
2559			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
2560							 &rspiocbq);
2561			if (unlikely(!cmdiocbq))
2562				break;
2563			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
2564				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
2565			if (cmdiocbq->iocb_cmpl) {
2566				spin_unlock_irqrestore(&phba->hbalock, iflag);
2567				(cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
2568						      &rspiocbq);
2569				spin_lock_irqsave(&phba->hbalock, iflag);
2570			}
2571			break;
2572		case LPFC_UNSOL_IOCB:
2573			spin_unlock_irqrestore(&phba->hbalock, iflag);
2574			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
2575			spin_lock_irqsave(&phba->hbalock, iflag);
2576			break;
2577		default:
2578			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
2579				char adaptermsg[LPFC_MAX_ADPTMSG];
2580				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
2581				memcpy(&adaptermsg[0], (uint8_t *) irsp,
2582				       MAX_MSG_DATA);
2583				dev_warn(&((phba->pcidev)->dev),
2584					 "lpfc%d: %s\n",
2585					 phba->brd_no, adaptermsg);
2586			} else {
2587				/* Unknown IOCB command */
2588				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2589						"0334 Unknown IOCB command "
2590						"Data: x%x, x%x x%x x%x x%x\n",
2591						type, irsp->ulpCommand,
2592						irsp->ulpStatus,
2593						irsp->ulpIoTag,
2594						irsp->ulpContext);
2595			}
2596			break;
2597		}
2598
2599		/*
2600		 * The response IOCB has been processed.  Update the ring
2601		 * pointer in SLIM.  If the port response put pointer has not
2602		 * been updated, sync the pgp->rspPutInx and fetch the new port
2603		 * response put pointer.
2604		 */
2605		writel(pring->rspidx, &phba->host_gp[pring->ringno].rspGetInx);
2606
2607		if (pring->rspidx == portRspPut)
2608			portRspPut = le32_to_cpu(pgp->rspPutInx);
2609	}
2610
2611	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
2612		pring->stats.iocb_rsp_full++;
2613		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
2614		writel(status, phba->CAregaddr);
2615		readl(phba->CAregaddr);
2616	}
2617	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
2618		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
2619		pring->stats.iocb_cmd_empty++;
2620
2621		/* Force update of the local copy of cmdGetInx */
2622		pring->local_getidx = le32_to_cpu(pgp->cmdGetInx);
2623		lpfc_sli_resume_iocb(phba, pring);
2624
2625		if ((pring->lpfc_sli_cmd_available))
2626			(pring->lpfc_sli_cmd_available) (phba, pring);
2627
2628	}
2629
2630	phba->fcp_ring_in_use = 0;
2631	spin_unlock_irqrestore(&phba->hbalock, iflag);
2632	return rc;
2633}
2634
2635/**
2636 * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
2637 * @phba: Pointer to HBA context object.
2638 * @pring: Pointer to driver SLI ring object.
2639 * @rspiocbp: Pointer to driver response IOCB object.
2640 *
2641 * This function is called from the worker thread when there is a slow-path
2642 * response IOCB to process. This function chains all the response iocbs until
2643 * seeing the iocb with the LE bit set. The function will call
2644 * lpfc_sli_process_sol_iocb function if the response iocb indicates a
2645 * completion of a command iocb. The function will call the
2646 * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
2647 * The function frees the resources or calls the completion handler if this
2648 * iocb is an abort completion. The function returns NULL when the response
2649 * iocb has the LE bit set and all the chained iocbs are processed, otherwise
2650 * this function shall chain the iocb on to the iocb_continueq and return the
2651 * response iocb passed in.
2652 **/
2653static struct lpfc_iocbq *
2654lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2655			struct lpfc_iocbq *rspiocbp)
2656{
2657	struct lpfc_iocbq *saveq;
2658	struct lpfc_iocbq *cmdiocbp;
2659	struct lpfc_iocbq *next_iocb;
2660	IOCB_t *irsp = NULL;
2661	uint32_t free_saveq;
2662	uint8_t iocb_cmd_type;
2663	lpfc_iocb_type type;
2664	unsigned long iflag;
2665	int rc;
2666
2667	spin_lock_irqsave(&phba->hbalock, iflag);
2668	/* First add the response iocb to the countinueq list */
2669	list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
2670	pring->iocb_continueq_cnt++;
2671
2672	/* Now, determine whetehr the list is completed for processing */
2673	irsp = &rspiocbp->iocb;
2674	if (irsp->ulpLe) {
2675		/*
2676		 * By default, the driver expects to free all resources
2677		 * associated with this iocb completion.
2678		 */
2679		free_saveq = 1;
2680		saveq = list_get_first(&pring->iocb_continueq,
2681				       struct lpfc_iocbq, list);
2682		irsp = &(saveq->iocb);
2683		list_del_init(&pring->iocb_continueq);
2684		pring->iocb_continueq_cnt = 0;
2685
2686		pring->stats.iocb_rsp++;
2687
2688		/*
2689		 * If resource errors reported from HBA, reduce
2690		 * queuedepths of the SCSI device.
2691		 */
2692		if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
2693		    (irsp->un.ulpWord[4] == IOERR_NO_RESOURCES)) {
2694			spin_unlock_irqrestore(&phba->hbalock, iflag);
2695			phba->lpfc_rampdown_queue_depth(phba);
2696			spin_lock_irqsave(&phba->hbalock, iflag);
2697		}
2698
2699		if (irsp->ulpStatus) {
2700			/* Rsp ring <ringno> error: IOCB */
2701			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2702					"0328 Rsp Ring %d error: "
2703					"IOCB Data: "
2704					"x%x x%x x%x x%x "
2705					"x%x x%x x%x x%x "
2706					"x%x x%x x%x x%x "
2707					"x%x x%x x%x x%x\n",
2708					pring->ringno,
2709					irsp->un.ulpWord[0],
2710					irsp->un.ulpWord[1],
2711					irsp->un.ulpWord[2],
2712					irsp->un.ulpWord[3],
2713					irsp->un.ulpWord[4],
2714					irsp->un.ulpWord[5],
2715					*(((uint32_t *) irsp) + 6),
2716					*(((uint32_t *) irsp) + 7),
2717					*(((uint32_t *) irsp) + 8),
2718					*(((uint32_t *) irsp) + 9),
2719					*(((uint32_t *) irsp) + 10),
2720					*(((uint32_t *) irsp) + 11),
2721					*(((uint32_t *) irsp) + 12),
2722					*(((uint32_t *) irsp) + 13),
2723					*(((uint32_t *) irsp) + 14),
2724					*(((uint32_t *) irsp) + 15));
2725		}
2726
2727		/*
2728		 * Fetch the IOCB command type and call the correct completion
2729		 * routine. Solicited and Unsolicited IOCBs on the ELS ring
2730		 * get freed back to the lpfc_iocb_list by the discovery
2731		 * kernel thread.
2732		 */
2733		iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
2734		type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
2735		switch (type) {
2736		case LPFC_SOL_IOCB:
2737			spin_unlock_irqrestore(&phba->hbalock, iflag);
2738			rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
2739			spin_lock_irqsave(&phba->hbalock, iflag);
2740			break;
2741
2742		case LPFC_UNSOL_IOCB:
2743			spin_unlock_irqrestore(&phba->hbalock, iflag);
2744			rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
2745			spin_lock_irqsave(&phba->hbalock, iflag);
2746			if (!rc)
2747				free_saveq = 0;
2748			break;
2749
2750		case LPFC_ABORT_IOCB:
2751			cmdiocbp = NULL;
2752			if (irsp->ulpCommand != CMD_XRI_ABORTED_CX)
2753				cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
2754								 saveq);
2755			if (cmdiocbp) {
2756				/* Call the specified completion routine */
2757				if (cmdiocbp->iocb_cmpl) {
2758					spin_unlock_irqrestore(&phba->hbalock,
2759							       iflag);
2760					(cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
2761							      saveq);
2762					spin_lock_irqsave(&phba->hbalock,
2763							  iflag);
2764				} else
2765					__lpfc_sli_release_iocbq(phba,
2766								 cmdiocbp);
2767			}
2768			break;
2769
2770		case LPFC_UNKNOWN_IOCB:
2771			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
2772				char adaptermsg[LPFC_MAX_ADPTMSG];
2773				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
2774				memcpy(&adaptermsg[0], (uint8_t *)irsp,
2775				       MAX_MSG_DATA);
2776				dev_warn(&((phba->pcidev)->dev),
2777					 "lpfc%d: %s\n",
2778					 phba->brd_no, adaptermsg);
2779			} else {
2780				/* Unknown IOCB command */
2781				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2782						"0335 Unknown IOCB "
2783						"command Data: x%x "
2784						"x%x x%x x%x\n",
2785						irsp->ulpCommand,
2786						irsp->ulpStatus,
2787						irsp->ulpIoTag,
2788						irsp->ulpContext);
2789			}
2790			break;
2791		}
2792
2793		if (free_saveq) {
2794			list_for_each_entry_safe(rspiocbp, next_iocb,
2795						 &saveq->list, list) {
2796				list_del(&rspiocbp->list);
2797				__lpfc_sli_release_iocbq(phba, rspiocbp);
2798			}
2799			__lpfc_sli_release_iocbq(phba, saveq);
2800		}
2801		rspiocbp = NULL;
2802	}
2803	spin_unlock_irqrestore(&phba->hbalock, iflag);
2804	return rspiocbp;
2805}
2806
2807/**
2808 * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
2809 * @phba: Pointer to HBA context object.
2810 * @pring: Pointer to driver SLI ring object.
2811 * @mask: Host attention register mask for this ring.
2812 *
2813 * This routine wraps the actual slow_ring event process routine from the
2814 * API jump table function pointer from the lpfc_hba struct.
2815 **/
2816void
2817lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
2818				struct lpfc_sli_ring *pring, uint32_t mask)
2819{
2820	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
2821}
2822
2823/**
2824 * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
2825 * @phba: Pointer to HBA context object.
2826 * @pring: Pointer to driver SLI ring object.
2827 * @mask: Host attention register mask for this ring.
2828 *
2829 * This function is called from the worker thread when there is a ring event
2830 * for non-fcp rings. The caller does not hold any lock. The function will
2831 * remove each response iocb in the response ring and calls the handle
2832 * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
2833 **/
2834static void
2835lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
2836				   struct lpfc_sli_ring *pring, uint32_t mask)
2837{
2838	struct lpfc_pgp *pgp;
2839	IOCB_t *entry;
2840	IOCB_t *irsp = NULL;
2841	struct lpfc_iocbq *rspiocbp = NULL;
2842	uint32_t portRspPut, portRspMax;
2843	unsigned long iflag;
2844	uint32_t status;
2845
2846	pgp = &phba->port_gp[pring->ringno];
2847	spin_lock_irqsave(&phba->hbalock, iflag);
2848	pring->stats.iocb_event++;
2849
2850	/*
2851	 * The next available response entry should never exceed the maximum
2852	 * entries.  If it does, treat it as an adapter hardware error.
2853	 */
2854	portRspMax = pring->numRiocb;
2855	portRspPut = le32_to_cpu(pgp->rspPutInx);
2856	if (portRspPut >= portRspMax) {
2857		/*
2858		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
2859		 * rsp ring <portRspMax>
2860		 */
2861		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
2862				"0303 Ring %d handler: portRspPut %d "
2863				"is bigger than rsp ring %d\n",
2864				pring->ringno, portRspPut, portRspMax);
2865
2866		phba->link_state = LPFC_HBA_ERROR;
2867		spin_unlock_irqrestore(&phba->hbalock, iflag);
2868
2869		phba->work_hs = HS_FFER3;
2870		lpfc_handle_eratt(phba);
2871
2872		return;
2873	}
2874
2875	rmb();
2876	while (pring->rspidx != portRspPut) {
2877		/*
2878		 * Build a completion list and call the appropriate handler.
2879		 * The process is to get the next available response iocb, get
2880		 * a free iocb from the list, copy the response data into the
2881		 * free iocb, insert to the continuation list, and update the
2882		 * next response index to slim.  This process makes response
2883		 * iocb's in the ring available to DMA as fast as possible but
2884		 * pays a penalty for a copy operation.  Since the iocb is
2885		 * only 32 bytes, this penalty is considered small relative to
2886		 * the PCI reads for register values and a slim write.  When
2887		 * the ulpLe field is set, the entire Command has been
2888		 * received.
2889		 */
2890		entry = lpfc_resp_iocb(phba, pring);
2891
2892		phba->last_completion_time = jiffies;
2893		rspiocbp = __lpfc_sli_get_iocbq(phba);
2894		if (rspiocbp == NULL) {
2895			printk(KERN_ERR "%s: out of buffers! Failing "
2896			       "completion.\n", __func__);
2897			break;
2898		}
2899
2900		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
2901				      phba->iocb_rsp_size);
2902		irsp = &rspiocbp->iocb;
2903
2904		if (++pring->rspidx >= portRspMax)
2905			pring->rspidx = 0;
2906
2907		if (pring->ringno == LPFC_ELS_RING) {
2908			lpfc_debugfs_slow_ring_trc(phba,
2909			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
2910				*(((uint32_t *) irsp) + 4),
2911				*(((uint32_t *) irsp) + 6),
2912				*(((uint32_t *) irsp) + 7));
2913		}
2914
2915		writel(pring->rspidx, &phba->host_gp[pring->ringno].rspGetInx);
2916
2917		spin_unlock_irqrestore(&phba->hbalock, iflag);
2918		/* Handle the response IOCB */
2919		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
2920		spin_lock_irqsave(&phba->hbalock, iflag);
2921
2922		/*
2923		 * If the port response put pointer has not been updated, sync
2924		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
2925		 * response put pointer.
2926		 */
2927		if (pring->rspidx == portRspPut) {
2928			portRspPut = le32_to_cpu(pgp->rspPutInx);
2929		}
2930	} /* while (pring->rspidx != portRspPut) */
2931
2932	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
2933		/* At least one response entry has been freed */
2934		pring->stats.iocb_rsp_full++;
2935		/* SET RxRE_RSP in Chip Att register */
2936		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
2937		writel(status, phba->CAregaddr);
2938		readl(phba->CAregaddr); /* flush */
2939	}
2940	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
2941		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
2942		pring->stats.iocb_cmd_empty++;
2943
2944		/* Force update of the local copy of cmdGetInx */
2945		pring->local_getidx = le32_to_cpu(pgp->cmdGetInx);
2946		lpfc_sli_resume_iocb(phba, pring);
2947
2948		if ((pring->lpfc_sli_cmd_available))
2949			(pring->lpfc_sli_cmd_available) (phba, pring);
2950
2951	}
2952
2953	spin_unlock_irqrestore(&phba->hbalock, iflag);
2954	return;
2955}
2956
2957/**
2958 * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
2959 * @phba: Pointer to HBA context object.
2960 * @pring: Pointer to driver SLI ring object.
2961 * @mask: Host attention register mask for this ring.
2962 *
2963 * This function is called from the worker thread when there is a pending
2964 * ELS response iocb on the driver internal slow-path response iocb worker
2965 * queue. The caller does not hold any lock. The function will remove each
2966 * response iocb from the response worker queue and calls the handle
2967 * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
2968 **/
2969static void
2970lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
2971				   struct lpfc_sli_ring *pring, uint32_t mask)
2972{
2973	struct lpfc_iocbq *irspiocbq;
2974	struct hbq_dmabuf *dmabuf;
2975	struct lpfc_cq_event *cq_event;
2976	unsigned long iflag;
2977
2978	spin_lock_irqsave(&phba->hbalock, iflag);
2979	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
2980	spin_unlock_irqrestore(&phba->hbalock, iflag);
2981	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
2982		/* Get the response iocb from the head of work queue */
2983		spin_lock_irqsave(&phba->hbalock, iflag);
2984		list_remove_head(&phba->sli4_hba.sp_queue_event,
2985				 cq_event, struct lpfc_cq_event, list);
2986		spin_unlock_irqrestore(&phba->hbalock, iflag);
2987
2988		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
2989		case CQE_CODE_COMPL_WQE:
2990			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
2991						 cq_event);
2992			/* Translate ELS WCQE to response IOCBQ */
2993			irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
2994								   irspiocbq);
2995			if (irspiocbq)
2996				lpfc_sli_sp_handle_rspiocb(phba, pring,
2997							   irspiocbq);
2998			break;
2999		case CQE_CODE_RECEIVE:
3000			dmabuf = container_of(cq_event, struct hbq_dmabuf,
3001					      cq_event);
3002			lpfc_sli4_handle_received_buffer(phba, dmabuf);
3003			break;
3004		default:
3005			break;
3006		}
3007	}
3008}
3009
3010/**
3011 * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
3012 * @phba: Pointer to HBA context object.
3013 * @pring: Pointer to driver SLI ring object.
3014 *
3015 * This function aborts all iocbs in the given ring and frees all the iocb
3016 * objects in txq. This function issues an abort iocb for all the iocb commands
3017 * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3018 * the return of this function. The caller is not required to hold any locks.
3019 **/
3020void
3021lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3022{
3023	LIST_HEAD(completions);
3024	struct lpfc_iocbq *iocb, *next_iocb;
3025
3026	if (pring->ringno == LPFC_ELS_RING) {
3027		lpfc_fabric_abort_hba(phba);
3028	}
3029
3030	/* Error everything on txq and txcmplq
3031	 * First do the txq.
3032	 */
3033	spin_lock_irq(&phba->hbalock);
3034	list_splice_init(&pring->txq, &completions);
3035	pring->txq_cnt = 0;
3036
3037	/* Next issue ABTS for everything on the txcmplq */
3038	list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3039		lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3040
3041	spin_unlock_irq(&phba->hbalock);
3042
3043	/* Cancel all the IOCBs from the completions list */
3044	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
3045			      IOERR_SLI_ABORTED);
3046}
3047
3048/**
3049 * lpfc_sli_flush_fcp_rings - flush all iocbs in the fcp ring
3050 * @phba: Pointer to HBA context object.
3051 *
3052 * This function flushes all iocbs in the fcp ring and frees all the iocb
3053 * objects in txq and txcmplq. This function will not issue abort iocbs
3054 * for all the iocb commands in txcmplq, they will just be returned with
3055 * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
3056 * slot has been permanently disabled.
3057 **/
3058void
3059lpfc_sli_flush_fcp_rings(struct lpfc_hba *phba)
3060{
3061	LIST_HEAD(txq);
3062	LIST_HEAD(txcmplq);
3063	struct lpfc_sli *psli = &phba->sli;
3064	struct lpfc_sli_ring  *pring;
3065
3066	/* Currently, only one fcp ring */
3067	pring = &psli->ring[psli->fcp_ring];
3068
3069	spin_lock_irq(&phba->hbalock);
3070	/* Retrieve everything on txq */
3071	list_splice_init(&pring->txq, &txq);
3072	pring->txq_cnt = 0;
3073
3074	/* Retrieve everything on the txcmplq */
3075	list_splice_init(&pring->txcmplq, &txcmplq);
3076	pring->txcmplq_cnt = 0;
3077	spin_unlock_irq(&phba->hbalock);
3078
3079	/* Flush the txq */
3080	lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
3081			      IOERR_SLI_DOWN);
3082
3083	/* Flush the txcmpq */
3084	lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
3085			      IOERR_SLI_DOWN);
3086}
3087
3088/**
3089 * lpfc_sli_brdready_s3 - Check for sli3 host ready status
3090 * @phba: Pointer to HBA context object.
3091 * @mask: Bit mask to be checked.
3092 *
3093 * This function reads the host status register and compares
3094 * with the provided bit mask to check if HBA completed
3095 * the restart. This function will wait in a loop for the
3096 * HBA to complete restart. If the HBA does not restart within
3097 * 15 iterations, the function will reset the HBA again. The
3098 * function returns 1 when HBA fail to restart otherwise returns
3099 * zero.
3100 **/
3101static int
3102lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
3103{
3104	uint32_t status;
3105	int i = 0;
3106	int retval = 0;
3107
3108	/* Read the HBA Host Status Register */
3109	status = readl(phba->HSregaddr);
3110
3111	/*
3112	 * Check status register every 100ms for 5 retries, then every
3113	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
3114	 * every 2.5 sec for 4.
3115	 * Break our of the loop if errors occurred during init.
3116	 */
3117	while (((status & mask) != mask) &&
3118	       !(status & HS_FFERM) &&
3119	       i++ < 20) {
3120
3121		if (i <= 5)
3122			msleep(10);
3123		else if (i <= 10)
3124			msleep(500);
3125		else
3126			msleep(2500);
3127
3128		if (i == 15) {
3129				/* Do post */
3130			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
3131			lpfc_sli_brdrestart(phba);
3132		}
3133		/* Read the HBA Host Status Register */
3134		status = readl(phba->HSregaddr);
3135	}
3136
3137	/* Check to see if any errors occurred during init */
3138	if ((status & HS_FFERM) || (i >= 20)) {
3139		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3140				"2751 Adapter failed to restart, "
3141				"status reg x%x, FW Data: A8 x%x AC x%x\n",
3142				status,
3143				readl(phba->MBslimaddr + 0xa8),
3144				readl(phba->MBslimaddr + 0xac));
3145		phba->link_state = LPFC_HBA_ERROR;
3146		retval = 1;
3147	}
3148
3149	return retval;
3150}
3151
3152/**
3153 * lpfc_sli_brdready_s4 - Check for sli4 host ready status
3154 * @phba: Pointer to HBA context object.
3155 * @mask: Bit mask to be checked.
3156 *
3157 * This function checks the host status register to check if HBA is
3158 * ready. This function will wait in a loop for the HBA to be ready
3159 * If the HBA is not ready , the function will will reset the HBA PCI
3160 * function again. The function returns 1 when HBA fail to be ready
3161 * otherwise returns zero.
3162 **/
3163static int
3164lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
3165{
3166	uint32_t status;
3167	int retval = 0;
3168
3169	/* Read the HBA Host Status Register */
3170	status = lpfc_sli4_post_status_check(phba);
3171
3172	if (status) {
3173		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
3174		lpfc_sli_brdrestart(phba);
3175		status = lpfc_sli4_post_status_check(phba);
3176	}
3177
3178	/* Check to see if any errors occurred during init */
3179	if (status) {
3180		phba->link_state = LPFC_HBA_ERROR;
3181		retval = 1;
3182	} else
3183		phba->sli4_hba.intr_enable = 0;
3184
3185	return retval;
3186}
3187
3188/**
3189 * lpfc_sli_brdready - Wrapper func for checking the hba readyness
3190 * @phba: Pointer to HBA context object.
3191 * @mask: Bit mask to be checked.
3192 *
3193 * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
3194 * from the API jump table function pointer from the lpfc_hba struct.
3195 **/
3196int
3197lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
3198{
3199	return phba->lpfc_sli_brdready(phba, mask);
3200}
3201
3202#define BARRIER_TEST_PATTERN (0xdeadbeef)
3203
3204/**
3205 * lpfc_reset_barrier - Make HBA ready for HBA reset
3206 * @phba: Pointer to HBA context object.
3207 *
3208 * This function is called before resetting an HBA. This
3209 * function requests HBA to quiesce DMAs before a reset.
3210 **/
3211void lpfc_reset_barrier(struct lpfc_hba *phba)
3212{
3213	uint32_t __iomem *resp_buf;
3214	uint32_t __iomem *mbox_buf;
3215	volatile uint32_t mbox;
3216	uint32_t hc_copy;
3217	int  i;
3218	uint8_t hdrtype;
3219
3220	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
3221	if (hdrtype != 0x80 ||
3222	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
3223	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
3224		return;
3225
3226	/*
3227	 * Tell the other part of the chip to suspend temporarily all
3228	 * its DMA activity.
3229	 */
3230	resp_buf = phba->MBslimaddr;
3231
3232	/* Disable the error attention */
3233	hc_copy = readl(phba->HCregaddr);
3234	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
3235	readl(phba->HCregaddr); /* flush */
3236	phba->link_flag |= LS_IGNORE_ERATT;
3237
3238	if (readl(phba->HAregaddr) & HA_ERATT) {
3239		/* Clear Chip error bit */
3240		writel(HA_ERATT, phba->HAregaddr);
3241		phba->pport->stopped = 1;
3242	}
3243
3244	mbox = 0;
3245	((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
3246	((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
3247
3248	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
3249	mbox_buf = phba->MBslimaddr;
3250	writel(mbox, mbox_buf);
3251
3252	for (i = 0;
3253	     readl(resp_buf + 1) != ~(BARRIER_TEST_PATTERN) && i < 50; i++)
3254		mdelay(1);
3255
3256	if (readl(resp_buf + 1) != ~(BARRIER_TEST_PATTERN)) {
3257		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
3258		    phba->pport->stopped)
3259			goto restore_hc;
3260		else
3261			goto clear_errat;
3262	}
3263
3264	((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
3265	for (i = 0; readl(resp_buf) != mbox &&  i < 500; i++)
3266		mdelay(1);
3267
3268clear_errat:
3269
3270	while (!(readl(phba->HAregaddr) & HA_ERATT) && ++i < 500)
3271		mdelay(1);
3272
3273	if (readl(phba->HAregaddr) & HA_ERATT) {
3274		writel(HA_ERATT, phba->HAregaddr);
3275		phba->pport->stopped = 1;
3276	}
3277
3278restore_hc:
3279	phba->link_flag &= ~LS_IGNORE_ERATT;
3280	writel(hc_copy, phba->HCregaddr);
3281	readl(phba->HCregaddr); /* flush */
3282}
3283
3284/**
3285 * lpfc_sli_brdkill - Issue a kill_board mailbox command
3286 * @phba: Pointer to HBA context object.
3287 *
3288 * This function issues a kill_board mailbox command and waits for
3289 * the error attention interrupt. This function is called for stopping
3290 * the firmware processing. The caller is not required to hold any
3291 * locks. This function calls lpfc_hba_down_post function to free
3292 * any pending commands after the kill. The function will return 1 when it
3293 * fails to kill the board else will return 0.
3294 **/
3295int
3296lpfc_sli_brdkill(struct lpfc_hba *phba)
3297{
3298	struct lpfc_sli *psli;
3299	LPFC_MBOXQ_t *pmb;
3300	uint32_t status;
3301	uint32_t ha_copy;
3302	int retval;
3303	int i = 0;
3304
3305	psli = &phba->sli;
3306
3307	/* Kill HBA */
3308	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3309			"0329 Kill HBA Data: x%x x%x\n",
3310			phba->pport->port_state, psli->sli_flag);
3311
3312	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
3313	if (!pmb)
3314		return 1;
3315
3316	/* Disable the error attention */
3317	spin_lock_irq(&phba->hbalock);
3318	status = readl(phba->HCregaddr);
3319	status &= ~HC_ERINT_ENA;
3320	writel(status, phba->HCregaddr);
3321	readl(phba->HCregaddr); /* flush */
3322	phba->link_flag |= LS_IGNORE_ERATT;
3323	spin_unlock_irq(&phba->hbalock);
3324
3325	lpfc_kill_board(phba, pmb);
3326	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
3327	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3328
3329	if (retval != MBX_SUCCESS) {
3330		if (retval != MBX_BUSY)
3331			mempool_free(pmb, phba->mbox_mem_pool);
3332		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3333				"2752 KILL_BOARD command failed retval %d\n",
3334				retval);
3335		spin_lock_irq(&phba->hbalock);
3336		phba->link_flag &= ~LS_IGNORE_ERATT;
3337		spin_unlock_irq(&phba->hbalock);
3338		return 1;
3339	}
3340
3341	spin_lock_irq(&phba->hbalock);
3342	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
3343	spin_unlock_irq(&phba->hbalock);
3344
3345	mempool_free(pmb, phba->mbox_mem_pool);
3346
3347	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
3348	 * attention every 100ms for 3 seconds. If we don't get ERATT after
3349	 * 3 seconds we still set HBA_ERROR state because the status of the
3350	 * board is now undefined.
3351	 */
3352	ha_copy = readl(phba->HAregaddr);
3353
3354	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
3355		mdelay(100);
3356		ha_copy = readl(phba->HAregaddr);
3357	}
3358
3359	del_timer_sync(&psli->mbox_tmo);
3360	if (ha_copy & HA_ERATT) {
3361		writel(HA_ERATT, phba->HAregaddr);
3362		phba->pport->stopped = 1;
3363	}
3364	spin_lock_irq(&phba->hbalock);
3365	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
3366	psli->mbox_active = NULL;
3367	phba->link_flag &= ~LS_IGNORE_ERATT;
3368	spin_unlock_irq(&phba->hbalock);
3369
3370	lpfc_hba_down_post(phba);
3371	phba->link_state = LPFC_HBA_ERROR;
3372
3373	return ha_copy & HA_ERATT ? 0 : 1;
3374}
3375
3376/**
3377 * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
3378 * @phba: Pointer to HBA context object.
3379 *
3380 * This function resets the HBA by writing HC_INITFF to the control
3381 * register. After the HBA resets, this function resets all the iocb ring
3382 * indices. This function disables PCI layer parity checking during
3383 * the reset.
3384 * This function returns 0 always.
3385 * The caller is not required to hold any locks.
3386 **/
3387int
3388lpfc_sli_brdreset(struct lpfc_hba *phba)
3389{
3390	struct lpfc_sli *psli;
3391	struct lpfc_sli_ring *pring;
3392	uint16_t cfg_value;
3393	int i;
3394
3395	psli = &phba->sli;
3396
3397	/* Reset HBA */
3398	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3399			"0325 Reset HBA Data: x%x x%x\n",
3400			phba->pport->port_state, psli->sli_flag);
3401
3402	/* perform board reset */
3403	phba->fc_eventTag = 0;
3404	phba->link_events = 0;
3405	phba->pport->fc_myDID = 0;
3406	phba->pport->fc_prevDID = 0;
3407
3408	/* Turn off parity checking and serr during the physical reset */
3409	pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value);
3410	pci_write_config_word(phba->pcidev, PCI_COMMAND,
3411			      (cfg_value &
3412			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
3413
3414	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
3415
3416	/* Now toggle INITFF bit in the Host Control Register */
3417	writel(HC_INITFF, phba->HCregaddr);
3418	mdelay(1);
3419	readl(phba->HCregaddr); /* flush */
3420	writel(0, phba->HCregaddr);
3421	readl(phba->HCregaddr); /* flush */
3422
3423	/* Restore PCI cmd register */
3424	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
3425
3426	/* Initialize relevant SLI info */
3427	for (i = 0; i < psli->num_rings; i++) {
3428		pring = &psli->ring[i];
3429		pring->flag = 0;
3430		pring->rspidx = 0;
3431		pring->next_cmdidx  = 0;
3432		pring->local_getidx = 0;
3433		pring->cmdidx = 0;
3434		pring->missbufcnt = 0;
3435	}
3436
3437	phba->link_state = LPFC_WARM_START;
3438	return 0;
3439}
3440
3441/**
3442 * lpfc_sli4_brdreset - Reset a sli-4 HBA
3443 * @phba: Pointer to HBA context object.
3444 *
3445 * This function resets a SLI4 HBA. This function disables PCI layer parity
3446 * checking during resets the device. The caller is not required to hold
3447 * any locks.
3448 *
3449 * This function returns 0 always.
3450 **/
3451int
3452lpfc_sli4_brdreset(struct lpfc_hba *phba)
3453{
3454	struct lpfc_sli *psli = &phba->sli;
3455	uint16_t cfg_value;
3456	uint8_t qindx;
3457
3458	/* Reset HBA */
3459	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3460			"0295 Reset HBA Data: x%x x%x\n",
3461			phba->pport->port_state, psli->sli_flag);
3462
3463	/* perform board reset */
3464	phba->fc_eventTag = 0;
3465	phba->link_events = 0;
3466	phba->pport->fc_myDID = 0;
3467	phba->pport->fc_prevDID = 0;
3468
3469	/* Turn off parity checking and serr during the physical reset */
3470	pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value);
3471	pci_write_config_word(phba->pcidev, PCI_COMMAND,
3472			      (cfg_value &
3473			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
3474
3475	spin_lock_irq(&phba->hbalock);
3476	psli->sli_flag &= ~(LPFC_PROCESS_LA);
3477	phba->fcf.fcf_flag = 0;
3478	/* Clean up the child queue list for the CQs */
3479	list_del_init(&phba->sli4_hba.mbx_wq->list);
3480	list_del_init(&phba->sli4_hba.els_wq->list);
3481	list_del_init(&phba->sli4_hba.hdr_rq->list);
3482	list_del_init(&phba->sli4_hba.dat_rq->list);
3483	list_del_init(&phba->sli4_hba.mbx_cq->list);
3484	list_del_init(&phba->sli4_hba.els_cq->list);
3485	for (qindx = 0; qindx < phba->cfg_fcp_wq_count; qindx++)
3486		list_del_init(&phba->sli4_hba.fcp_wq[qindx]->list);
3487	for (qindx = 0; qindx < phba->cfg_fcp_eq_count; qindx++)
3488		list_del_init(&phba->sli4_hba.fcp_cq[qindx]->list);
3489	spin_unlock_irq(&phba->hbalock);
3490
3491	/* Now physically reset the device */
3492	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3493			"0389 Performing PCI function reset!\n");
3494	/* Perform FCoE PCI function reset */
3495	lpfc_pci_function_reset(phba);
3496
3497	return 0;
3498}
3499
3500/**
3501 * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
3502 * @phba: Pointer to HBA context object.
3503 *
3504 * This function is called in the SLI initialization code path to
3505 * restart the HBA. The caller is not required to hold any lock.
3506 * This function writes MBX_RESTART mailbox command to the SLIM and
3507 * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
3508 * function to free any pending commands. The function enables
3509 * POST only during the first initialization. The function returns zero.
3510 * The function does not guarantee completion of MBX_RESTART mailbox
3511 * command before the return of this function.
3512 **/
3513static int
3514lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
3515{
3516	MAILBOX_t *mb;
3517	struct lpfc_sli *psli;
3518	volatile uint32_t word0;
3519	void __iomem *to_slim;
3520	uint32_t hba_aer_enabled;
3521
3522	spin_lock_irq(&phba->hbalock);
3523
3524	/* Take PCIe device Advanced Error Reporting (AER) state */
3525	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
3526
3527	psli = &phba->sli;
3528
3529	/* Restart HBA */
3530	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3531			"0337 Restart HBA Data: x%x x%x\n",
3532			phba->pport->port_state, psli->sli_flag);
3533
3534	word0 = 0;
3535	mb = (MAILBOX_t *) &word0;
3536	mb->mbxCommand = MBX_RESTART;
3537	mb->mbxHc = 1;
3538
3539	lpfc_reset_barrier(phba);
3540
3541	to_slim = phba->MBslimaddr;
3542	writel(*(uint32_t *) mb, to_slim);
3543	readl(to_slim); /* flush */
3544
3545	/* Only skip post after fc_ffinit is completed */
3546	if (phba->pport->port_state)
3547		word0 = 1;	/* This is really setting up word1 */
3548	else
3549		word0 = 0;	/* This is really setting up word1 */
3550	to_slim = phba->MBslimaddr + sizeof (uint32_t);
3551	writel(*(uint32_t *) mb, to_slim);
3552	readl(to_slim); /* flush */
3553
3554	lpfc_sli_brdreset(phba);
3555	phba->pport->stopped = 0;
3556	phba->link_state = LPFC_INIT_START;
3557	phba->hba_flag = 0;
3558	spin_unlock_irq(&phba->hbalock);
3559
3560	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
3561	psli->stats_start = get_seconds();
3562
3563	/* Give the INITFF and Post time to settle. */
3564	mdelay(100);
3565
3566	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
3567	if (hba_aer_enabled)
3568		pci_disable_pcie_error_reporting(phba->pcidev);
3569
3570	lpfc_hba_down_post(phba);
3571
3572	return 0;
3573}
3574
3575/**
3576 * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
3577 * @phba: Pointer to HBA context object.
3578 *
3579 * This function is called in the SLI initialization code path to restart
3580 * a SLI4 HBA. The caller is not required to hold any lock.
3581 * At the end of the function, it calls lpfc_hba_down_post function to
3582 * free any pending commands.
3583 **/
3584static int
3585lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
3586{
3587	struct lpfc_sli *psli = &phba->sli;
3588	uint32_t hba_aer_enabled;
3589
3590	/* Restart HBA */
3591	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3592			"0296 Restart HBA Data: x%x x%x\n",
3593			phba->pport->port_state, psli->sli_flag);
3594
3595	/* Take PCIe device Advanced Error Reporting (AER) state */
3596	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
3597
3598	lpfc_sli4_brdreset(phba);
3599
3600	spin_lock_irq(&phba->hbalock);
3601	phba->pport->stopped = 0;
3602	phba->link_state = LPFC_INIT_START;
3603	phba->hba_flag = 0;
3604	spin_unlock_irq(&phba->hbalock);
3605
3606	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
3607	psli->stats_start = get_seconds();
3608
3609	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
3610	if (hba_aer_enabled)
3611		pci_disable_pcie_error_reporting(phba->pcidev);
3612
3613	lpfc_hba_down_post(phba);
3614
3615	return 0;
3616}
3617
3618/**
3619 * lpfc_sli_brdrestart - Wrapper func for restarting hba
3620 * @phba: Pointer to HBA context object.
3621 *
3622 * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
3623 * API jump table function pointer from the lpfc_hba struct.
3624**/
3625int
3626lpfc_sli_brdrestart(struct lpfc_hba *phba)
3627{
3628	return phba->lpfc_sli_brdrestart(phba);
3629}
3630
3631/**
3632 * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
3633 * @phba: Pointer to HBA context object.
3634 *
3635 * This function is called after a HBA restart to wait for successful
3636 * restart of the HBA. Successful restart of the HBA is indicated by
3637 * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
3638 * iteration, the function will restart the HBA again. The function returns
3639 * zero if HBA successfully restarted else returns negative error code.
3640 **/
3641static int
3642lpfc_sli_chipset_init(struct lpfc_hba *phba)
3643{
3644	uint32_t status, i = 0;
3645
3646	/* Read the HBA Host Status Register */
3647	status = readl(phba->HSregaddr);
3648
3649	/* Check status register to see what current state is */
3650	i = 0;
3651	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
3652
3653		/* Check every 100ms for 5 retries, then every 500ms for 5, then
3654		 * every 2.5 sec for 5, then reset board and every 2.5 sec for
3655		 * 4.
3656		 */
3657		if (i++ >= 20) {
3658			/* Adapter failed to init, timeout, status reg
3659			   <status> */
3660			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3661					"0436 Adapter failed to init, "
3662					"timeout, status reg x%x, "
3663					"FW Data: A8 x%x AC x%x\n", status,
3664					readl(phba->MBslimaddr + 0xa8),
3665					readl(phba->MBslimaddr + 0xac));
3666			phba->link_state = LPFC_HBA_ERROR;
3667			return -ETIMEDOUT;
3668		}
3669
3670		/* Check to see if any errors occurred during init */
3671		if (status & HS_FFERM) {
3672			/* ERROR: During chipset initialization */
3673			/* Adapter failed to init, chipset, status reg
3674			   <status> */
3675			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3676					"0437 Adapter failed to init, "
3677					"chipset, status reg x%x, "
3678					"FW Data: A8 x%x AC x%x\n", status,
3679					readl(phba->MBslimaddr + 0xa8),
3680					readl(phba->MBslimaddr + 0xac));
3681			phba->link_state = LPFC_HBA_ERROR;
3682			return -EIO;
3683		}
3684
3685		if (i <= 5) {
3686			msleep(10);
3687		} else if (i <= 10) {
3688			msleep(500);
3689		} else {
3690			msleep(2500);
3691		}
3692
3693		if (i == 15) {
3694				/* Do post */
3695			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
3696			lpfc_sli_brdrestart(phba);
3697		}
3698		/* Read the HBA Host Status Register */
3699		status = readl(phba->HSregaddr);
3700	}
3701
3702	/* Check to see if any errors occurred during init */
3703	if (status & HS_FFERM) {
3704		/* ERROR: During chipset initialization */
3705		/* Adapter failed to init, chipset, status reg <status> */
3706		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3707				"0438 Adapter failed to init, chipset, "
3708				"status reg x%x, "
3709				"FW Data: A8 x%x AC x%x\n", status,
3710				readl(phba->MBslimaddr + 0xa8),
3711				readl(phba->MBslimaddr + 0xac));
3712		phba->link_state = LPFC_HBA_ERROR;
3713		return -EIO;
3714	}
3715
3716	/* Clear all interrupt enable conditions */
3717	writel(0, phba->HCregaddr);
3718	readl(phba->HCregaddr); /* flush */
3719
3720	/* setup host attn register */
3721	writel(0xffffffff, phba->HAregaddr);
3722	readl(phba->HAregaddr); /* flush */
3723	return 0;
3724}
3725
3726/**
3727 * lpfc_sli_hbq_count - Get the number of HBQs to be configured
3728 *
3729 * This function calculates and returns the number of HBQs required to be
3730 * configured.
3731 **/
3732int
3733lpfc_sli_hbq_count(void)
3734{
3735	return ARRAY_SIZE(lpfc_hbq_defs);
3736}
3737
3738/**
3739 * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
3740 *
3741 * This function adds the number of hbq entries in every HBQ to get
3742 * the total number of hbq entries required for the HBA and returns
3743 * the total count.
3744 **/
3745static int
3746lpfc_sli_hbq_entry_count(void)
3747{
3748	int  hbq_count = lpfc_sli_hbq_count();
3749	int  count = 0;
3750	int  i;
3751
3752	for (i = 0; i < hbq_count; ++i)
3753		count += lpfc_hbq_defs[i]->entry_count;
3754	return count;
3755}
3756
3757/**
3758 * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
3759 *
3760 * This function calculates amount of memory required for all hbq entries
3761 * to be configured and returns the total memory required.
3762 **/
3763int
3764lpfc_sli_hbq_size(void)
3765{
3766	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
3767}
3768
3769/**
3770 * lpfc_sli_hbq_setup - configure and initialize HBQs
3771 * @phba: Pointer to HBA context object.
3772 *
3773 * This function is called during the SLI initialization to configure
3774 * all the HBQs and post buffers to the HBQ. The caller is not
3775 * required to hold any locks. This function will return zero if successful
3776 * else it will return negative error code.
3777 **/
3778static int
3779lpfc_sli_hbq_setup(struct lpfc_hba *phba)
3780{
3781	int  hbq_count = lpfc_sli_hbq_count();
3782	LPFC_MBOXQ_t *pmb;
3783	MAILBOX_t *pmbox;
3784	uint32_t hbqno;
3785	uint32_t hbq_entry_index;
3786
3787				/* Get a Mailbox buffer to setup mailbox
3788				 * commands for HBA initialization
3789				 */
3790	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
3791
3792	if (!pmb)
3793		return -ENOMEM;
3794
3795	pmbox = &pmb->u.mb;
3796
3797	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
3798	phba->link_state = LPFC_INIT_MBX_CMDS;
3799	phba->hbq_in_use = 1;
3800
3801	hbq_entry_index = 0;
3802	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
3803		phba->hbqs[hbqno].next_hbqPutIdx = 0;
3804		phba->hbqs[hbqno].hbqPutIdx      = 0;
3805		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
3806		phba->hbqs[hbqno].entry_count =
3807			lpfc_hbq_defs[hbqno]->entry_count;
3808		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
3809			hbq_entry_index, pmb);
3810		hbq_entry_index += phba->hbqs[hbqno].entry_count;
3811
3812		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
3813			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
3814			   mbxStatus <status>, ring <num> */
3815
3816			lpfc_printf_log(phba, KERN_ERR,
3817					LOG_SLI | LOG_VPORT,
3818					"1805 Adapter failed to init. "
3819					"Data: x%x x%x x%x\n",
3820					pmbox->mbxCommand,
3821					pmbox->mbxStatus, hbqno);
3822
3823			phba->link_state = LPFC_HBA_ERROR;
3824			mempool_free(pmb, phba->mbox_mem_pool);
3825			return -ENXIO;
3826		}
3827	}
3828	phba->hbq_count = hbq_count;
3829
3830	mempool_free(pmb, phba->mbox_mem_pool);
3831
3832	/* Initially populate or replenish the HBQs */
3833	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
3834		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
3835	return 0;
3836}
3837
3838/**
3839 * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
3840 * @phba: Pointer to HBA context object.
3841 *
3842 * This function is called during the SLI initialization to configure
3843 * all the HBQs and post buffers to the HBQ. The caller is not
3844 * required to hold any locks. This function will return zero if successful
3845 * else it will return negative error code.
3846 **/
3847static int
3848lpfc_sli4_rb_setup(struct lpfc_hba *phba)
3849{
3850	phba->hbq_in_use = 1;
3851	phba->hbqs[0].entry_count = lpfc_hbq_defs[0]->entry_count;
3852	phba->hbq_count = 1;
3853	/* Initially populate or replenish the HBQs */
3854	lpfc_sli_hbqbuf_init_hbqs(phba, 0);
3855	return 0;
3856}
3857
3858/**
3859 * lpfc_sli_config_port - Issue config port mailbox command
3860 * @phba: Pointer to HBA context object.
3861 * @sli_mode: sli mode - 2/3
3862 *
3863 * This function is called by the sli intialization code path
3864 * to issue config_port mailbox command. This function restarts the
3865 * HBA firmware and issues a config_port mailbox command to configure
3866 * the SLI interface in the sli mode specified by sli_mode
3867 * variable. The caller is not required to hold any locks.
3868 * The function returns 0 if successful, else returns negative error
3869 * code.
3870 **/
3871int
3872lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
3873{
3874	LPFC_MBOXQ_t *pmb;
3875	uint32_t resetcount = 0, rc = 0, done = 0;
3876
3877	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
3878	if (!pmb) {
3879		phba->link_state = LPFC_HBA_ERROR;
3880		return -ENOMEM;
3881	}
3882
3883	phba->sli_rev = sli_mode;
3884	while (resetcount < 2 && !done) {
3885		spin_lock_irq(&phba->hbalock);
3886		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
3887		spin_unlock_irq(&phba->hbalock);
3888		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
3889		lpfc_sli_brdrestart(phba);
3890		rc = lpfc_sli_chipset_init(phba);
3891		if (rc)
3892			break;
3893
3894		spin_lock_irq(&phba->hbalock);
3895		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
3896		spin_unlock_irq(&phba->hbalock);
3897		resetcount++;
3898
3899		/* Call pre CONFIG_PORT mailbox command initialization.  A
3900		 * value of 0 means the call was successful.  Any other
3901		 * nonzero value is a failure, but if ERESTART is returned,
3902		 * the driver may reset the HBA and try again.
3903		 */
3904		rc = lpfc_config_port_prep(phba);
3905		if (rc == -ERESTART) {
3906			phba->link_state = LPFC_LINK_UNKNOWN;
3907			continue;
3908		} else if (rc)
3909			break;
3910		phba->link_state = LPFC_INIT_MBX_CMDS;
3911		lpfc_config_port(phba, pmb);
3912		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
3913		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
3914					LPFC_SLI3_HBQ_ENABLED |
3915					LPFC_SLI3_CRP_ENABLED |
3916					LPFC_SLI3_BG_ENABLED |
3917					LPFC_SLI3_DSS_ENABLED);
3918		if (rc != MBX_SUCCESS) {
3919			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3920				"0442 Adapter failed to init, mbxCmd x%x "
3921				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
3922				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
3923			spin_lock_irq(&phba->hbalock);
3924			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
3925			spin_unlock_irq(&phba->hbalock);
3926			rc = -ENXIO;
3927		} else {
3928			/* Allow asynchronous mailbox command to go through */
3929			spin_lock_irq(&phba->hbalock);
3930			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
3931			spin_unlock_irq(&phba->hbalock);
3932			done = 1;
3933		}
3934	}
3935	if (!done) {
3936		rc = -EINVAL;
3937		goto do_prep_failed;
3938	}
3939	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
3940		if (!pmb->u.mb.un.varCfgPort.cMA) {
3941			rc = -ENXIO;
3942			goto do_prep_failed;
3943		}
3944		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
3945			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
3946			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
3947			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
3948				phba->max_vpi : phba->max_vports;
3949
3950		} else
3951			phba->max_vpi = 0;
3952		phba->fips_level = 0;
3953		phba->fips_spec_rev = 0;
3954		if (pmb->u.mb.un.varCfgPort.gdss) {
3955			phba->sli3_options |= LPFC_SLI3_DSS_ENABLED;
3956			phba->fips_level = pmb->u.mb.un.varCfgPort.fips_level;
3957			phba->fips_spec_rev = pmb->u.mb.un.varCfgPort.fips_rev;
3958			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
3959					"2850 Security Crypto Active. FIPS x%d "
3960					"(Spec Rev: x%d)",
3961					phba->fips_level, phba->fips_spec_rev);
3962		}
3963		if (pmb->u.mb.un.varCfgPort.sec_err) {
3964			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3965					"2856 Config Port Security Crypto "
3966					"Error: x%x ",
3967					pmb->u.mb.un.varCfgPort.sec_err);
3968		}
3969		if (pmb->u.mb.un.varCfgPort.gerbm)
3970			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
3971		if (pmb->u.mb.un.varCfgPort.gcrp)
3972			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
3973
3974		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
3975		phba->port_gp = phba->mbox->us.s3_pgp.port;
3976
3977		if (phba->cfg_enable_bg) {
3978			if (pmb->u.mb.un.varCfgPort.gbg)
3979				phba->sli3_options |= LPFC_SLI3_BG_ENABLED;
3980			else
3981				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
3982						"0443 Adapter did not grant "
3983						"BlockGuard\n");
3984		}
3985	} else {
3986		phba->hbq_get = NULL;
3987		phba->port_gp = phba->mbox->us.s2.port;
3988		phba->max_vpi = 0;
3989	}
3990do_prep_failed:
3991	mempool_free(pmb, phba->mbox_mem_pool);
3992	return rc;
3993}
3994
3995
3996/**
3997 * lpfc_sli_hba_setup - SLI intialization function
3998 * @phba: Pointer to HBA context object.
3999 *
4000 * This function is the main SLI intialization function. This function
4001 * is called by the HBA intialization code, HBA reset code and HBA
4002 * error attention handler code. Caller is not required to hold any
4003 * locks. This function issues config_port mailbox command to configure
4004 * the SLI, setup iocb rings and HBQ rings. In the end the function
4005 * calls the config_port_post function to issue init_link mailbox
4006 * command and to start the discovery. The function will return zero
4007 * if successful, else it will return negative error code.
4008 **/
4009int
4010lpfc_sli_hba_setup(struct lpfc_hba *phba)
4011{
4012	uint32_t rc;
4013	int  mode = 3;
4014
4015	switch (lpfc_sli_mode) {
4016	case 2:
4017		if (phba->cfg_enable_npiv) {
4018			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4019				"1824 NPIV enabled: Override lpfc_sli_mode "
4020				"parameter (%d) to auto (0).\n",
4021				lpfc_sli_mode);
4022			break;
4023		}
4024		mode = 2;
4025		break;
4026	case 0:
4027	case 3:
4028		break;
4029	default:
4030		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4031				"1819 Unrecognized lpfc_sli_mode "
4032				"parameter: %d.\n", lpfc_sli_mode);
4033
4034		break;
4035	}
4036
4037	rc = lpfc_sli_config_port(phba, mode);
4038
4039	if (rc && lpfc_sli_mode == 3)
4040		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
4041				"1820 Unable to select SLI-3.  "
4042				"Not supported by adapter.\n");
4043	if (rc && mode != 2)
4044		rc = lpfc_sli_config_port(phba, 2);
4045	if (rc)
4046		goto lpfc_sli_hba_setup_error;
4047
4048	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
4049	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
4050		rc = pci_enable_pcie_error_reporting(phba->pcidev);
4051		if (!rc) {
4052			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4053					"2709 This device supports "
4054					"Advanced Error Reporting (AER)\n");
4055			spin_lock_irq(&phba->hbalock);
4056			phba->hba_flag |= HBA_AER_ENABLED;
4057			spin_unlock_irq(&phba->hbalock);
4058		} else {
4059			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4060					"2708 This device does not support "
4061					"Advanced Error Reporting (AER)\n");
4062			phba->cfg_aer_support = 0;
4063		}
4064	}
4065
4066	if (phba->sli_rev == 3) {
4067		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
4068		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
4069	} else {
4070		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
4071		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
4072		phba->sli3_options = 0;
4073	}
4074
4075	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4076			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
4077			phba->sli_rev, phba->max_vpi);
4078	rc = lpfc_sli_ring_map(phba);
4079
4080	if (rc)
4081		goto lpfc_sli_hba_setup_error;
4082
4083	/* Init HBQs */
4084	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
4085		rc = lpfc_sli_hbq_setup(phba);
4086		if (rc)
4087			goto lpfc_sli_hba_setup_error;
4088	}
4089	spin_lock_irq(&phba->hbalock);
4090	phba->sli.sli_flag |= LPFC_PROCESS_LA;
4091	spin_unlock_irq(&phba->hbalock);
4092
4093	rc = lpfc_config_port_post(phba);
4094	if (rc)
4095		goto lpfc_sli_hba_setup_error;
4096
4097	return rc;
4098
4099lpfc_sli_hba_setup_error:
4100	phba->link_state = LPFC_HBA_ERROR;
4101	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4102			"0445 Firmware initialization failed\n");
4103	return rc;
4104}
4105
4106/**
4107 * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
4108 * @phba: Pointer to HBA context object.
4109 * @mboxq: mailbox pointer.
4110 * This function issue a dump mailbox command to read config region
4111 * 23 and parse the records in the region and populate driver
4112 * data structure.
4113 **/
4114static int
4115lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba,
4116		LPFC_MBOXQ_t *mboxq)
4117{
4118	struct lpfc_dmabuf *mp;
4119	struct lpfc_mqe *mqe;
4120	uint32_t data_length;
4121	int rc;
4122
4123	/* Program the default value of vlan_id and fc_map */
4124	phba->valid_vlan = 0;
4125	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
4126	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
4127	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
4128
4129	mqe = &mboxq->u.mqe;
4130	if (lpfc_dump_fcoe_param(phba, mboxq))
4131		return -ENOMEM;
4132
4133	mp = (struct lpfc_dmabuf *) mboxq->context1;
4134	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4135
4136	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
4137			"(%d):2571 Mailbox cmd x%x Status x%x "
4138			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
4139			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
4140			"CQ: x%x x%x x%x x%x\n",
4141			mboxq->vport ? mboxq->vport->vpi : 0,
4142			bf_get(lpfc_mqe_command, mqe),
4143			bf_get(lpfc_mqe_status, mqe),
4144			mqe->un.mb_words[0], mqe->un.mb_words[1],
4145			mqe->un.mb_words[2], mqe->un.mb_words[3],
4146			mqe->un.mb_words[4], mqe->un.mb_words[5],
4147			mqe->un.mb_words[6], mqe->un.mb_words[7],
4148			mqe->un.mb_words[8], mqe->un.mb_words[9],
4149			mqe->un.mb_words[10], mqe->un.mb_words[11],
4150			mqe->un.mb_words[12], mqe->un.mb_words[13],
4151			mqe->un.mb_words[14], mqe->un.mb_words[15],
4152			mqe->un.mb_words[16], mqe->un.mb_words[50],
4153			mboxq->mcqe.word0,
4154			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
4155			mboxq->mcqe.trailer);
4156
4157	if (rc) {
4158		lpfc_mbuf_free(phba, mp->virt, mp->phys);
4159		kfree(mp);
4160		return -EIO;
4161	}
4162	data_length = mqe->un.mb_words[5];
4163	if (data_length > DMP_RGN23_SIZE) {
4164		lpfc_mbuf_free(phba, mp->virt, mp->phys);
4165		kfree(mp);
4166		return -EIO;
4167	}
4168
4169	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
4170	lpfc_mbuf_free(phba, mp->virt, mp->phys);
4171	kfree(mp);
4172	return 0;
4173}
4174
4175/**
4176 * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
4177 * @phba: pointer to lpfc hba data structure.
4178 * @mboxq: pointer to the LPFC_MBOXQ_t structure.
4179 * @vpd: pointer to the memory to hold resulting port vpd data.
4180 * @vpd_size: On input, the number of bytes allocated to @vpd.
4181 *	      On output, the number of data bytes in @vpd.
4182 *
4183 * This routine executes a READ_REV SLI4 mailbox command.  In
4184 * addition, this routine gets the port vpd data.
4185 *
4186 * Return codes
4187 * 	0 - successful
4188 * 	ENOMEM - could not allocated memory.
4189 **/
4190static int
4191lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
4192		    uint8_t *vpd, uint32_t *vpd_size)
4193{
4194	int rc = 0;
4195	uint32_t dma_size;
4196	struct lpfc_dmabuf *dmabuf;
4197	struct lpfc_mqe *mqe;
4198
4199	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
4200	if (!dmabuf)
4201		return -ENOMEM;
4202
4203	/*
4204	 * Get a DMA buffer for the vpd data resulting from the READ_REV
4205	 * mailbox command.
4206	 */
4207	dma_size = *vpd_size;
4208	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
4209					  dma_size,
4210					  &dmabuf->phys,
4211					  GFP_KERNEL);
4212	if (!dmabuf->virt) {
4213		kfree(dmabuf);
4214		return -ENOMEM;
4215	}
4216	memset(dmabuf->virt, 0, dma_size);
4217
4218	/*
4219	 * The SLI4 implementation of READ_REV conflicts at word1,
4220	 * bits 31:16 and SLI4 adds vpd functionality not present
4221	 * in SLI3.  This code corrects the conflicts.
4222	 */
4223	lpfc_read_rev(phba, mboxq);
4224	mqe = &mboxq->u.mqe;
4225	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
4226	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
4227	mqe->un.read_rev.word1 &= 0x0000FFFF;
4228	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
4229	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
4230
4231	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4232	if (rc) {
4233		dma_free_coherent(&phba->pcidev->dev, dma_size,
4234				  dmabuf->virt, dmabuf->phys);
4235		kfree(dmabuf);
4236		return -EIO;
4237	}
4238
4239	/*
4240	 * The available vpd length cannot be bigger than the
4241	 * DMA buffer passed to the port.  Catch the less than
4242	 * case and update the caller's size.
4243	 */
4244	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
4245		*vpd_size = mqe->un.read_rev.avail_vpd_len;
4246
4247	memcpy(vpd, dmabuf->virt, *vpd_size);
4248
4249	dma_free_coherent(&phba->pcidev->dev, dma_size,
4250			  dmabuf->virt, dmabuf->phys);
4251	kfree(dmabuf);
4252	return 0;
4253}
4254
4255/**
4256 * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
4257 * @phba: pointer to lpfc hba data structure.
4258 *
4259 * This routine is called to explicitly arm the SLI4 device's completion and
4260 * event queues
4261 **/
4262static void
4263lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
4264{
4265	uint8_t fcp_eqidx;
4266
4267	lpfc_sli4_cq_release(phba->sli4_hba.mbx_cq, LPFC_QUEUE_REARM);
4268	lpfc_sli4_cq_release(phba->sli4_hba.els_cq, LPFC_QUEUE_REARM);
4269	for (fcp_eqidx = 0; fcp_eqidx < phba->cfg_fcp_eq_count; fcp_eqidx++)
4270		lpfc_sli4_cq_release(phba->sli4_hba.fcp_cq[fcp_eqidx],
4271				     LPFC_QUEUE_REARM);
4272	lpfc_sli4_eq_release(phba->sli4_hba.sp_eq, LPFC_QUEUE_REARM);
4273	for (fcp_eqidx = 0; fcp_eqidx < phba->cfg_fcp_eq_count; fcp_eqidx++)
4274		lpfc_sli4_eq_release(phba->sli4_hba.fp_eq[fcp_eqidx],
4275				     LPFC_QUEUE_REARM);
4276}
4277
4278/**
4279 * lpfc_sli4_hba_setup - SLI4 device intialization PCI function
4280 * @phba: Pointer to HBA context object.
4281 *
4282 * This function is the main SLI4 device intialization PCI function. This
4283 * function is called by the HBA intialization code, HBA reset code and
4284 * HBA error attention handler code. Caller is not required to hold any
4285 * locks.
4286 **/
4287int
4288lpfc_sli4_hba_setup(struct lpfc_hba *phba)
4289{
4290	int rc;
4291	LPFC_MBOXQ_t *mboxq;
4292	struct lpfc_mqe *mqe;
4293	uint8_t *vpd;
4294	uint32_t vpd_size;
4295	uint32_t ftr_rsp = 0;
4296	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
4297	struct lpfc_vport *vport = phba->pport;
4298	struct lpfc_dmabuf *mp;
4299
4300	/* Perform a PCI function reset to start from clean */
4301	rc = lpfc_pci_function_reset(phba);
4302	if (unlikely(rc))
4303		return -ENODEV;
4304
4305	/* Check the HBA Host Status Register for readyness */
4306	rc = lpfc_sli4_post_status_check(phba);
4307	if (unlikely(rc))
4308		return -ENODEV;
4309	else {
4310		spin_lock_irq(&phba->hbalock);
4311		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
4312		spin_unlock_irq(&phba->hbalock);
4313	}
4314
4315	/*
4316	 * Allocate a single mailbox container for initializing the
4317	 * port.
4318	 */
4319	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4320	if (!mboxq)
4321		return -ENOMEM;
4322
4323	/*
4324	 * Continue initialization with default values even if driver failed
4325	 * to read FCoE param config regions
4326	 */
4327	if (lpfc_sli4_read_fcoe_params(phba, mboxq))
4328		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
4329			"2570 Failed to read FCoE parameters\n");
4330
4331	/* Issue READ_REV to collect vpd and FW information. */
4332	vpd_size = SLI4_PAGE_SIZE;
4333	vpd = kzalloc(vpd_size, GFP_KERNEL);
4334	if (!vpd) {
4335		rc = -ENOMEM;
4336		goto out_free_mbox;
4337	}
4338
4339	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
4340	if (unlikely(rc))
4341		goto out_free_vpd;
4342
4343	mqe = &mboxq->u.mqe;
4344	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
4345	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev))
4346		phba->hba_flag |= HBA_FCOE_SUPPORT;
4347
4348	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
4349		LPFC_DCBX_CEE_MODE)
4350		phba->hba_flag |= HBA_FIP_SUPPORT;
4351	else
4352		phba->hba_flag &= ~HBA_FIP_SUPPORT;
4353
4354	if (phba->sli_rev != LPFC_SLI_REV4 ||
4355	    !(phba->hba_flag & HBA_FCOE_SUPPORT)) {
4356		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4357			"0376 READ_REV Error. SLI Level %d "
4358			"FCoE enabled %d\n",
4359			phba->sli_rev, phba->hba_flag & HBA_FCOE_SUPPORT);
4360		rc = -EIO;
4361		goto out_free_vpd;
4362	}
4363	/*
4364	 * Evaluate the read rev and vpd data. Populate the driver
4365	 * state with the results. If this routine fails, the failure
4366	 * is not fatal as the driver will use generic values.
4367	 */
4368	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
4369	if (unlikely(!rc)) {
4370		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4371				"0377 Error %d parsing vpd. "
4372				"Using defaults.\n", rc);
4373		rc = 0;
4374	}
4375
4376	/* Save information as VPD data */
4377	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
4378	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
4379	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
4380	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
4381					 &mqe->un.read_rev);
4382	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
4383				       &mqe->un.read_rev);
4384	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
4385					    &mqe->un.read_rev);
4386	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
4387					   &mqe->un.read_rev);
4388	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
4389	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
4390	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
4391	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
4392	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
4393	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
4394	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
4395			"(%d):0380 READ_REV Status x%x "
4396			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
4397			mboxq->vport ? mboxq->vport->vpi : 0,
4398			bf_get(lpfc_mqe_status, mqe),
4399			phba->vpd.rev.opFwName,
4400			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
4401			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
4402
4403	/*
4404	 * Discover the port's supported feature set and match it against the
4405	 * hosts requests.
4406	 */
4407	lpfc_request_features(phba, mboxq);
4408	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4409	if (unlikely(rc)) {
4410		rc = -EIO;
4411		goto out_free_vpd;
4412	}
4413
4414	/*
4415	 * The port must support FCP initiator mode as this is the
4416	 * only mode running in the host.
4417	 */
4418	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
4419		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
4420				"0378 No support for fcpi mode.\n");
4421		ftr_rsp++;
4422	}
4423
4424	/*
4425	 * If the port cannot support the host's requested features
4426	 * then turn off the global config parameters to disable the
4427	 * feature in the driver.  This is not a fatal error.
4428	 */
4429	if ((phba->cfg_enable_bg) &&
4430	    !(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
4431		ftr_rsp++;
4432
4433	if (phba->max_vpi && phba->cfg_enable_npiv &&
4434	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
4435		ftr_rsp++;
4436
4437	if (ftr_rsp) {
4438		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
4439				"0379 Feature Mismatch Data: x%08x %08x "
4440				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
4441				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
4442				phba->cfg_enable_npiv, phba->max_vpi);
4443		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
4444			phba->cfg_enable_bg = 0;
4445		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
4446			phba->cfg_enable_npiv = 0;
4447	}
4448
4449	/* These SLI3 features are assumed in SLI4 */
4450	spin_lock_irq(&phba->hbalock);
4451	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
4452	spin_unlock_irq(&phba->hbalock);
4453
4454	/* Read the port's service parameters. */
4455	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
4456	if (rc) {
4457		phba->link_state = LPFC_HBA_ERROR;
4458		rc = -ENOMEM;
4459		goto out_free_vpd;
4460	}
4461
4462	mboxq->vport = vport;
4463	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
4464	mp = (struct lpfc_dmabuf *) mboxq->context1;
4465	if (rc == MBX_SUCCESS) {
4466		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
4467		rc = 0;
4468	}
4469
4470	/*
4471	 * This memory was allocated by the lpfc_read_sparam routine. Release
4472	 * it to the mbuf pool.
4473	 */
4474	lpfc_mbuf_free(phba, mp->virt, mp->phys);
4475	kfree(mp);
4476	mboxq->context1 = NULL;
4477	if (unlikely(rc)) {
4478		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4479				"0382 READ_SPARAM command failed "
4480				"status %d, mbxStatus x%x\n",
4481				rc, bf_get(lpfc_mqe_status, mqe));
4482		phba->link_state = LPFC_HBA_ERROR;
4483		rc = -EIO;
4484		goto out_free_vpd;
4485	}
4486
4487	if (phba->cfg_soft_wwnn)
4488		u64_to_wwn(phba->cfg_soft_wwnn,
4489			   vport->fc_sparam.nodeName.u.wwn);
4490	if (phba->cfg_soft_wwpn)
4491		u64_to_wwn(phba->cfg_soft_wwpn,
4492			   vport->fc_sparam.portName.u.wwn);
4493	memcpy(&vport->fc_nodename, &vport->fc_sparam.nodeName,
4494	       sizeof(struct lpfc_name));
4495	memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
4496	       sizeof(struct lpfc_name));
4497
4498	/* Update the fc_host data structures with new wwn. */
4499	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
4500	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
4501
4502	/* Register SGL pool to the device using non-embedded mailbox command */
4503	rc = lpfc_sli4_post_sgl_list(phba);
4504	if (unlikely(rc)) {
4505		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4506				"0582 Error %d during sgl post operation\n",
4507					rc);
4508		rc = -ENODEV;
4509		goto out_free_vpd;
4510	}
4511
4512	/* Register SCSI SGL pool to the device */
4513	rc = lpfc_sli4_repost_scsi_sgl_list(phba);
4514	if (unlikely(rc)) {
4515		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
4516				"0383 Error %d during scsi sgl post "
4517				"operation\n", rc);
4518		/* Some Scsi buffers were moved to the abort scsi list */
4519		/* A pci function reset will repost them */
4520		rc = -ENODEV;
4521		goto out_free_vpd;
4522	}
4523
4524	/* Post the rpi header region to the device. */
4525	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
4526	if (unlikely(rc)) {
4527		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4528				"0393 Error %d during rpi post operation\n",
4529				rc);
4530		rc = -ENODEV;
4531		goto out_free_vpd;
4532	}
4533
4534	/* Set up all the queues to the device */
4535	rc = lpfc_sli4_queue_setup(phba);
4536	if (unlikely(rc)) {
4537		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4538				"0381 Error %d during queue setup.\n ", rc);
4539		goto out_stop_timers;
4540	}
4541
4542	/* Arm the CQs and then EQs on device */
4543	lpfc_sli4_arm_cqeq_intr(phba);
4544
4545	/* Indicate device interrupt mode */
4546	phba->sli4_hba.intr_enable = 1;
4547
4548	/* Allow asynchronous mailbox command to go through */
4549	spin_lock_irq(&phba->hbalock);
4550	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
4551	spin_unlock_irq(&phba->hbalock);
4552
4553	/* Post receive buffers to the device */
4554	lpfc_sli4_rb_setup(phba);
4555
4556	/* Reset HBA FCF states after HBA reset */
4557	phba->fcf.fcf_flag = 0;
4558	phba->fcf.current_rec.flag = 0;
4559
4560	/* Start the ELS watchdog timer */
4561	mod_timer(&vport->els_tmofunc,
4562		  jiffies + HZ * (phba->fc_ratov * 2));
4563
4564	/* Start heart beat timer */
4565	mod_timer(&phba->hb_tmofunc,
4566		  jiffies + HZ * LPFC_HB_MBOX_INTERVAL);
4567	phba->hb_outstanding = 0;
4568	phba->last_completion_time = jiffies;
4569
4570	/* Start error attention (ERATT) polling timer */
4571	mod_timer(&phba->eratt_poll, jiffies + HZ * LPFC_ERATT_POLL_INTERVAL);
4572
4573	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
4574	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
4575		rc = pci_enable_pcie_error_reporting(phba->pcidev);
4576		if (!rc) {
4577			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4578					"2829 This device supports "
4579					"Advanced Error Reporting (AER)\n");
4580			spin_lock_irq(&phba->hbalock);
4581			phba->hba_flag |= HBA_AER_ENABLED;
4582			spin_unlock_irq(&phba->hbalock);
4583		} else {
4584			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4585					"2830 This device does not support "
4586					"Advanced Error Reporting (AER)\n");
4587			phba->cfg_aer_support = 0;
4588		}
4589	}
4590
4591	/*
4592	 * The port is ready, set the host's link state to LINK_DOWN
4593	 * in preparation for link interrupts.
4594	 */
4595	lpfc_init_link(phba, mboxq, phba->cfg_topology, phba->cfg_link_speed);
4596	mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4597	lpfc_set_loopback_flag(phba);
4598	/* Change driver state to LPFC_LINK_DOWN right before init link */
4599	spin_lock_irq(&phba->hbalock);
4600	phba->link_state = LPFC_LINK_DOWN;
4601	spin_unlock_irq(&phba->hbalock);
4602	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
4603	if (unlikely(rc != MBX_NOT_FINISHED)) {
4604		kfree(vpd);
4605		return 0;
4606	} else
4607		rc = -EIO;
4608
4609	/* Unset all the queues set up in this routine when error out */
4610	if (rc)
4611		lpfc_sli4_queue_unset(phba);
4612
4613out_stop_timers:
4614	if (rc)
4615		lpfc_stop_hba_timers(phba);
4616out_free_vpd:
4617	kfree(vpd);
4618out_free_mbox:
4619	mempool_free(mboxq, phba->mbox_mem_pool);
4620	return rc;
4621}
4622
4623/**
4624 * lpfc_mbox_timeout - Timeout call back function for mbox timer
4625 * @ptr: context object - pointer to hba structure.
4626 *
4627 * This is the callback function for mailbox timer. The mailbox
4628 * timer is armed when a new mailbox command is issued and the timer
4629 * is deleted when the mailbox complete. The function is called by
4630 * the kernel timer code when a mailbox does not complete within
4631 * expected time. This function wakes up the worker thread to
4632 * process the mailbox timeout and returns. All the processing is
4633 * done by the worker thread function lpfc_mbox_timeout_handler.
4634 **/
4635void
4636lpfc_mbox_timeout(unsigned long ptr)
4637{
4638	struct lpfc_hba  *phba = (struct lpfc_hba *) ptr;
4639	unsigned long iflag;
4640	uint32_t tmo_posted;
4641
4642	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
4643	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
4644	if (!tmo_posted)
4645		phba->pport->work_port_events |= WORKER_MBOX_TMO;
4646	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
4647
4648	if (!tmo_posted)
4649		lpfc_worker_wake_up(phba);
4650	return;
4651}
4652
4653
4654/**
4655 * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
4656 * @phba: Pointer to HBA context object.
4657 *
4658 * This function is called from worker thread when a mailbox command times out.
4659 * The caller is not required to hold any locks. This function will reset the
4660 * HBA and recover all the pending commands.
4661 **/
4662void
4663lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
4664{
4665	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
4666	MAILBOX_t *mb = &pmbox->u.mb;
4667	struct lpfc_sli *psli = &phba->sli;
4668	struct lpfc_sli_ring *pring;
4669
4670	/* Check the pmbox pointer first.  There is a race condition
4671	 * between the mbox timeout handler getting executed in the
4672	 * worklist and the mailbox actually completing. When this
4673	 * race condition occurs, the mbox_active will be NULL.
4674	 */
4675	spin_lock_irq(&phba->hbalock);
4676	if (pmbox == NULL) {
4677		lpfc_printf_log(phba, KERN_WARNING,
4678				LOG_MBOX | LOG_SLI,
4679				"0353 Active Mailbox cleared - mailbox timeout "
4680				"exiting\n");
4681		spin_unlock_irq(&phba->hbalock);
4682		return;
4683	}
4684
4685	/* Mbox cmd <mbxCommand> timeout */
4686	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4687			"0310 Mailbox command x%x timeout Data: x%x x%x x%p\n",
4688			mb->mbxCommand,
4689			phba->pport->port_state,
4690			phba->sli.sli_flag,
4691			phba->sli.mbox_active);
4692	spin_unlock_irq(&phba->hbalock);
4693
4694	/* Setting state unknown so lpfc_sli_abort_iocb_ring
4695	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
4696	 * it to fail all oustanding SCSI IO.
4697	 */
4698	spin_lock_irq(&phba->pport->work_port_lock);
4699	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
4700	spin_unlock_irq(&phba->pport->work_port_lock);
4701	spin_lock_irq(&phba->hbalock);
4702	phba->link_state = LPFC_LINK_UNKNOWN;
4703	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
4704	spin_unlock_irq(&phba->hbalock);
4705
4706	pring = &psli->ring[psli->fcp_ring];
4707	lpfc_sli_abort_iocb_ring(phba, pring);
4708
4709	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4710			"0345 Resetting board due to mailbox timeout\n");
4711
4712	/* Reset the HBA device */
4713	lpfc_reset_hba(phba);
4714}
4715
4716/**
4717 * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
4718 * @phba: Pointer to HBA context object.
4719 * @pmbox: Pointer to mailbox object.
4720 * @flag: Flag indicating how the mailbox need to be processed.
4721 *
4722 * This function is called by discovery code and HBA management code
4723 * to submit a mailbox command to firmware with SLI-3 interface spec. This
4724 * function gets the hbalock to protect the data structures.
4725 * The mailbox command can be submitted in polling mode, in which case
4726 * this function will wait in a polling loop for the completion of the
4727 * mailbox.
4728 * If the mailbox is submitted in no_wait mode (not polling) the
4729 * function will submit the command and returns immediately without waiting
4730 * for the mailbox completion. The no_wait is supported only when HBA
4731 * is in SLI2/SLI3 mode - interrupts are enabled.
4732 * The SLI interface allows only one mailbox pending at a time. If the
4733 * mailbox is issued in polling mode and there is already a mailbox
4734 * pending, then the function will return an error. If the mailbox is issued
4735 * in NO_WAIT mode and there is a mailbox pending already, the function
4736 * will return MBX_BUSY after queuing the mailbox into mailbox queue.
4737 * The sli layer owns the mailbox object until the completion of mailbox
4738 * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
4739 * return codes the caller owns the mailbox command after the return of
4740 * the function.
4741 **/
4742static int
4743lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
4744		       uint32_t flag)
4745{
4746	MAILBOX_t *mb;
4747	struct lpfc_sli *psli = &phba->sli;
4748	uint32_t status, evtctr;
4749	uint32_t ha_copy;
4750	int i;
4751	unsigned long timeout;
4752	unsigned long drvr_flag = 0;
4753	uint32_t word0, ldata;
4754	void __iomem *to_slim;
4755	int processing_queue = 0;
4756
4757	spin_lock_irqsave(&phba->hbalock, drvr_flag);
4758	if (!pmbox) {
4759		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4760		/* processing mbox queue from intr_handler */
4761		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
4762			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
4763			return MBX_SUCCESS;
4764		}
4765		processing_queue = 1;
4766		pmbox = lpfc_mbox_get(phba);
4767		if (!pmbox) {
4768			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
4769			return MBX_SUCCESS;
4770		}
4771	}
4772
4773	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
4774		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
4775		if(!pmbox->vport) {
4776			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
4777			lpfc_printf_log(phba, KERN_ERR,
4778					LOG_MBOX | LOG_VPORT,
4779					"1806 Mbox x%x failed. No vport\n",
4780					pmbox->u.mb.mbxCommand);
4781			dump_stack();
4782			goto out_not_finished;
4783		}
4784	}
4785
4786	/* If the PCI channel is in offline state, do not post mbox. */
4787	if (unlikely(pci_channel_offline(phba->pcidev))) {
4788		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
4789		goto out_not_finished;
4790	}
4791
4792	/* If HBA has a deferred error attention, fail the iocb. */
4793	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
4794		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
4795		goto out_not_finished;
4796	}
4797
4798	psli = &phba->sli;
4799
4800	mb = &pmbox->u.mb;
4801	status = MBX_SUCCESS;
4802
4803	if (phba->link_state == LPFC_HBA_ERROR) {
4804		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
4805
4806		/* Mbox command <mbxCommand> cannot issue */
4807		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4808				"(%d):0311 Mailbox command x%x cannot "
4809				"issue Data: x%x x%x\n",
4810				pmbox->vport ? pmbox->vport->vpi : 0,
4811				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
4812		goto out_not_finished;
4813	}
4814
4815	if (mb->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT &&
4816	    !(readl(phba->HCregaddr) & HC_MBINT_ENA)) {
4817		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
4818		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4819				"(%d):2528 Mailbox command x%x cannot "
4820				"issue Data: x%x x%x\n",
4821				pmbox->vport ? pmbox->vport->vpi : 0,
4822				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
4823		goto out_not_finished;
4824	}
4825
4826	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
4827		/* Polling for a mbox command when another one is already active
4828		 * is not allowed in SLI. Also, the driver must have established
4829		 * SLI2 mode to queue and process multiple mbox commands.
4830		 */
4831
4832		if (flag & MBX_POLL) {
4833			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
4834
4835			/* Mbox command <mbxCommand> cannot issue */
4836			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4837					"(%d):2529 Mailbox command x%x "
4838					"cannot issue Data: x%x x%x\n",
4839					pmbox->vport ? pmbox->vport->vpi : 0,
4840					pmbox->u.mb.mbxCommand,
4841					psli->sli_flag, flag);
4842			goto out_not_finished;
4843		}
4844
4845		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
4846			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
4847			/* Mbox command <mbxCommand> cannot issue */
4848			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4849					"(%d):2530 Mailbox command x%x "
4850					"cannot issue Data: x%x x%x\n",
4851					pmbox->vport ? pmbox->vport->vpi : 0,
4852					pmbox->u.mb.mbxCommand,
4853					psli->sli_flag, flag);
4854			goto out_not_finished;
4855		}
4856
4857		/* Another mailbox command is still being processed, queue this
4858		 * command to be processed later.
4859		 */
4860		lpfc_mbox_put(phba, pmbox);
4861
4862		/* Mbox cmd issue - BUSY */
4863		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
4864				"(%d):0308 Mbox cmd issue - BUSY Data: "
4865				"x%x x%x x%x x%x\n",
4866				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
4867				mb->mbxCommand, phba->pport->port_state,
4868				psli->sli_flag, flag);
4869
4870		psli->slistat.mbox_busy++;
4871		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
4872
4873		if (pmbox->vport) {
4874			lpfc_debugfs_disc_trc(pmbox->vport,
4875				LPFC_DISC_TRC_MBOX_VPORT,
4876				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
4877				(uint32_t)mb->mbxCommand,
4878				mb->un.varWords[0], mb->un.varWords[1]);
4879		}
4880		else {
4881			lpfc_debugfs_disc_trc(phba->pport,
4882				LPFC_DISC_TRC_MBOX,
4883				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
4884				(uint32_t)mb->mbxCommand,
4885				mb->un.varWords[0], mb->un.varWords[1]);
4886		}
4887
4888		return MBX_BUSY;
4889	}
4890
4891	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
4892
4893	/* If we are not polling, we MUST be in SLI2 mode */
4894	if (flag != MBX_POLL) {
4895		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
4896		    (mb->mbxCommand != MBX_KILL_BOARD)) {
4897			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4898			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
4899			/* Mbox command <mbxCommand> cannot issue */
4900			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
4901					"(%d):2531 Mailbox command x%x "
4902					"cannot issue Data: x%x x%x\n",
4903					pmbox->vport ? pmbox->vport->vpi : 0,
4904					pmbox->u.mb.mbxCommand,
4905					psli->sli_flag, flag);
4906			goto out_not_finished;
4907		}
4908		/* timeout active mbox command */
4909		mod_timer(&psli->mbox_tmo, (jiffies +
4910			       (HZ * lpfc_mbox_tmo_val(phba, mb->mbxCommand))));
4911	}
4912
4913	/* Mailbox cmd <cmd> issue */
4914	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
4915			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
4916			"x%x\n",
4917			pmbox->vport ? pmbox->vport->vpi : 0,
4918			mb->mbxCommand, phba->pport->port_state,
4919			psli->sli_flag, flag);
4920
4921	if (mb->mbxCommand != MBX_HEARTBEAT) {
4922		if (pmbox->vport) {
4923			lpfc_debugfs_disc_trc(pmbox->vport,
4924				LPFC_DISC_TRC_MBOX_VPORT,
4925				"MBOX Send vport: cmd:x%x mb:x%x x%x",
4926				(uint32_t)mb->mbxCommand,
4927				mb->un.varWords[0], mb->un.varWords[1]);
4928		}
4929		else {
4930			lpfc_debugfs_disc_trc(phba->pport,
4931				LPFC_DISC_TRC_MBOX,
4932				"MBOX Send:       cmd:x%x mb:x%x x%x",
4933				(uint32_t)mb->mbxCommand,
4934				mb->un.varWords[0], mb->un.varWords[1]);
4935		}
4936	}
4937
4938	psli->slistat.mbox_cmd++;
4939	evtctr = psli->slistat.mbox_event;
4940
4941	/* next set own bit for the adapter and copy over command word */
4942	mb->mbxOwner = OWN_CHIP;
4943
4944	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
4945		/* Populate mbox extension offset word. */
4946		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
4947			*(((uint32_t *)mb) + pmbox->mbox_offset_word)
4948				= (uint8_t *)phba->mbox_ext
4949				  - (uint8_t *)phba->mbox;
4950		}
4951
4952		/* Copy the mailbox extension data */
4953		if (pmbox->in_ext_byte_len && pmbox->context2) {
4954			lpfc_sli_pcimem_bcopy(pmbox->context2,
4955				(uint8_t *)phba->mbox_ext,
4956				pmbox->in_ext_byte_len);
4957		}
4958		/* Copy command data to host SLIM area */
4959		lpfc_sli_pcimem_bcopy(mb, phba->mbox, MAILBOX_CMD_SIZE);
4960	} else {
4961		/* Populate mbox extension offset word. */
4962		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
4963			*(((uint32_t *)mb) + pmbox->mbox_offset_word)
4964				= MAILBOX_HBA_EXT_OFFSET;
4965
4966		/* Copy the mailbox extension data */
4967		if (pmbox->in_ext_byte_len && pmbox->context2) {
4968			lpfc_memcpy_to_slim(phba->MBslimaddr +
4969				MAILBOX_HBA_EXT_OFFSET,
4970				pmbox->context2, pmbox->in_ext_byte_len);
4971
4972		}
4973		if (mb->mbxCommand == MBX_CONFIG_PORT) {
4974			/* copy command data into host mbox for cmpl */
4975			lpfc_sli_pcimem_bcopy(mb, phba->mbox, MAILBOX_CMD_SIZE);
4976		}
4977
4978		/* First copy mbox command data to HBA SLIM, skip past first
4979		   word */
4980		to_slim = phba->MBslimaddr + sizeof (uint32_t);
4981		lpfc_memcpy_to_slim(to_slim, &mb->un.varWords[0],
4982			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
4983
4984		/* Next copy over first word, with mbxOwner set */
4985		ldata = *((uint32_t *)mb);
4986		to_slim = phba->MBslimaddr;
4987		writel(ldata, to_slim);
4988		readl(to_slim); /* flush */
4989
4990		if (mb->mbxCommand == MBX_CONFIG_PORT) {
4991			/* switch over to host mailbox */
4992			psli->sli_flag |= LPFC_SLI_ACTIVE;
4993		}
4994	}
4995
4996	wmb();
4997
4998	switch (flag) {
4999	case MBX_NOWAIT:
5000		/* Set up reference to mailbox command */
5001		psli->mbox_active = pmbox;
5002		/* Interrupt board to do it */
5003		writel(CA_MBATT, phba->CAregaddr);
5004		readl(phba->CAregaddr); /* flush */
5005		/* Don't wait for it to finish, just return */
5006		break;
5007
5008	case MBX_POLL:
5009		/* Set up null reference to mailbox command */
5010		psli->mbox_active = NULL;
5011		/* Interrupt board to do it */
5012		writel(CA_MBATT, phba->CAregaddr);
5013		readl(phba->CAregaddr); /* flush */
5014
5015		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
5016			/* First read mbox status word */
5017			word0 = *((uint32_t *)phba->mbox);
5018			word0 = le32_to_cpu(word0);
5019		} else {
5020			/* First read mbox status word */
5021			word0 = readl(phba->MBslimaddr);
5022		}
5023
5024		/* Read the HBA Host Attention Register */
5025		ha_copy = readl(phba->HAregaddr);
5026		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
5027							     mb->mbxCommand) *
5028					   1000) + jiffies;
5029		i = 0;
5030		/* Wait for command to complete */
5031		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
5032		       (!(ha_copy & HA_MBATT) &&
5033			(phba->link_state > LPFC_WARM_START))) {
5034			if (time_after(jiffies, timeout)) {
5035				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5036				spin_unlock_irqrestore(&phba->hbalock,
5037						       drvr_flag);
5038				goto out_not_finished;
5039			}
5040
5041			/* Check if we took a mbox interrupt while we were
5042			   polling */
5043			if (((word0 & OWN_CHIP) != OWN_CHIP)
5044			    && (evtctr != psli->slistat.mbox_event))
5045				break;
5046
5047			if (i++ > 10) {
5048				spin_unlock_irqrestore(&phba->hbalock,
5049						       drvr_flag);
5050				msleep(1);
5051				spin_lock_irqsave(&phba->hbalock, drvr_flag);
5052			}
5053
5054			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
5055				/* First copy command data */
5056				word0 = *((uint32_t *)phba->mbox);
5057				word0 = le32_to_cpu(word0);
5058				if (mb->mbxCommand == MBX_CONFIG_PORT) {
5059					MAILBOX_t *slimmb;
5060					uint32_t slimword0;
5061					/* Check real SLIM for any errors */
5062					slimword0 = readl(phba->MBslimaddr);
5063					slimmb = (MAILBOX_t *) & slimword0;
5064					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
5065					    && slimmb->mbxStatus) {
5066						psli->sli_flag &=
5067						    ~LPFC_SLI_ACTIVE;
5068						word0 = slimword0;
5069					}
5070				}
5071			} else {
5072				/* First copy command data */
5073				word0 = readl(phba->MBslimaddr);
5074			}
5075			/* Read the HBA Host Attention Register */
5076			ha_copy = readl(phba->HAregaddr);
5077		}
5078
5079		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
5080			/* copy results back to user */
5081			lpfc_sli_pcimem_bcopy(phba->mbox, mb, MAILBOX_CMD_SIZE);
5082			/* Copy the mailbox extension data */
5083			if (pmbox->out_ext_byte_len && pmbox->context2) {
5084				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
5085						      pmbox->context2,
5086						      pmbox->out_ext_byte_len);
5087			}
5088		} else {
5089			/* First copy command data */
5090			lpfc_memcpy_from_slim(mb, phba->MBslimaddr,
5091							MAILBOX_CMD_SIZE);
5092			/* Copy the mailbox extension data */
5093			if (pmbox->out_ext_byte_len && pmbox->context2) {
5094				lpfc_memcpy_from_slim(pmbox->context2,
5095					phba->MBslimaddr +
5096					MAILBOX_HBA_EXT_OFFSET,
5097					pmbox->out_ext_byte_len);
5098			}
5099		}
5100
5101		writel(HA_MBATT, phba->HAregaddr);
5102		readl(phba->HAregaddr); /* flush */
5103
5104		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5105		status = mb->mbxStatus;
5106	}
5107
5108	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
5109	return status;
5110
5111out_not_finished:
5112	if (processing_queue) {
5113		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
5114		lpfc_mbox_cmpl_put(phba, pmbox);
5115	}
5116	return MBX_NOT_FINISHED;
5117}
5118
5119/**
5120 * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
5121 * @phba: Pointer to HBA context object.
5122 *
5123 * The function blocks the posting of SLI4 asynchronous mailbox commands from
5124 * the driver internal pending mailbox queue. It will then try to wait out the
5125 * possible outstanding mailbox command before return.
5126 *
5127 * Returns:
5128 * 	0 - the outstanding mailbox command completed; otherwise, the wait for
5129 * 	the outstanding mailbox command timed out.
5130 **/
5131static int
5132lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
5133{
5134	struct lpfc_sli *psli = &phba->sli;
5135	uint8_t actcmd = MBX_HEARTBEAT;
5136	int rc = 0;
5137	unsigned long timeout;
5138
5139	/* Mark the asynchronous mailbox command posting as blocked */
5140	spin_lock_irq(&phba->hbalock);
5141	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
5142	if (phba->sli.mbox_active)
5143		actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
5144	spin_unlock_irq(&phba->hbalock);
5145	/* Determine how long we might wait for the active mailbox
5146	 * command to be gracefully completed by firmware.
5147	 */
5148	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, actcmd) * 1000) +
5149				   jiffies;
5150	/* Wait for the outstnading mailbox command to complete */
5151	while (phba->sli.mbox_active) {
5152		/* Check active mailbox complete status every 2ms */
5153		msleep(2);
5154		if (time_after(jiffies, timeout)) {
5155			/* Timeout, marked the outstanding cmd not complete */
5156			rc = 1;
5157			break;
5158		}
5159	}
5160
5161	/* Can not cleanly block async mailbox command, fails it */
5162	if (rc) {
5163		spin_lock_irq(&phba->hbalock);
5164		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5165		spin_unlock_irq(&phba->hbalock);
5166	}
5167	return rc;
5168}
5169
5170/**
5171 * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
5172 * @phba: Pointer to HBA context object.
5173 *
5174 * The function unblocks and resume posting of SLI4 asynchronous mailbox
5175 * commands from the driver internal pending mailbox queue. It makes sure
5176 * that there is no outstanding mailbox command before resuming posting
5177 * asynchronous mailbox commands. If, for any reason, there is outstanding
5178 * mailbox command, it will try to wait it out before resuming asynchronous
5179 * mailbox command posting.
5180 **/
5181static void
5182lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
5183{
5184	struct lpfc_sli *psli = &phba->sli;
5185
5186	spin_lock_irq(&phba->hbalock);
5187	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
5188		/* Asynchronous mailbox posting is not blocked, do nothing */
5189		spin_unlock_irq(&phba->hbalock);
5190		return;
5191	}
5192
5193	/* Outstanding synchronous mailbox command is guaranteed to be done,
5194	 * successful or timeout, after timing-out the outstanding mailbox
5195	 * command shall always be removed, so just unblock posting async
5196	 * mailbox command and resume
5197	 */
5198	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5199	spin_unlock_irq(&phba->hbalock);
5200
5201	/* wake up worker thread to post asynchronlous mailbox command */
5202	lpfc_worker_wake_up(phba);
5203}
5204
5205/**
5206 * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
5207 * @phba: Pointer to HBA context object.
5208 * @mboxq: Pointer to mailbox object.
5209 *
5210 * The function posts a mailbox to the port.  The mailbox is expected
5211 * to be comletely filled in and ready for the port to operate on it.
5212 * This routine executes a synchronous completion operation on the
5213 * mailbox by polling for its completion.
5214 *
5215 * The caller must not be holding any locks when calling this routine.
5216 *
5217 * Returns:
5218 *	MBX_SUCCESS - mailbox posted successfully
5219 *	Any of the MBX error values.
5220 **/
5221static int
5222lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
5223{
5224	int rc = MBX_SUCCESS;
5225	unsigned long iflag;
5226	uint32_t db_ready;
5227	uint32_t mcqe_status;
5228	uint32_t mbx_cmnd;
5229	unsigned long timeout;
5230	struct lpfc_sli *psli = &phba->sli;
5231	struct lpfc_mqe *mb = &mboxq->u.mqe;
5232	struct lpfc_bmbx_create *mbox_rgn;
5233	struct dma_address *dma_address;
5234	struct lpfc_register bmbx_reg;
5235
5236	/*
5237	 * Only one mailbox can be active to the bootstrap mailbox region
5238	 * at a time and there is no queueing provided.
5239	 */
5240	spin_lock_irqsave(&phba->hbalock, iflag);
5241	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
5242		spin_unlock_irqrestore(&phba->hbalock, iflag);
5243		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
5244				"(%d):2532 Mailbox command x%x (x%x) "
5245				"cannot issue Data: x%x x%x\n",
5246				mboxq->vport ? mboxq->vport->vpi : 0,
5247				mboxq->u.mb.mbxCommand,
5248				lpfc_sli4_mbox_opcode_get(phba, mboxq),
5249				psli->sli_flag, MBX_POLL);
5250		return MBXERR_ERROR;
5251	}
5252	/* The server grabs the token and owns it until release */
5253	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5254	phba->sli.mbox_active = mboxq;
5255	spin_unlock_irqrestore(&phba->hbalock, iflag);
5256
5257	/*
5258	 * Initialize the bootstrap memory region to avoid stale data areas
5259	 * in the mailbox post.  Then copy the caller's mailbox contents to
5260	 * the bmbx mailbox region.
5261	 */
5262	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
5263	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
5264	lpfc_sli_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
5265			      sizeof(struct lpfc_mqe));
5266
5267	/* Post the high mailbox dma address to the port and wait for ready. */
5268	dma_address = &phba->sli4_hba.bmbx.dma_address;
5269	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
5270
5271	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mbx_cmnd)
5272				   * 1000) + jiffies;
5273	do {
5274		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
5275		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
5276		if (!db_ready)
5277			msleep(2);
5278
5279		if (time_after(jiffies, timeout)) {
5280			rc = MBXERR_ERROR;
5281			goto exit;
5282		}
5283	} while (!db_ready);
5284
5285	/* Post the low mailbox dma address to the port. */
5286	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
5287	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mbx_cmnd)
5288				   * 1000) + jiffies;
5289	do {
5290		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
5291		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
5292		if (!db_ready)
5293			msleep(2);
5294
5295		if (time_after(jiffies, timeout)) {
5296			rc = MBXERR_ERROR;
5297			goto exit;
5298		}
5299	} while (!db_ready);
5300
5301	/*
5302	 * Read the CQ to ensure the mailbox has completed.
5303	 * If so, update the mailbox status so that the upper layers
5304	 * can complete the request normally.
5305	 */
5306	lpfc_sli_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
5307			      sizeof(struct lpfc_mqe));
5308	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
5309	lpfc_sli_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
5310			      sizeof(struct lpfc_mcqe));
5311	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
5312
5313	/* Prefix the mailbox status with range x4000 to note SLI4 status. */
5314	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
5315		bf_set(lpfc_mqe_status, mb, LPFC_MBX_ERROR_RANGE | mcqe_status);
5316		rc = MBXERR_ERROR;
5317	} else
5318		lpfc_sli4_swap_str(phba, mboxq);
5319
5320	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5321			"(%d):0356 Mailbox cmd x%x (x%x) Status x%x "
5322			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
5323			" x%x x%x CQ: x%x x%x x%x x%x\n",
5324			mboxq->vport ? mboxq->vport->vpi : 0,
5325			mbx_cmnd, lpfc_sli4_mbox_opcode_get(phba, mboxq),
5326			bf_get(lpfc_mqe_status, mb),
5327			mb->un.mb_words[0], mb->un.mb_words[1],
5328			mb->un.mb_words[2], mb->un.mb_words[3],
5329			mb->un.mb_words[4], mb->un.mb_words[5],
5330			mb->un.mb_words[6], mb->un.mb_words[7],
5331			mb->un.mb_words[8], mb->un.mb_words[9],
5332			mb->un.mb_words[10], mb->un.mb_words[11],
5333			mb->un.mb_words[12], mboxq->mcqe.word0,
5334			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5335			mboxq->mcqe.trailer);
5336exit:
5337	/* We are holding the token, no needed for lock when release */
5338	spin_lock_irqsave(&phba->hbalock, iflag);
5339	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5340	phba->sli.mbox_active = NULL;
5341	spin_unlock_irqrestore(&phba->hbalock, iflag);
5342	return rc;
5343}
5344
5345/**
5346 * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
5347 * @phba: Pointer to HBA context object.
5348 * @pmbox: Pointer to mailbox object.
5349 * @flag: Flag indicating how the mailbox need to be processed.
5350 *
5351 * This function is called by discovery code and HBA management code to submit
5352 * a mailbox command to firmware with SLI-4 interface spec.
5353 *
5354 * Return codes the caller owns the mailbox command after the return of the
5355 * function.
5356 **/
5357static int
5358lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5359		       uint32_t flag)
5360{
5361	struct lpfc_sli *psli = &phba->sli;
5362	unsigned long iflags;
5363	int rc;
5364
5365	rc = lpfc_mbox_dev_check(phba);
5366	if (unlikely(rc)) {
5367		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
5368				"(%d):2544 Mailbox command x%x (x%x) "
5369				"cannot issue Data: x%x x%x\n",
5370				mboxq->vport ? mboxq->vport->vpi : 0,
5371				mboxq->u.mb.mbxCommand,
5372				lpfc_sli4_mbox_opcode_get(phba, mboxq),
5373				psli->sli_flag, flag);
5374		goto out_not_finished;
5375	}
5376
5377	/* Detect polling mode and jump to a handler */
5378	if (!phba->sli4_hba.intr_enable) {
5379		if (flag == MBX_POLL)
5380			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
5381		else
5382			rc = -EIO;
5383		if (rc != MBX_SUCCESS)
5384			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
5385					"(%d):2541 Mailbox command x%x "
5386					"(x%x) cannot issue Data: x%x x%x\n",
5387					mboxq->vport ? mboxq->vport->vpi : 0,
5388					mboxq->u.mb.mbxCommand,
5389					lpfc_sli4_mbox_opcode_get(phba, mboxq),
5390					psli->sli_flag, flag);
5391		return rc;
5392	} else if (flag == MBX_POLL) {
5393		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
5394				"(%d):2542 Try to issue mailbox command "
5395				"x%x (x%x) synchronously ahead of async"
5396				"mailbox command queue: x%x x%x\n",
5397				mboxq->vport ? mboxq->vport->vpi : 0,
5398				mboxq->u.mb.mbxCommand,
5399				lpfc_sli4_mbox_opcode_get(phba, mboxq),
5400				psli->sli_flag, flag);
5401		/* Try to block the asynchronous mailbox posting */
5402		rc = lpfc_sli4_async_mbox_block(phba);
5403		if (!rc) {
5404			/* Successfully blocked, now issue sync mbox cmd */
5405			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
5406			if (rc != MBX_SUCCESS)
5407				lpfc_printf_log(phba, KERN_ERR,
5408						LOG_MBOX | LOG_SLI,
5409						"(%d):2597 Mailbox command "
5410						"x%x (x%x) cannot issue "
5411						"Data: x%x x%x\n",
5412						mboxq->vport ?
5413						mboxq->vport->vpi : 0,
5414						mboxq->u.mb.mbxCommand,
5415						lpfc_sli4_mbox_opcode_get(phba,
5416								mboxq),
5417						psli->sli_flag, flag);
5418			/* Unblock the async mailbox posting afterward */
5419			lpfc_sli4_async_mbox_unblock(phba);
5420		}
5421		return rc;
5422	}
5423
5424	/* Now, interrupt mode asynchrous mailbox command */
5425	rc = lpfc_mbox_cmd_check(phba, mboxq);
5426	if (rc) {
5427		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
5428				"(%d):2543 Mailbox command x%x (x%x) "
5429				"cannot issue Data: x%x x%x\n",
5430				mboxq->vport ? mboxq->vport->vpi : 0,
5431				mboxq->u.mb.mbxCommand,
5432				lpfc_sli4_mbox_opcode_get(phba, mboxq),
5433				psli->sli_flag, flag);
5434		goto out_not_finished;
5435	}
5436
5437	/* Put the mailbox command to the driver internal FIFO */
5438	psli->slistat.mbox_busy++;
5439	spin_lock_irqsave(&phba->hbalock, iflags);
5440	lpfc_mbox_put(phba, mboxq);
5441	spin_unlock_irqrestore(&phba->hbalock, iflags);
5442	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5443			"(%d):0354 Mbox cmd issue - Enqueue Data: "
5444			"x%x (x%x) x%x x%x x%x\n",
5445			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
5446			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5447			lpfc_sli4_mbox_opcode_get(phba, mboxq),
5448			phba->pport->port_state,
5449			psli->sli_flag, MBX_NOWAIT);
5450	/* Wake up worker thread to transport mailbox command from head */
5451	lpfc_worker_wake_up(phba);
5452
5453	return MBX_BUSY;
5454
5455out_not_finished:
5456	return MBX_NOT_FINISHED;
5457}
5458
5459/**
5460 * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
5461 * @phba: Pointer to HBA context object.
5462 *
5463 * This function is called by worker thread to send a mailbox command to
5464 * SLI4 HBA firmware.
5465 *
5466 **/
5467int
5468lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
5469{
5470	struct lpfc_sli *psli = &phba->sli;
5471	LPFC_MBOXQ_t *mboxq;
5472	int rc = MBX_SUCCESS;
5473	unsigned long iflags;
5474	struct lpfc_mqe *mqe;
5475	uint32_t mbx_cmnd;
5476
5477	/* Check interrupt mode before post async mailbox command */
5478	if (unlikely(!phba->sli4_hba.intr_enable))
5479		return MBX_NOT_FINISHED;
5480
5481	/* Check for mailbox command service token */
5482	spin_lock_irqsave(&phba->hbalock, iflags);
5483	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
5484		spin_unlock_irqrestore(&phba->hbalock, iflags);
5485		return MBX_NOT_FINISHED;
5486	}
5487	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
5488		spin_unlock_irqrestore(&phba->hbalock, iflags);
5489		return MBX_NOT_FINISHED;
5490	}
5491	if (unlikely(phba->sli.mbox_active)) {
5492		spin_unlock_irqrestore(&phba->hbalock, iflags);
5493		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
5494				"0384 There is pending active mailbox cmd\n");
5495		return MBX_NOT_FINISHED;
5496	}
5497	/* Take the mailbox command service token */
5498	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5499
5500	/* Get the next mailbox command from head of queue */
5501	mboxq = lpfc_mbox_get(phba);
5502
5503	/* If no more mailbox command waiting for post, we're done */
5504	if (!mboxq) {
5505		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5506		spin_unlock_irqrestore(&phba->hbalock, iflags);
5507		return MBX_SUCCESS;
5508	}
5509	phba->sli.mbox_active = mboxq;
5510	spin_unlock_irqrestore(&phba->hbalock, iflags);
5511
5512	/* Check device readiness for posting mailbox command */
5513	rc = lpfc_mbox_dev_check(phba);
5514	if (unlikely(rc))
5515		/* Driver clean routine will clean up pending mailbox */
5516		goto out_not_finished;
5517
5518	/* Prepare the mbox command to be posted */
5519	mqe = &mboxq->u.mqe;
5520	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
5521
5522	/* Start timer for the mbox_tmo and log some mailbox post messages */
5523	mod_timer(&psli->mbox_tmo, (jiffies +
5524		  (HZ * lpfc_mbox_tmo_val(phba, mbx_cmnd))));
5525
5526	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5527			"(%d):0355 Mailbox cmd x%x (x%x) issue Data: "
5528			"x%x x%x\n",
5529			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
5530			lpfc_sli4_mbox_opcode_get(phba, mboxq),
5531			phba->pport->port_state, psli->sli_flag);
5532
5533	if (mbx_cmnd != MBX_HEARTBEAT) {
5534		if (mboxq->vport) {
5535			lpfc_debugfs_disc_trc(mboxq->vport,
5536				LPFC_DISC_TRC_MBOX_VPORT,
5537				"MBOX Send vport: cmd:x%x mb:x%x x%x",
5538				mbx_cmnd, mqe->un.mb_words[0],
5539				mqe->un.mb_words[1]);
5540		} else {
5541			lpfc_debugfs_disc_trc(phba->pport,
5542				LPFC_DISC_TRC_MBOX,
5543				"MBOX Send: cmd:x%x mb:x%x x%x",
5544				mbx_cmnd, mqe->un.mb_words[0],
5545				mqe->un.mb_words[1]);
5546		}
5547	}
5548	psli->slistat.mbox_cmd++;
5549
5550	/* Post the mailbox command to the port */
5551	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
5552	if (rc != MBX_SUCCESS) {
5553		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
5554				"(%d):2533 Mailbox command x%x (x%x) "
5555				"cannot issue Data: x%x x%x\n",
5556				mboxq->vport ? mboxq->vport->vpi : 0,
5557				mboxq->u.mb.mbxCommand,
5558				lpfc_sli4_mbox_opcode_get(phba, mboxq),
5559				psli->sli_flag, MBX_NOWAIT);
5560		goto out_not_finished;
5561	}
5562
5563	return rc;
5564
5565out_not_finished:
5566	spin_lock_irqsave(&phba->hbalock, iflags);
5567	mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
5568	__lpfc_mbox_cmpl_put(phba, mboxq);
5569	/* Release the token */
5570	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5571	phba->sli.mbox_active = NULL;
5572	spin_unlock_irqrestore(&phba->hbalock, iflags);
5573
5574	return MBX_NOT_FINISHED;
5575}
5576
5577/**
5578 * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
5579 * @phba: Pointer to HBA context object.
5580 * @pmbox: Pointer to mailbox object.
5581 * @flag: Flag indicating how the mailbox need to be processed.
5582 *
5583 * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
5584 * the API jump table function pointer from the lpfc_hba struct.
5585 *
5586 * Return codes the caller owns the mailbox command after the return of the
5587 * function.
5588 **/
5589int
5590lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
5591{
5592	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
5593}
5594
5595/**
5596 * lpfc_mbox_api_table_setup - Set up mbox api fucntion jump table
5597 * @phba: The hba struct for which this call is being executed.
5598 * @dev_grp: The HBA PCI-Device group number.
5599 *
5600 * This routine sets up the mbox interface API function jump table in @phba
5601 * struct.
5602 * Returns: 0 - success, -ENODEV - failure.
5603 **/
5604int
5605lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
5606{
5607
5608	switch (dev_grp) {
5609	case LPFC_PCI_DEV_LP:
5610		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
5611		phba->lpfc_sli_handle_slow_ring_event =
5612				lpfc_sli_handle_slow_ring_event_s3;
5613		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
5614		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
5615		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
5616		break;
5617	case LPFC_PCI_DEV_OC:
5618		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
5619		phba->lpfc_sli_handle_slow_ring_event =
5620				lpfc_sli_handle_slow_ring_event_s4;
5621		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
5622		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
5623		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
5624		break;
5625	default:
5626		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5627				"1420 Invalid HBA PCI-device group: 0x%x\n",
5628				dev_grp);
5629		return -ENODEV;
5630		break;
5631	}
5632	return 0;
5633}
5634
5635/**
5636 * __lpfc_sli_ringtx_put - Add an iocb to the txq
5637 * @phba: Pointer to HBA context object.
5638 * @pring: Pointer to driver SLI ring object.
5639 * @piocb: Pointer to address of newly added command iocb.
5640 *
5641 * This function is called with hbalock held to add a command
5642 * iocb to the txq when SLI layer cannot submit the command iocb
5643 * to the ring.
5644 **/
5645void
5646__lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
5647		    struct lpfc_iocbq *piocb)
5648{
5649	/* Insert the caller's iocb in the txq tail for later processing. */
5650	list_add_tail(&piocb->list, &pring->txq);
5651	pring->txq_cnt++;
5652}
5653
5654/**
5655 * lpfc_sli_next_iocb - Get the next iocb in the txq
5656 * @phba: Pointer to HBA context object.
5657 * @pring: Pointer to driver SLI ring object.
5658 * @piocb: Pointer to address of newly added command iocb.
5659 *
5660 * This function is called with hbalock held before a new
5661 * iocb is submitted to the firmware. This function checks
5662 * txq to flush the iocbs in txq to Firmware before
5663 * submitting new iocbs to the Firmware.
5664 * If there are iocbs in the txq which need to be submitted
5665 * to firmware, lpfc_sli_next_iocb returns the first element
5666 * of the txq after dequeuing it from txq.
5667 * If there is no iocb in the txq then the function will return
5668 * *piocb and *piocb is set to NULL. Caller needs to check
5669 * *piocb to find if there are more commands in the txq.
5670 **/
5671static struct lpfc_iocbq *
5672lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
5673		   struct lpfc_iocbq **piocb)
5674{
5675	struct lpfc_iocbq * nextiocb;
5676
5677	nextiocb = lpfc_sli_ringtx_get(phba, pring);
5678	if (!nextiocb) {
5679		nextiocb = *piocb;
5680		*piocb = NULL;
5681	}
5682
5683	return nextiocb;
5684}
5685
5686/**
5687 * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
5688 * @phba: Pointer to HBA context object.
5689 * @ring_number: SLI ring number to issue iocb on.
5690 * @piocb: Pointer to command iocb.
5691 * @flag: Flag indicating if this command can be put into txq.
5692 *
5693 * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
5694 * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
5695 * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
5696 * flag is turned on, the function returns IOCB_ERROR. When the link is down,
5697 * this function allows only iocbs for posting buffers. This function finds
5698 * next available slot in the command ring and posts the command to the
5699 * available slot and writes the port attention register to request HBA start
5700 * processing new iocb. If there is no slot available in the ring and
5701 * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
5702 * the function returns IOCB_BUSY.
5703 *
5704 * This function is called with hbalock held. The function will return success
5705 * after it successfully submit the iocb to firmware or after adding to the
5706 * txq.
5707 **/
5708static int
5709__lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
5710		    struct lpfc_iocbq *piocb, uint32_t flag)
5711{
5712	struct lpfc_iocbq *nextiocb;
5713	IOCB_t *iocb;
5714	struct lpfc_sli_ring *pring = &phba->sli.ring[ring_number];
5715
5716	if (piocb->iocb_cmpl && (!piocb->vport) &&
5717	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
5718	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
5719		lpfc_printf_log(phba, KERN_ERR,
5720				LOG_SLI | LOG_VPORT,
5721				"1807 IOCB x%x failed. No vport\n",
5722				piocb->iocb.ulpCommand);
5723		dump_stack();
5724		return IOCB_ERROR;
5725	}
5726
5727
5728	/* If the PCI channel is in offline state, do not post iocbs. */
5729	if (unlikely(pci_channel_offline(phba->pcidev)))
5730		return IOCB_ERROR;
5731
5732	/* If HBA has a deferred error attention, fail the iocb. */
5733	if (unlikely(phba->hba_flag & DEFER_ERATT))
5734		return IOCB_ERROR;
5735
5736	/*
5737	 * We should never get an IOCB if we are in a < LINK_DOWN state
5738	 */
5739	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
5740		return IOCB_ERROR;
5741
5742	/*
5743	 * Check to see if we are blocking IOCB processing because of a
5744	 * outstanding event.
5745	 */
5746	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
5747		goto iocb_busy;
5748
5749	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
5750		/*
5751		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
5752		 * can be issued if the link is not up.
5753		 */
5754		switch (piocb->iocb.ulpCommand) {
5755		case CMD_GEN_REQUEST64_CR:
5756		case CMD_GEN_REQUEST64_CX:
5757			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
5758				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
5759					FC_RCTL_DD_UNSOL_CMD) ||
5760				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
5761					MENLO_TRANSPORT_TYPE))
5762
5763				goto iocb_busy;
5764			break;
5765		case CMD_QUE_RING_BUF_CN:
5766		case CMD_QUE_RING_BUF64_CN:
5767			/*
5768			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
5769			 * completion, iocb_cmpl MUST be 0.
5770			 */
5771			if (piocb->iocb_cmpl)
5772				piocb->iocb_cmpl = NULL;
5773			/*FALLTHROUGH*/
5774		case CMD_CREATE_XRI_CR:
5775		case CMD_CLOSE_XRI_CN:
5776		case CMD_CLOSE_XRI_CX:
5777			break;
5778		default:
5779			goto iocb_busy;
5780		}
5781
5782	/*
5783	 * For FCP commands, we must be in a state where we can process link
5784	 * attention events.
5785	 */
5786	} else if (unlikely(pring->ringno == phba->sli.fcp_ring &&
5787			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
5788		goto iocb_busy;
5789	}
5790
5791	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
5792	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
5793		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
5794
5795	if (iocb)
5796		lpfc_sli_update_ring(phba, pring);
5797	else
5798		lpfc_sli_update_full_ring(phba, pring);
5799
5800	if (!piocb)
5801		return IOCB_SUCCESS;
5802
5803	goto out_busy;
5804
5805 iocb_busy:
5806	pring->stats.iocb_cmd_delay++;
5807
5808 out_busy:
5809
5810	if (!(flag & SLI_IOCB_RET_IOCB)) {
5811		__lpfc_sli_ringtx_put(phba, pring, piocb);
5812		return IOCB_SUCCESS;
5813	}
5814
5815	return IOCB_BUSY;
5816}
5817
5818/**
5819 * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
5820 * @phba: Pointer to HBA context object.
5821 * @piocb: Pointer to command iocb.
5822 * @sglq: Pointer to the scatter gather queue object.
5823 *
5824 * This routine converts the bpl or bde that is in the IOCB
5825 * to a sgl list for the sli4 hardware. The physical address
5826 * of the bpl/bde is converted back to a virtual address.
5827 * If the IOCB contains a BPL then the list of BDE's is
5828 * converted to sli4_sge's. If the IOCB contains a single
5829 * BDE then it is converted to a single sli_sge.
5830 * The IOCB is still in cpu endianess so the contents of
5831 * the bpl can be used without byte swapping.
5832 *
5833 * Returns valid XRI = Success, NO_XRI = Failure.
5834**/
5835static uint16_t
5836lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
5837		struct lpfc_sglq *sglq)
5838{
5839	uint16_t xritag = NO_XRI;
5840	struct ulp_bde64 *bpl = NULL;
5841	struct ulp_bde64 bde;
5842	struct sli4_sge *sgl  = NULL;
5843	IOCB_t *icmd;
5844	int numBdes = 0;
5845	int i = 0;
5846
5847	if (!piocbq || !sglq)
5848		return xritag;
5849
5850	sgl  = (struct sli4_sge *)sglq->sgl;
5851	icmd = &piocbq->iocb;
5852	if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
5853		numBdes = icmd->un.genreq64.bdl.bdeSize /
5854				sizeof(struct ulp_bde64);
5855		/* The addrHigh and addrLow fields within the IOCB
5856		 * have not been byteswapped yet so there is no
5857		 * need to swap them back.
5858		 */
5859		bpl  = (struct ulp_bde64 *)
5860			((struct lpfc_dmabuf *)piocbq->context3)->virt;
5861
5862		if (!bpl)
5863			return xritag;
5864
5865		for (i = 0; i < numBdes; i++) {
5866			/* Should already be byte swapped. */
5867			sgl->addr_hi = bpl->addrHigh;
5868			sgl->addr_lo = bpl->addrLow;
5869
5870			if ((i+1) == numBdes)
5871				bf_set(lpfc_sli4_sge_last, sgl, 1);
5872			else
5873				bf_set(lpfc_sli4_sge_last, sgl, 0);
5874			sgl->word2 = cpu_to_le32(sgl->word2);
5875			/* swap the size field back to the cpu so we
5876			 * can assign it to the sgl.
5877			 */
5878			bde.tus.w = le32_to_cpu(bpl->tus.w);
5879			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
5880			bpl++;
5881			sgl++;
5882		}
5883	} else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
5884			/* The addrHigh and addrLow fields of the BDE have not
5885			 * been byteswapped yet so they need to be swapped
5886			 * before putting them in the sgl.
5887			 */
5888			sgl->addr_hi =
5889				cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
5890			sgl->addr_lo =
5891				cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
5892			bf_set(lpfc_sli4_sge_last, sgl, 1);
5893			sgl->word2 = cpu_to_le32(sgl->word2);
5894			sgl->sge_len =
5895				cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
5896	}
5897	return sglq->sli4_xritag;
5898}
5899
5900/**
5901 * lpfc_sli4_scmd_to_wqidx_distr - scsi command to SLI4 WQ index distribution
5902 * @phba: Pointer to HBA context object.
5903 *
5904 * This routine performs a round robin SCSI command to SLI4 FCP WQ index
5905 * distribution.  This is called by __lpfc_sli_issue_iocb_s4() with the hbalock
5906 * held.
5907 *
5908 * Return: index into SLI4 fast-path FCP queue index.
5909 **/
5910static uint32_t
5911lpfc_sli4_scmd_to_wqidx_distr(struct lpfc_hba *phba)
5912{
5913	++phba->fcp_qidx;
5914	if (phba->fcp_qidx >= phba->cfg_fcp_wq_count)
5915		phba->fcp_qidx = 0;
5916
5917	return phba->fcp_qidx;
5918}
5919
5920/**
5921 * lpfc_sli_iocb2wqe - Convert the IOCB to a work queue entry.
5922 * @phba: Pointer to HBA context object.
5923 * @piocb: Pointer to command iocb.
5924 * @wqe: Pointer to the work queue entry.
5925 *
5926 * This routine converts the iocb command to its Work Queue Entry
5927 * equivalent. The wqe pointer should not have any fields set when
5928 * this routine is called because it will memcpy over them.
5929 * This routine does not set the CQ_ID or the WQEC bits in the
5930 * wqe.
5931 *
5932 * Returns: 0 = Success, IOCB_ERROR = Failure.
5933 **/
5934static int
5935lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
5936		union lpfc_wqe *wqe)
5937{
5938	uint32_t xmit_len = 0, total_len = 0;
5939	uint8_t ct = 0;
5940	uint32_t fip;
5941	uint32_t abort_tag;
5942	uint8_t command_type = ELS_COMMAND_NON_FIP;
5943	uint8_t cmnd;
5944	uint16_t xritag;
5945	struct ulp_bde64 *bpl = NULL;
5946	uint32_t els_id = ELS_ID_DEFAULT;
5947	int numBdes, i;
5948	struct ulp_bde64 bde;
5949
5950	fip = phba->hba_flag & HBA_FIP_SUPPORT;
5951	/* The fcp commands will set command type */
5952	if (iocbq->iocb_flag &  LPFC_IO_FCP)
5953		command_type = FCP_COMMAND;
5954	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
5955		command_type = ELS_COMMAND_FIP;
5956	else
5957		command_type = ELS_COMMAND_NON_FIP;
5958
5959	/* Some of the fields are in the right position already */
5960	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
5961	abort_tag = (uint32_t) iocbq->iotag;
5962	xritag = iocbq->sli4_xritag;
5963	wqe->words[7] = 0; /* The ct field has moved so reset */
5964	/* words0-2 bpl convert bde */
5965	if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
5966		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
5967				sizeof(struct ulp_bde64);
5968		bpl  = (struct ulp_bde64 *)
5969			((struct lpfc_dmabuf *)iocbq->context3)->virt;
5970		if (!bpl)
5971			return IOCB_ERROR;
5972
5973		/* Should already be byte swapped. */
5974		wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
5975		wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
5976		/* swap the size field back to the cpu so we
5977		 * can assign it to the sgl.
5978		 */
5979		wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
5980		xmit_len = wqe->generic.bde.tus.f.bdeSize;
5981		total_len = 0;
5982		for (i = 0; i < numBdes; i++) {
5983			bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
5984			total_len += bde.tus.f.bdeSize;
5985		}
5986	} else
5987		xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
5988
5989	iocbq->iocb.ulpIoTag = iocbq->iotag;
5990	cmnd = iocbq->iocb.ulpCommand;
5991
5992	switch (iocbq->iocb.ulpCommand) {
5993	case CMD_ELS_REQUEST64_CR:
5994		if (!iocbq->iocb.ulpLe) {
5995			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5996				"2007 Only Limited Edition cmd Format"
5997				" supported 0x%x\n",
5998				iocbq->iocb.ulpCommand);
5999			return IOCB_ERROR;
6000		}
6001		wqe->els_req.payload_len = xmit_len;
6002		/* Els_reguest64 has a TMO */
6003		bf_set(wqe_tmo, &wqe->els_req.wqe_com,
6004			iocbq->iocb.ulpTimeout);
6005		/* Need a VF for word 4 set the vf bit*/
6006		bf_set(els_req64_vf, &wqe->els_req, 0);
6007		/* And a VFID for word 12 */
6008		bf_set(els_req64_vfid, &wqe->els_req, 0);
6009		/*
6010		 * Set ct field to 3, indicates that the context_tag field
6011		 * contains the FCFI and remote N_Port_ID is
6012		 * in word 5.
6013		 */
6014
6015		ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
6016		bf_set(lpfc_wqe_gen_context, &wqe->generic,
6017				iocbq->iocb.ulpContext);
6018
6019		bf_set(lpfc_wqe_gen_ct, &wqe->generic, ct);
6020		bf_set(lpfc_wqe_gen_pu, &wqe->generic, 0);
6021		/* CCP CCPE PV PRI in word10 were set in the memcpy */
6022
6023		if (command_type == ELS_COMMAND_FIP) {
6024			els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
6025					>> LPFC_FIP_ELS_ID_SHIFT);
6026		}
6027		bf_set(lpfc_wqe_gen_els_id, &wqe->generic, els_id);
6028
6029	break;
6030	case CMD_XMIT_SEQUENCE64_CX:
6031		bf_set(lpfc_wqe_gen_context, &wqe->generic,
6032					iocbq->iocb.un.ulpWord[3]);
6033		wqe->generic.word3 = 0;
6034		bf_set(wqe_rcvoxid, &wqe->generic, iocbq->iocb.ulpContext);
6035		/* The entire sequence is transmitted for this IOCB */
6036		xmit_len = total_len;
6037		cmnd = CMD_XMIT_SEQUENCE64_CR;
6038	case CMD_XMIT_SEQUENCE64_CR:
6039		/* word3 iocb=io_tag32 wqe=payload_offset */
6040		/* payload offset used for multilpe outstanding
6041		 * sequences on the same exchange
6042		 */
6043		wqe->words[3] = 0;
6044		/* word4 relative_offset memcpy */
6045		/* word5 r_ctl/df_ctl memcpy */
6046		bf_set(lpfc_wqe_gen_pu, &wqe->generic, 0);
6047		wqe->xmit_sequence.xmit_len = xmit_len;
6048		command_type = OTHER_COMMAND;
6049	break;
6050	case CMD_XMIT_BCAST64_CN:
6051		/* word3 iocb=iotag32 wqe=payload_len */
6052		wqe->words[3] = 0; /* no definition for this in wqe */
6053		/* word4 iocb=rsvd wqe=rsvd */
6054		/* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
6055		/* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
6056		bf_set(lpfc_wqe_gen_ct, &wqe->generic,
6057			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
6058	break;
6059	case CMD_FCP_IWRITE64_CR:
6060		command_type = FCP_COMMAND_DATA_OUT;
6061		/* The struct for wqe fcp_iwrite has 3 fields that are somewhat
6062		 * confusing.
6063		 * word3 is payload_len: byte offset to the sgl entry for the
6064		 * fcp_command.
6065		 * word4 is total xfer len, same as the IOCB->ulpParameter.
6066		 * word5 is initial xfer len 0 = wait for xfer-ready
6067		 */
6068
6069		/* Always wait for xfer-ready before sending data */
6070		wqe->fcp_iwrite.initial_xfer_len = 0;
6071		/* word 4 (xfer length) should have been set on the memcpy */
6072
6073	/* allow write to fall through to read */
6074	case CMD_FCP_IREAD64_CR:
6075		/* FCP_CMD is always the 1st sgl entry */
6076		wqe->fcp_iread.payload_len =
6077			xmit_len + sizeof(struct fcp_rsp);
6078
6079		/* word 4 (xfer length) should have been set on the memcpy */
6080
6081		bf_set(lpfc_wqe_gen_erp, &wqe->generic,
6082			iocbq->iocb.ulpFCP2Rcvy);
6083		bf_set(lpfc_wqe_gen_lnk, &wqe->generic, iocbq->iocb.ulpXS);
6084		/* The XC bit and the XS bit are similar. The driver never
6085		 * tracked whether or not the exchange was previouslly open.
6086		 * XC = Exchange create, 0 is create. 1 is already open.
6087		 * XS = link cmd: 1 do not close the exchange after command.
6088		 * XS = 0 close exchange when command completes.
6089		 * The only time we would not set the XC bit is when the XS bit
6090		 * is set and we are sending our 2nd or greater command on
6091		 * this exchange.
6092		 */
6093		/* Always open the exchange */
6094		bf_set(wqe_xc, &wqe->fcp_iread.wqe_com, 0);
6095
6096		wqe->words[10] &= 0xffff0000; /* zero out ebde count */
6097		bf_set(lpfc_wqe_gen_pu, &wqe->generic, iocbq->iocb.ulpPU);
6098		break;
6099	case CMD_FCP_ICMND64_CR:
6100		/* Always open the exchange */
6101		bf_set(wqe_xc, &wqe->fcp_iread.wqe_com, 0);
6102
6103		wqe->words[4] = 0;
6104		wqe->words[10] &= 0xffff0000; /* zero out ebde count */
6105		bf_set(lpfc_wqe_gen_pu, &wqe->generic, 0);
6106	break;
6107	case CMD_GEN_REQUEST64_CR:
6108		/* word3 command length is described as byte offset to the
6109		 * rsp_data. Would always be 16, sizeof(struct sli4_sge)
6110		 * sgl[0] = cmnd
6111		 * sgl[1] = rsp.
6112		 *
6113		 */
6114		wqe->gen_req.command_len = xmit_len;
6115		/* Word4 parameter  copied in the memcpy */
6116		/* Word5 [rctl, type, df_ctl, la] copied in memcpy */
6117		/* word6 context tag copied in memcpy */
6118		if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
6119			ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
6120			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6121				"2015 Invalid CT %x command 0x%x\n",
6122				ct, iocbq->iocb.ulpCommand);
6123			return IOCB_ERROR;
6124		}
6125		bf_set(lpfc_wqe_gen_ct, &wqe->generic, 0);
6126		bf_set(wqe_tmo, &wqe->gen_req.wqe_com,
6127			iocbq->iocb.ulpTimeout);
6128
6129		bf_set(lpfc_wqe_gen_pu, &wqe->generic, iocbq->iocb.ulpPU);
6130		command_type = OTHER_COMMAND;
6131	break;
6132	case CMD_XMIT_ELS_RSP64_CX:
6133		/* words0-2 BDE memcpy */
6134		/* word3 iocb=iotag32 wqe=rsvd */
6135		wqe->words[3] = 0;
6136		/* word4 iocb=did wge=rsvd. */
6137		wqe->words[4] = 0;
6138		/* word5 iocb=rsvd wge=did */
6139		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
6140			 iocbq->iocb.un.elsreq64.remoteID);
6141
6142		bf_set(lpfc_wqe_gen_ct, &wqe->generic,
6143			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
6144
6145		bf_set(lpfc_wqe_gen_pu, &wqe->generic, iocbq->iocb.ulpPU);
6146		bf_set(wqe_rcvoxid, &wqe->generic, iocbq->iocb.ulpContext);
6147		if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
6148			bf_set(lpfc_wqe_gen_context, &wqe->generic,
6149			       iocbq->vport->vpi + phba->vpi_base);
6150		command_type = OTHER_COMMAND;
6151	break;
6152	case CMD_CLOSE_XRI_CN:
6153	case CMD_ABORT_XRI_CN:
6154	case CMD_ABORT_XRI_CX:
6155		/* words 0-2 memcpy should be 0 rserved */
6156		/* port will send abts */
6157		if (iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
6158			/*
6159			 * The link is down so the fw does not need to send abts
6160			 * on the wire.
6161			 */
6162			bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
6163		else
6164			bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
6165		bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
6166		wqe->words[5] = 0;
6167		bf_set(lpfc_wqe_gen_ct, &wqe->generic,
6168			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
6169		abort_tag = iocbq->iocb.un.acxri.abortIoTag;
6170		/*
6171		 * The abort handler will send us CMD_ABORT_XRI_CN or
6172		 * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
6173		 */
6174		bf_set(lpfc_wqe_gen_command, &wqe->generic, CMD_ABORT_XRI_CX);
6175		cmnd = CMD_ABORT_XRI_CX;
6176		command_type = OTHER_COMMAND;
6177		xritag = 0;
6178	break;
6179	case CMD_XMIT_BLS_RSP64_CX:
6180		/* As BLS ABTS-ACC WQE is very different from other WQEs,
6181		 * we re-construct this WQE here based on information in
6182		 * iocbq from scratch.
6183		 */
6184		memset(wqe, 0, sizeof(union lpfc_wqe));
6185		/* OX_ID is invariable to who sent ABTS to CT exchange */
6186		bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
6187		       bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_acc));
6188		if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_acc) ==
6189		    LPFC_ABTS_UNSOL_INT) {
6190			/* ABTS sent by initiator to CT exchange, the
6191			 * RX_ID field will be filled with the newly
6192			 * allocated responder XRI.
6193			 */
6194			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
6195			       iocbq->sli4_xritag);
6196		} else {
6197			/* ABTS sent by responder to CT exchange, the
6198			 * RX_ID field will be filled with the responder
6199			 * RX_ID from ABTS.
6200			 */
6201			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
6202			       bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_acc));
6203		}
6204		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
6205		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
6206		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
6207		       iocbq->iocb.ulpContext);
6208		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
6209		command_type = OTHER_COMMAND;
6210	break;
6211	case CMD_XRI_ABORTED_CX:
6212	case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
6213		/* words0-2 are all 0's no bde */
6214		/* word3 and word4 are rsvrd */
6215		wqe->words[3] = 0;
6216		wqe->words[4] = 0;
6217		/* word5 iocb=rsvd wge=did */
6218		/* There is no remote port id in the IOCB? */
6219		/* Let this fall through and fail */
6220	case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
6221	case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
6222	case CMD_FCP_TRSP64_CX: /* Target mode rcv */
6223	case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
6224	default:
6225		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6226				"2014 Invalid command 0x%x\n",
6227				iocbq->iocb.ulpCommand);
6228		return IOCB_ERROR;
6229	break;
6230
6231	}
6232	bf_set(lpfc_wqe_gen_xri, &wqe->generic, xritag);
6233	bf_set(lpfc_wqe_gen_request_tag, &wqe->generic, iocbq->iotag);
6234	wqe->generic.abort_tag = abort_tag;
6235	bf_set(lpfc_wqe_gen_cmd_type, &wqe->generic, command_type);
6236	bf_set(lpfc_wqe_gen_command, &wqe->generic, cmnd);
6237	bf_set(lpfc_wqe_gen_class, &wqe->generic, iocbq->iocb.ulpClass);
6238	bf_set(lpfc_wqe_gen_cq_id, &wqe->generic, LPFC_WQE_CQ_ID_DEFAULT);
6239
6240	return 0;
6241}
6242
6243/**
6244 * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
6245 * @phba: Pointer to HBA context object.
6246 * @ring_number: SLI ring number to issue iocb on.
6247 * @piocb: Pointer to command iocb.
6248 * @flag: Flag indicating if this command can be put into txq.
6249 *
6250 * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
6251 * an iocb command to an HBA with SLI-4 interface spec.
6252 *
6253 * This function is called with hbalock held. The function will return success
6254 * after it successfully submit the iocb to firmware or after adding to the
6255 * txq.
6256 **/
6257static int
6258__lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
6259			 struct lpfc_iocbq *piocb, uint32_t flag)
6260{
6261	struct lpfc_sglq *sglq;
6262	union lpfc_wqe wqe;
6263	struct lpfc_sli_ring *pring = &phba->sli.ring[ring_number];
6264
6265	if (piocb->sli4_xritag == NO_XRI) {
6266		if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
6267		    piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
6268			sglq = NULL;
6269		else {
6270			if (pring->txq_cnt) {
6271				if (!(flag & SLI_IOCB_RET_IOCB)) {
6272					__lpfc_sli_ringtx_put(phba,
6273						pring, piocb);
6274					return IOCB_SUCCESS;
6275				} else {
6276					return IOCB_BUSY;
6277				}
6278			} else {
6279			sglq = __lpfc_sli_get_sglq(phba);
6280				if (!sglq) {
6281					if (!(flag & SLI_IOCB_RET_IOCB)) {
6282						__lpfc_sli_ringtx_put(phba,
6283								pring,
6284								piocb);
6285						return IOCB_SUCCESS;
6286					} else
6287						return IOCB_BUSY;
6288				}
6289			}
6290		}
6291	} else if (piocb->iocb_flag &  LPFC_IO_FCP) {
6292		sglq = NULL; /* These IO's already have an XRI and
6293			      * a mapped sgl.
6294			      */
6295	} else {
6296		/* This is a continuation of a commandi,(CX) so this
6297		 * sglq is on the active list
6298		 */
6299		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_xritag);
6300		if (!sglq)
6301			return IOCB_ERROR;
6302	}
6303
6304	if (sglq) {
6305		piocb->sli4_xritag = sglq->sli4_xritag;
6306
6307		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
6308			return IOCB_ERROR;
6309	}
6310
6311	if (lpfc_sli4_iocb2wqe(phba, piocb, &wqe))
6312		return IOCB_ERROR;
6313
6314	if ((piocb->iocb_flag & LPFC_IO_FCP) ||
6315		(piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
6316		/*
6317		 * For FCP command IOCB, get a new WQ index to distribute
6318		 * WQE across the WQsr. On the other hand, for abort IOCB,
6319		 * it carries the same WQ index to the original command
6320		 * IOCB.
6321		 */
6322		if (piocb->iocb_flag & LPFC_IO_FCP)
6323			piocb->fcp_wqidx = lpfc_sli4_scmd_to_wqidx_distr(phba);
6324		if (lpfc_sli4_wq_put(phba->sli4_hba.fcp_wq[piocb->fcp_wqidx],
6325				     &wqe))
6326			return IOCB_ERROR;
6327	} else {
6328		if (lpfc_sli4_wq_put(phba->sli4_hba.els_wq, &wqe))
6329			return IOCB_ERROR;
6330	}
6331	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
6332
6333	return 0;
6334}
6335
6336/**
6337 * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
6338 *
6339 * This routine wraps the actual lockless version for issusing IOCB function
6340 * pointer from the lpfc_hba struct.
6341 *
6342 * Return codes:
6343 * 	IOCB_ERROR - Error
6344 * 	IOCB_SUCCESS - Success
6345 * 	IOCB_BUSY - Busy
6346 **/
6347int
6348__lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
6349		struct lpfc_iocbq *piocb, uint32_t flag)
6350{
6351	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
6352}
6353
6354/**
6355 * lpfc_sli_api_table_setup - Set up sli api fucntion jump table
6356 * @phba: The hba struct for which this call is being executed.
6357 * @dev_grp: The HBA PCI-Device group number.
6358 *
6359 * This routine sets up the SLI interface API function jump table in @phba
6360 * struct.
6361 * Returns: 0 - success, -ENODEV - failure.
6362 **/
6363int
6364lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
6365{
6366
6367	switch (dev_grp) {
6368	case LPFC_PCI_DEV_LP:
6369		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
6370		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
6371		break;
6372	case LPFC_PCI_DEV_OC:
6373		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
6374		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
6375		break;
6376	default:
6377		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6378				"1419 Invalid HBA PCI-device group: 0x%x\n",
6379				dev_grp);
6380		return -ENODEV;
6381		break;
6382	}
6383	phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
6384	return 0;
6385}
6386
6387/**
6388 * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
6389 * @phba: Pointer to HBA context object.
6390 * @pring: Pointer to driver SLI ring object.
6391 * @piocb: Pointer to command iocb.
6392 * @flag: Flag indicating if this command can be put into txq.
6393 *
6394 * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
6395 * function. This function gets the hbalock and calls
6396 * __lpfc_sli_issue_iocb function and will return the error returned
6397 * by __lpfc_sli_issue_iocb function. This wrapper is used by
6398 * functions which do not hold hbalock.
6399 **/
6400int
6401lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
6402		    struct lpfc_iocbq *piocb, uint32_t flag)
6403{
6404	unsigned long iflags;
6405	int rc;
6406
6407	spin_lock_irqsave(&phba->hbalock, iflags);
6408	rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
6409	spin_unlock_irqrestore(&phba->hbalock, iflags);
6410
6411	return rc;
6412}
6413
6414/**
6415 * lpfc_extra_ring_setup - Extra ring setup function
6416 * @phba: Pointer to HBA context object.
6417 *
6418 * This function is called while driver attaches with the
6419 * HBA to setup the extra ring. The extra ring is used
6420 * only when driver needs to support target mode functionality
6421 * or IP over FC functionalities.
6422 *
6423 * This function is called with no lock held.
6424 **/
6425static int
6426lpfc_extra_ring_setup( struct lpfc_hba *phba)
6427{
6428	struct lpfc_sli *psli;
6429	struct lpfc_sli_ring *pring;
6430
6431	psli = &phba->sli;
6432
6433	/* Adjust cmd/rsp ring iocb entries more evenly */
6434
6435	/* Take some away from the FCP ring */
6436	pring = &psli->ring[psli->fcp_ring];
6437	pring->numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
6438	pring->numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
6439	pring->numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
6440	pring->numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
6441
6442	/* and give them to the extra ring */
6443	pring = &psli->ring[psli->extra_ring];
6444
6445	pring->numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
6446	pring->numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
6447	pring->numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
6448	pring->numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
6449
6450	/* Setup default profile for this ring */
6451	pring->iotag_max = 4096;
6452	pring->num_mask = 1;
6453	pring->prt[0].profile = 0;      /* Mask 0 */
6454	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
6455	pring->prt[0].type = phba->cfg_multi_ring_type;
6456	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
6457	return 0;
6458}
6459
6460/**
6461 * lpfc_sli_async_event_handler - ASYNC iocb handler function
6462 * @phba: Pointer to HBA context object.
6463 * @pring: Pointer to driver SLI ring object.
6464 * @iocbq: Pointer to iocb object.
6465 *
6466 * This function is called by the slow ring event handler
6467 * function when there is an ASYNC event iocb in the ring.
6468 * This function is called with no lock held.
6469 * Currently this function handles only temperature related
6470 * ASYNC events. The function decodes the temperature sensor
6471 * event message and posts events for the management applications.
6472 **/
6473static void
6474lpfc_sli_async_event_handler(struct lpfc_hba * phba,
6475	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
6476{
6477	IOCB_t *icmd;
6478	uint16_t evt_code;
6479	uint16_t temp;
6480	struct temp_event temp_event_data;
6481	struct Scsi_Host *shost;
6482	uint32_t *iocb_w;
6483
6484	icmd = &iocbq->iocb;
6485	evt_code = icmd->un.asyncstat.evt_code;
6486	temp = icmd->ulpContext;
6487
6488	if ((evt_code != ASYNC_TEMP_WARN) &&
6489		(evt_code != ASYNC_TEMP_SAFE)) {
6490		iocb_w = (uint32_t *) icmd;
6491		lpfc_printf_log(phba,
6492			KERN_ERR,
6493			LOG_SLI,
6494			"0346 Ring %d handler: unexpected ASYNC_STATUS"
6495			" evt_code 0x%x\n"
6496			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
6497			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
6498			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
6499			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
6500			pring->ringno,
6501			icmd->un.asyncstat.evt_code,
6502			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
6503			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
6504			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
6505			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
6506
6507		return;
6508	}
6509	temp_event_data.data = (uint32_t)temp;
6510	temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
6511	if (evt_code == ASYNC_TEMP_WARN) {
6512		temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
6513		lpfc_printf_log(phba,
6514				KERN_ERR,
6515				LOG_TEMP,
6516				"0347 Adapter is very hot, please take "
6517				"corrective action. temperature : %d Celsius\n",
6518				temp);
6519	}
6520	if (evt_code == ASYNC_TEMP_SAFE) {
6521		temp_event_data.event_code = LPFC_NORMAL_TEMP;
6522		lpfc_printf_log(phba,
6523				KERN_ERR,
6524				LOG_TEMP,
6525				"0340 Adapter temperature is OK now. "
6526				"temperature : %d Celsius\n",
6527				temp);
6528	}
6529
6530	/* Send temperature change event to applications */
6531	shost = lpfc_shost_from_vport(phba->pport);
6532	fc_host_post_vendor_event(shost, fc_get_event_number(),
6533		sizeof(temp_event_data), (char *) &temp_event_data,
6534		LPFC_NL_VENDOR_ID);
6535
6536}
6537
6538
6539/**
6540 * lpfc_sli_setup - SLI ring setup function
6541 * @phba: Pointer to HBA context object.
6542 *
6543 * lpfc_sli_setup sets up rings of the SLI interface with
6544 * number of iocbs per ring and iotags. This function is
6545 * called while driver attach to the HBA and before the
6546 * interrupts are enabled. So there is no need for locking.
6547 *
6548 * This function always returns 0.
6549 **/
6550int
6551lpfc_sli_setup(struct lpfc_hba *phba)
6552{
6553	int i, totiocbsize = 0;
6554	struct lpfc_sli *psli = &phba->sli;
6555	struct lpfc_sli_ring *pring;
6556
6557	psli->num_rings = MAX_CONFIGURED_RINGS;
6558	psli->sli_flag = 0;
6559	psli->fcp_ring = LPFC_FCP_RING;
6560	psli->next_ring = LPFC_FCP_NEXT_RING;
6561	psli->extra_ring = LPFC_EXTRA_RING;
6562
6563	psli->iocbq_lookup = NULL;
6564	psli->iocbq_lookup_len = 0;
6565	psli->last_iotag = 0;
6566
6567	for (i = 0; i < psli->num_rings; i++) {
6568		pring = &psli->ring[i];
6569		switch (i) {
6570		case LPFC_FCP_RING:	/* ring 0 - FCP */
6571			/* numCiocb and numRiocb are used in config_port */
6572			pring->numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
6573			pring->numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
6574			pring->numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
6575			pring->numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
6576			pring->numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
6577			pring->numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
6578			pring->sizeCiocb = (phba->sli_rev == 3) ?
6579							SLI3_IOCB_CMD_SIZE :
6580							SLI2_IOCB_CMD_SIZE;
6581			pring->sizeRiocb = (phba->sli_rev == 3) ?
6582							SLI3_IOCB_RSP_SIZE :
6583							SLI2_IOCB_RSP_SIZE;
6584			pring->iotag_ctr = 0;
6585			pring->iotag_max =
6586			    (phba->cfg_hba_queue_depth * 2);
6587			pring->fast_iotag = pring->iotag_max;
6588			pring->num_mask = 0;
6589			break;
6590		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
6591			/* numCiocb and numRiocb are used in config_port */
6592			pring->numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
6593			pring->numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
6594			pring->sizeCiocb = (phba->sli_rev == 3) ?
6595							SLI3_IOCB_CMD_SIZE :
6596							SLI2_IOCB_CMD_SIZE;
6597			pring->sizeRiocb = (phba->sli_rev == 3) ?
6598							SLI3_IOCB_RSP_SIZE :
6599							SLI2_IOCB_RSP_SIZE;
6600			pring->iotag_max = phba->cfg_hba_queue_depth;
6601			pring->num_mask = 0;
6602			break;
6603		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
6604			/* numCiocb and numRiocb are used in config_port */
6605			pring->numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
6606			pring->numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
6607			pring->sizeCiocb = (phba->sli_rev == 3) ?
6608							SLI3_IOCB_CMD_SIZE :
6609							SLI2_IOCB_CMD_SIZE;
6610			pring->sizeRiocb = (phba->sli_rev == 3) ?
6611							SLI3_IOCB_RSP_SIZE :
6612							SLI2_IOCB_RSP_SIZE;
6613			pring->fast_iotag = 0;
6614			pring->iotag_ctr = 0;
6615			pring->iotag_max = 4096;
6616			pring->lpfc_sli_rcv_async_status =
6617				lpfc_sli_async_event_handler;
6618			pring->num_mask = LPFC_MAX_RING_MASK;
6619			pring->prt[0].profile = 0;	/* Mask 0 */
6620			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
6621			pring->prt[0].type = FC_TYPE_ELS;
6622			pring->prt[0].lpfc_sli_rcv_unsol_event =
6623			    lpfc_els_unsol_event;
6624			pring->prt[1].profile = 0;	/* Mask 1 */
6625			pring->prt[1].rctl = FC_RCTL_ELS_REP;
6626			pring->prt[1].type = FC_TYPE_ELS;
6627			pring->prt[1].lpfc_sli_rcv_unsol_event =
6628			    lpfc_els_unsol_event;
6629			pring->prt[2].profile = 0;	/* Mask 2 */
6630			/* NameServer Inquiry */
6631			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
6632			/* NameServer */
6633			pring->prt[2].type = FC_TYPE_CT;
6634			pring->prt[2].lpfc_sli_rcv_unsol_event =
6635			    lpfc_ct_unsol_event;
6636			pring->prt[3].profile = 0;	/* Mask 3 */
6637			/* NameServer response */
6638			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
6639			/* NameServer */
6640			pring->prt[3].type = FC_TYPE_CT;
6641			pring->prt[3].lpfc_sli_rcv_unsol_event =
6642			    lpfc_ct_unsol_event;
6643			/* abort unsolicited sequence */
6644			pring->prt[4].profile = 0;	/* Mask 4 */
6645			pring->prt[4].rctl = FC_RCTL_BA_ABTS;
6646			pring->prt[4].type = FC_TYPE_BLS;
6647			pring->prt[4].lpfc_sli_rcv_unsol_event =
6648			    lpfc_sli4_ct_abort_unsol_event;
6649			break;
6650		}
6651		totiocbsize += (pring->numCiocb * pring->sizeCiocb) +
6652				(pring->numRiocb * pring->sizeRiocb);
6653	}
6654	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
6655		/* Too many cmd / rsp ring entries in SLI2 SLIM */
6656		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
6657		       "SLI2 SLIM Data: x%x x%lx\n",
6658		       phba->brd_no, totiocbsize,
6659		       (unsigned long) MAX_SLIM_IOCB_SIZE);
6660	}
6661	if (phba->cfg_multi_ring_support == 2)
6662		lpfc_extra_ring_setup(phba);
6663
6664	return 0;
6665}
6666
6667/**
6668 * lpfc_sli_queue_setup - Queue initialization function
6669 * @phba: Pointer to HBA context object.
6670 *
6671 * lpfc_sli_queue_setup sets up mailbox queues and iocb queues for each
6672 * ring. This function also initializes ring indices of each ring.
6673 * This function is called during the initialization of the SLI
6674 * interface of an HBA.
6675 * This function is called with no lock held and always returns
6676 * 1.
6677 **/
6678int
6679lpfc_sli_queue_setup(struct lpfc_hba *phba)
6680{
6681	struct lpfc_sli *psli;
6682	struct lpfc_sli_ring *pring;
6683	int i;
6684
6685	psli = &phba->sli;
6686	spin_lock_irq(&phba->hbalock);
6687	INIT_LIST_HEAD(&psli->mboxq);
6688	INIT_LIST_HEAD(&psli->mboxq_cmpl);
6689	/* Initialize list headers for txq and txcmplq as double linked lists */
6690	for (i = 0; i < psli->num_rings; i++) {
6691		pring = &psli->ring[i];
6692		pring->ringno = i;
6693		pring->next_cmdidx  = 0;
6694		pring->local_getidx = 0;
6695		pring->cmdidx = 0;
6696		INIT_LIST_HEAD(&pring->txq);
6697		INIT_LIST_HEAD(&pring->txcmplq);
6698		INIT_LIST_HEAD(&pring->iocb_continueq);
6699		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
6700		INIT_LIST_HEAD(&pring->postbufq);
6701	}
6702	spin_unlock_irq(&phba->hbalock);
6703	return 1;
6704}
6705
6706/**
6707 * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
6708 * @phba: Pointer to HBA context object.
6709 *
6710 * This routine flushes the mailbox command subsystem. It will unconditionally
6711 * flush all the mailbox commands in the three possible stages in the mailbox
6712 * command sub-system: pending mailbox command queue; the outstanding mailbox
6713 * command; and completed mailbox command queue. It is caller's responsibility
6714 * to make sure that the driver is in the proper state to flush the mailbox
6715 * command sub-system. Namely, the posting of mailbox commands into the
6716 * pending mailbox command queue from the various clients must be stopped;
6717 * either the HBA is in a state that it will never works on the outstanding
6718 * mailbox command (such as in EEH or ERATT conditions) or the outstanding
6719 * mailbox command has been completed.
6720 **/
6721static void
6722lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
6723{
6724	LIST_HEAD(completions);
6725	struct lpfc_sli *psli = &phba->sli;
6726	LPFC_MBOXQ_t *pmb;
6727	unsigned long iflag;
6728
6729	/* Flush all the mailbox commands in the mbox system */
6730	spin_lock_irqsave(&phba->hbalock, iflag);
6731	/* The pending mailbox command queue */
6732	list_splice_init(&phba->sli.mboxq, &completions);
6733	/* The outstanding active mailbox command */
6734	if (psli->mbox_active) {
6735		list_add_tail(&psli->mbox_active->list, &completions);
6736		psli->mbox_active = NULL;
6737		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
6738	}
6739	/* The completed mailbox command queue */
6740	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
6741	spin_unlock_irqrestore(&phba->hbalock, iflag);
6742
6743	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
6744	while (!list_empty(&completions)) {
6745		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
6746		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
6747		if (pmb->mbox_cmpl)
6748			pmb->mbox_cmpl(phba, pmb);
6749	}
6750}
6751
6752/**
6753 * lpfc_sli_host_down - Vport cleanup function
6754 * @vport: Pointer to virtual port object.
6755 *
6756 * lpfc_sli_host_down is called to clean up the resources
6757 * associated with a vport before destroying virtual
6758 * port data structures.
6759 * This function does following operations:
6760 * - Free discovery resources associated with this virtual
6761 *   port.
6762 * - Free iocbs associated with this virtual port in
6763 *   the txq.
6764 * - Send abort for all iocb commands associated with this
6765 *   vport in txcmplq.
6766 *
6767 * This function is called with no lock held and always returns 1.
6768 **/
6769int
6770lpfc_sli_host_down(struct lpfc_vport *vport)
6771{
6772	LIST_HEAD(completions);
6773	struct lpfc_hba *phba = vport->phba;
6774	struct lpfc_sli *psli = &phba->sli;
6775	struct lpfc_sli_ring *pring;
6776	struct lpfc_iocbq *iocb, *next_iocb;
6777	int i;
6778	unsigned long flags = 0;
6779	uint16_t prev_pring_flag;
6780
6781	lpfc_cleanup_discovery_resources(vport);
6782
6783	spin_lock_irqsave(&phba->hbalock, flags);
6784	for (i = 0; i < psli->num_rings; i++) {
6785		pring = &psli->ring[i];
6786		prev_pring_flag = pring->flag;
6787		/* Only slow rings */
6788		if (pring->ringno == LPFC_ELS_RING) {
6789			pring->flag |= LPFC_DEFERRED_RING_EVENT;
6790			/* Set the lpfc data pending flag */
6791			set_bit(LPFC_DATA_READY, &phba->data_flags);
6792		}
6793		/*
6794		 * Error everything on the txq since these iocbs have not been
6795		 * given to the FW yet.
6796		 */
6797		list_for_each_entry_safe(iocb, next_iocb, &pring->txq, list) {
6798			if (iocb->vport != vport)
6799				continue;
6800			list_move_tail(&iocb->list, &completions);
6801			pring->txq_cnt--;
6802		}
6803
6804		/* Next issue ABTS for everything on the txcmplq */
6805		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq,
6806									list) {
6807			if (iocb->vport != vport)
6808				continue;
6809			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
6810		}
6811
6812		pring->flag = prev_pring_flag;
6813	}
6814
6815	spin_unlock_irqrestore(&phba->hbalock, flags);
6816
6817	/* Cancel all the IOCBs from the completions list */
6818	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
6819			      IOERR_SLI_DOWN);
6820	return 1;
6821}
6822
6823/**
6824 * lpfc_sli_hba_down - Resource cleanup function for the HBA
6825 * @phba: Pointer to HBA context object.
6826 *
6827 * This function cleans up all iocb, buffers, mailbox commands
6828 * while shutting down the HBA. This function is called with no
6829 * lock held and always returns 1.
6830 * This function does the following to cleanup driver resources:
6831 * - Free discovery resources for each virtual port
6832 * - Cleanup any pending fabric iocbs
6833 * - Iterate through the iocb txq and free each entry
6834 *   in the list.
6835 * - Free up any buffer posted to the HBA
6836 * - Free mailbox commands in the mailbox queue.
6837 **/
6838int
6839lpfc_sli_hba_down(struct lpfc_hba *phba)
6840{
6841	LIST_HEAD(completions);
6842	struct lpfc_sli *psli = &phba->sli;
6843	struct lpfc_sli_ring *pring;
6844	struct lpfc_dmabuf *buf_ptr;
6845	unsigned long flags = 0;
6846	int i;
6847
6848	/* Shutdown the mailbox command sub-system */
6849	lpfc_sli_mbox_sys_shutdown(phba);
6850
6851	lpfc_hba_down_prep(phba);
6852
6853	lpfc_fabric_abort_hba(phba);
6854
6855	spin_lock_irqsave(&phba->hbalock, flags);
6856	for (i = 0; i < psli->num_rings; i++) {
6857		pring = &psli->ring[i];
6858		/* Only slow rings */
6859		if (pring->ringno == LPFC_ELS_RING) {
6860			pring->flag |= LPFC_DEFERRED_RING_EVENT;
6861			/* Set the lpfc data pending flag */
6862			set_bit(LPFC_DATA_READY, &phba->data_flags);
6863		}
6864
6865		/*
6866		 * Error everything on the txq since these iocbs have not been
6867		 * given to the FW yet.
6868		 */
6869		list_splice_init(&pring->txq, &completions);
6870		pring->txq_cnt = 0;
6871
6872	}
6873	spin_unlock_irqrestore(&phba->hbalock, flags);
6874
6875	/* Cancel all the IOCBs from the completions list */
6876	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
6877			      IOERR_SLI_DOWN);
6878
6879	spin_lock_irqsave(&phba->hbalock, flags);
6880	list_splice_init(&phba->elsbuf, &completions);
6881	phba->elsbuf_cnt = 0;
6882	phba->elsbuf_prev_cnt = 0;
6883	spin_unlock_irqrestore(&phba->hbalock, flags);
6884
6885	while (!list_empty(&completions)) {
6886		list_remove_head(&completions, buf_ptr,
6887			struct lpfc_dmabuf, list);
6888		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
6889		kfree(buf_ptr);
6890	}
6891
6892	/* Return any active mbox cmds */
6893	del_timer_sync(&psli->mbox_tmo);
6894
6895	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
6896	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
6897	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
6898
6899	return 1;
6900}
6901
6902/**
6903 * lpfc_sli4_hba_down - PCI function resource cleanup for the SLI4 HBA
6904 * @phba: Pointer to HBA context object.
6905 *
6906 * This function cleans up all queues, iocb, buffers, mailbox commands while
6907 * shutting down the SLI4 HBA FCoE function. This function is called with no
6908 * lock held and always returns 1.
6909 *
6910 * This function does the following to cleanup driver FCoE function resources:
6911 * - Free discovery resources for each virtual port
6912 * - Cleanup any pending fabric iocbs
6913 * - Iterate through the iocb txq and free each entry in the list.
6914 * - Free up any buffer posted to the HBA.
6915 * - Clean up all the queue entries: WQ, RQ, MQ, EQ, CQ, etc.
6916 * - Free mailbox commands in the mailbox queue.
6917 **/
6918int
6919lpfc_sli4_hba_down(struct lpfc_hba *phba)
6920{
6921	/* Stop the SLI4 device port */
6922	lpfc_stop_port(phba);
6923
6924	/* Tear down the queues in the HBA */
6925	lpfc_sli4_queue_unset(phba);
6926
6927	/* unregister default FCFI from the HBA */
6928	lpfc_sli4_fcfi_unreg(phba, phba->fcf.fcfi);
6929
6930	return 1;
6931}
6932
6933/**
6934 * lpfc_sli_pcimem_bcopy - SLI memory copy function
6935 * @srcp: Source memory pointer.
6936 * @destp: Destination memory pointer.
6937 * @cnt: Number of words required to be copied.
6938 *
6939 * This function is used for copying data between driver memory
6940 * and the SLI memory. This function also changes the endianness
6941 * of each word if native endianness is different from SLI
6942 * endianness. This function can be called with or without
6943 * lock.
6944 **/
6945void
6946lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
6947{
6948	uint32_t *src = srcp;
6949	uint32_t *dest = destp;
6950	uint32_t ldata;
6951	int i;
6952
6953	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
6954		ldata = *src;
6955		ldata = le32_to_cpu(ldata);
6956		*dest = ldata;
6957		src++;
6958		dest++;
6959	}
6960}
6961
6962
6963/**
6964 * lpfc_sli_bemem_bcopy - SLI memory copy function
6965 * @srcp: Source memory pointer.
6966 * @destp: Destination memory pointer.
6967 * @cnt: Number of words required to be copied.
6968 *
6969 * This function is used for copying data between a data structure
6970 * with big endian representation to local endianness.
6971 * This function can be called with or without lock.
6972 **/
6973void
6974lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
6975{
6976	uint32_t *src = srcp;
6977	uint32_t *dest = destp;
6978	uint32_t ldata;
6979	int i;
6980
6981	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
6982		ldata = *src;
6983		ldata = be32_to_cpu(ldata);
6984		*dest = ldata;
6985		src++;
6986		dest++;
6987	}
6988}
6989
6990/**
6991 * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
6992 * @phba: Pointer to HBA context object.
6993 * @pring: Pointer to driver SLI ring object.
6994 * @mp: Pointer to driver buffer object.
6995 *
6996 * This function is called with no lock held.
6997 * It always return zero after adding the buffer to the postbufq
6998 * buffer list.
6999 **/
7000int
7001lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
7002			 struct lpfc_dmabuf *mp)
7003{
7004	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
7005	   later */
7006	spin_lock_irq(&phba->hbalock);
7007	list_add_tail(&mp->list, &pring->postbufq);
7008	pring->postbufq_cnt++;
7009	spin_unlock_irq(&phba->hbalock);
7010	return 0;
7011}
7012
7013/**
7014 * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
7015 * @phba: Pointer to HBA context object.
7016 *
7017 * When HBQ is enabled, buffers are searched based on tags. This function
7018 * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
7019 * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
7020 * does not conflict with tags of buffer posted for unsolicited events.
7021 * The function returns the allocated tag. The function is called with
7022 * no locks held.
7023 **/
7024uint32_t
7025lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
7026{
7027	spin_lock_irq(&phba->hbalock);
7028	phba->buffer_tag_count++;
7029	/*
7030	 * Always set the QUE_BUFTAG_BIT to distiguish between
7031	 * a tag assigned by HBQ.
7032	 */
7033	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
7034	spin_unlock_irq(&phba->hbalock);
7035	return phba->buffer_tag_count;
7036}
7037
7038/**
7039 * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
7040 * @phba: Pointer to HBA context object.
7041 * @pring: Pointer to driver SLI ring object.
7042 * @tag: Buffer tag.
7043 *
7044 * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
7045 * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
7046 * iocb is posted to the response ring with the tag of the buffer.
7047 * This function searches the pring->postbufq list using the tag
7048 * to find buffer associated with CMD_IOCB_RET_XRI64_CX
7049 * iocb. If the buffer is found then lpfc_dmabuf object of the
7050 * buffer is returned to the caller else NULL is returned.
7051 * This function is called with no lock held.
7052 **/
7053struct lpfc_dmabuf *
7054lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
7055			uint32_t tag)
7056{
7057	struct lpfc_dmabuf *mp, *next_mp;
7058	struct list_head *slp = &pring->postbufq;
7059
7060	/* Search postbufq, from the begining, looking for a match on tag */
7061	spin_lock_irq(&phba->hbalock);
7062	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
7063		if (mp->buffer_tag == tag) {
7064			list_del_init(&mp->list);
7065			pring->postbufq_cnt--;
7066			spin_unlock_irq(&phba->hbalock);
7067			return mp;
7068		}
7069	}
7070
7071	spin_unlock_irq(&phba->hbalock);
7072	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7073			"0402 Cannot find virtual addr for buffer tag on "
7074			"ring %d Data x%lx x%p x%p x%x\n",
7075			pring->ringno, (unsigned long) tag,
7076			slp->next, slp->prev, pring->postbufq_cnt);
7077
7078	return NULL;
7079}
7080
7081/**
7082 * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
7083 * @phba: Pointer to HBA context object.
7084 * @pring: Pointer to driver SLI ring object.
7085 * @phys: DMA address of the buffer.
7086 *
7087 * This function searches the buffer list using the dma_address
7088 * of unsolicited event to find the driver's lpfc_dmabuf object
7089 * corresponding to the dma_address. The function returns the
7090 * lpfc_dmabuf object if a buffer is found else it returns NULL.
7091 * This function is called by the ct and els unsolicited event
7092 * handlers to get the buffer associated with the unsolicited
7093 * event.
7094 *
7095 * This function is called with no lock held.
7096 **/
7097struct lpfc_dmabuf *
7098lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
7099			 dma_addr_t phys)
7100{
7101	struct lpfc_dmabuf *mp, *next_mp;
7102	struct list_head *slp = &pring->postbufq;
7103
7104	/* Search postbufq, from the begining, looking for a match on phys */
7105	spin_lock_irq(&phba->hbalock);
7106	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
7107		if (mp->phys == phys) {
7108			list_del_init(&mp->list);
7109			pring->postbufq_cnt--;
7110			spin_unlock_irq(&phba->hbalock);
7111			return mp;
7112		}
7113	}
7114
7115	spin_unlock_irq(&phba->hbalock);
7116	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7117			"0410 Cannot find virtual addr for mapped buf on "
7118			"ring %d Data x%llx x%p x%p x%x\n",
7119			pring->ringno, (unsigned long long)phys,
7120			slp->next, slp->prev, pring->postbufq_cnt);
7121	return NULL;
7122}
7123
7124/**
7125 * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
7126 * @phba: Pointer to HBA context object.
7127 * @cmdiocb: Pointer to driver command iocb object.
7128 * @rspiocb: Pointer to driver response iocb object.
7129 *
7130 * This function is the completion handler for the abort iocbs for
7131 * ELS commands. This function is called from the ELS ring event
7132 * handler with no lock held. This function frees memory resources
7133 * associated with the abort iocb.
7134 **/
7135static void
7136lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
7137			struct lpfc_iocbq *rspiocb)
7138{
7139	IOCB_t *irsp = &rspiocb->iocb;
7140	uint16_t abort_iotag, abort_context;
7141	struct lpfc_iocbq *abort_iocb;
7142	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
7143
7144	abort_iocb = NULL;
7145
7146	if (irsp->ulpStatus) {
7147		abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
7148		abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
7149
7150		spin_lock_irq(&phba->hbalock);
7151		if (phba->sli_rev < LPFC_SLI_REV4) {
7152			if (abort_iotag != 0 &&
7153				abort_iotag <= phba->sli.last_iotag)
7154				abort_iocb =
7155					phba->sli.iocbq_lookup[abort_iotag];
7156		} else
7157			/* For sli4 the abort_tag is the XRI,
7158			 * so the abort routine puts the iotag  of the iocb
7159			 * being aborted in the context field of the abort
7160			 * IOCB.
7161			 */
7162			abort_iocb = phba->sli.iocbq_lookup[abort_context];
7163
7164		/*
7165		 *  If the iocb is not found in Firmware queue the iocb
7166		 *  might have completed already. Do not free it again.
7167		 */
7168		if (irsp->ulpStatus == IOSTAT_LOCAL_REJECT) {
7169			if (irsp->un.ulpWord[4] != IOERR_NO_XRI) {
7170				spin_unlock_irq(&phba->hbalock);
7171				lpfc_sli_release_iocbq(phba, cmdiocb);
7172				return;
7173			}
7174			/* For SLI4 the ulpContext field for abort IOCB
7175			 * holds the iotag of the IOCB being aborted so
7176			 * the local abort_context needs to be reset to
7177			 * match the aborted IOCBs ulpContext.
7178			 */
7179			if (abort_iocb && phba->sli_rev == LPFC_SLI_REV4)
7180				abort_context = abort_iocb->iocb.ulpContext;
7181		}
7182
7183		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
7184				"0327 Cannot abort els iocb %p "
7185				"with tag %x context %x, abort status %x, "
7186				"abort code %x\n",
7187				abort_iocb, abort_iotag, abort_context,
7188				irsp->ulpStatus, irsp->un.ulpWord[4]);
7189		/*
7190		 * make sure we have the right iocbq before taking it
7191		 * off the txcmplq and try to call completion routine.
7192		 */
7193		if (!abort_iocb ||
7194		    abort_iocb->iocb.ulpContext != abort_context ||
7195		    (abort_iocb->iocb_flag & LPFC_DRIVER_ABORTED) == 0)
7196			spin_unlock_irq(&phba->hbalock);
7197		else if (phba->sli_rev < LPFC_SLI_REV4) {
7198			/*
7199			 * leave the SLI4 aborted command on the txcmplq
7200			 * list and the command complete WCQE's XB bit
7201			 * will tell whether the SGL (XRI) can be released
7202			 * immediately or to the aborted SGL list for the
7203			 * following abort XRI from the HBA.
7204			 */
7205			list_del_init(&abort_iocb->list);
7206			if (abort_iocb->iocb_flag & LPFC_IO_ON_Q) {
7207				abort_iocb->iocb_flag &= ~LPFC_IO_ON_Q;
7208				pring->txcmplq_cnt--;
7209			}
7210
7211			/* Firmware could still be in progress of DMAing
7212			 * payload, so don't free data buffer till after
7213			 * a hbeat.
7214			 */
7215			abort_iocb->iocb_flag |= LPFC_DELAY_MEM_FREE;
7216			abort_iocb->iocb_flag &= ~LPFC_DRIVER_ABORTED;
7217			spin_unlock_irq(&phba->hbalock);
7218
7219			abort_iocb->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
7220			abort_iocb->iocb.un.ulpWord[4] = IOERR_ABORT_REQUESTED;
7221			(abort_iocb->iocb_cmpl)(phba, abort_iocb, abort_iocb);
7222		} else
7223			spin_unlock_irq(&phba->hbalock);
7224	}
7225
7226	lpfc_sli_release_iocbq(phba, cmdiocb);
7227	return;
7228}
7229
7230/**
7231 * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
7232 * @phba: Pointer to HBA context object.
7233 * @cmdiocb: Pointer to driver command iocb object.
7234 * @rspiocb: Pointer to driver response iocb object.
7235 *
7236 * The function is called from SLI ring event handler with no
7237 * lock held. This function is the completion handler for ELS commands
7238 * which are aborted. The function frees memory resources used for
7239 * the aborted ELS commands.
7240 **/
7241static void
7242lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
7243		     struct lpfc_iocbq *rspiocb)
7244{
7245	IOCB_t *irsp = &rspiocb->iocb;
7246
7247	/* ELS cmd tag <ulpIoTag> completes */
7248	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
7249			"0139 Ignoring ELS cmd tag x%x completion Data: "
7250			"x%x x%x x%x\n",
7251			irsp->ulpIoTag, irsp->ulpStatus,
7252			irsp->un.ulpWord[4], irsp->ulpTimeout);
7253	if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
7254		lpfc_ct_free_iocb(phba, cmdiocb);
7255	else
7256		lpfc_els_free_iocb(phba, cmdiocb);
7257	return;
7258}
7259
7260/**
7261 * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
7262 * @phba: Pointer to HBA context object.
7263 * @pring: Pointer to driver SLI ring object.
7264 * @cmdiocb: Pointer to driver command iocb object.
7265 *
7266 * This function issues an abort iocb for the provided command
7267 * iocb. This function is called with hbalock held.
7268 * The function returns 0 when it fails due to memory allocation
7269 * failure or when the command iocb is an abort request.
7270 **/
7271int
7272lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
7273			   struct lpfc_iocbq *cmdiocb)
7274{
7275	struct lpfc_vport *vport = cmdiocb->vport;
7276	struct lpfc_iocbq *abtsiocbp;
7277	IOCB_t *icmd = NULL;
7278	IOCB_t *iabt = NULL;
7279	int retval = IOCB_ERROR;
7280
7281	/*
7282	 * There are certain command types we don't want to abort.  And we
7283	 * don't want to abort commands that are already in the process of
7284	 * being aborted.
7285	 */
7286	icmd = &cmdiocb->iocb;
7287	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
7288	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
7289	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
7290		return 0;
7291
7292	/* If we're unloading, don't abort iocb on the ELS ring, but change the
7293	 * callback so that nothing happens when it finishes.
7294	 */
7295	if ((vport->load_flag & FC_UNLOADING) &&
7296	    (pring->ringno == LPFC_ELS_RING)) {
7297		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
7298			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
7299		else
7300			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
7301		goto abort_iotag_exit;
7302	}
7303
7304	/* issue ABTS for this IOCB based on iotag */
7305	abtsiocbp = __lpfc_sli_get_iocbq(phba);
7306	if (abtsiocbp == NULL)
7307		return 0;
7308
7309	/* This signals the response to set the correct status
7310	 * before calling the completion handler
7311	 */
7312	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
7313
7314	iabt = &abtsiocbp->iocb;
7315	iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
7316	iabt->un.acxri.abortContextTag = icmd->ulpContext;
7317	if (phba->sli_rev == LPFC_SLI_REV4) {
7318		iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
7319		iabt->un.acxri.abortContextTag = cmdiocb->iotag;
7320	}
7321	else
7322		iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
7323	iabt->ulpLe = 1;
7324	iabt->ulpClass = icmd->ulpClass;
7325
7326	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
7327	abtsiocbp->fcp_wqidx = cmdiocb->fcp_wqidx;
7328	if (cmdiocb->iocb_flag & LPFC_IO_FCP)
7329		abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
7330
7331	if (phba->link_state >= LPFC_LINK_UP)
7332		iabt->ulpCommand = CMD_ABORT_XRI_CN;
7333	else
7334		iabt->ulpCommand = CMD_CLOSE_XRI_CN;
7335
7336	abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
7337
7338	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
7339			 "0339 Abort xri x%x, original iotag x%x, "
7340			 "abort cmd iotag x%x\n",
7341			 iabt->un.acxri.abortIoTag,
7342			 iabt->un.acxri.abortContextTag,
7343			 abtsiocbp->iotag);
7344	retval = __lpfc_sli_issue_iocb(phba, pring->ringno, abtsiocbp, 0);
7345
7346	if (retval)
7347		__lpfc_sli_release_iocbq(phba, abtsiocbp);
7348abort_iotag_exit:
7349	/*
7350	 * Caller to this routine should check for IOCB_ERROR
7351	 * and handle it properly.  This routine no longer removes
7352	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
7353	 */
7354	return retval;
7355}
7356
7357/**
7358 * lpfc_sli_validate_fcp_iocb - find commands associated with a vport or LUN
7359 * @iocbq: Pointer to driver iocb object.
7360 * @vport: Pointer to driver virtual port object.
7361 * @tgt_id: SCSI ID of the target.
7362 * @lun_id: LUN ID of the scsi device.
7363 * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
7364 *
7365 * This function acts as an iocb filter for functions which abort or count
7366 * all FCP iocbs pending on a lun/SCSI target/SCSI host. It will return
7367 * 0 if the filtering criteria is met for the given iocb and will return
7368 * 1 if the filtering criteria is not met.
7369 * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
7370 * given iocb is for the SCSI device specified by vport, tgt_id and
7371 * lun_id parameter.
7372 * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
7373 * given iocb is for the SCSI target specified by vport and tgt_id
7374 * parameters.
7375 * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
7376 * given iocb is for the SCSI host associated with the given vport.
7377 * This function is called with no locks held.
7378 **/
7379static int
7380lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
7381			   uint16_t tgt_id, uint64_t lun_id,
7382			   lpfc_ctx_cmd ctx_cmd)
7383{
7384	struct lpfc_scsi_buf *lpfc_cmd;
7385	int rc = 1;
7386
7387	if (!(iocbq->iocb_flag &  LPFC_IO_FCP))
7388		return rc;
7389
7390	if (iocbq->vport != vport)
7391		return rc;
7392
7393	lpfc_cmd = container_of(iocbq, struct lpfc_scsi_buf, cur_iocbq);
7394
7395	if (lpfc_cmd->pCmd == NULL)
7396		return rc;
7397
7398	switch (ctx_cmd) {
7399	case LPFC_CTX_LUN:
7400		if ((lpfc_cmd->rdata->pnode) &&
7401		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
7402		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
7403			rc = 0;
7404		break;
7405	case LPFC_CTX_TGT:
7406		if ((lpfc_cmd->rdata->pnode) &&
7407		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
7408			rc = 0;
7409		break;
7410	case LPFC_CTX_HOST:
7411		rc = 0;
7412		break;
7413	default:
7414		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
7415			__func__, ctx_cmd);
7416		break;
7417	}
7418
7419	return rc;
7420}
7421
7422/**
7423 * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
7424 * @vport: Pointer to virtual port.
7425 * @tgt_id: SCSI ID of the target.
7426 * @lun_id: LUN ID of the scsi device.
7427 * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
7428 *
7429 * This function returns number of FCP commands pending for the vport.
7430 * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
7431 * commands pending on the vport associated with SCSI device specified
7432 * by tgt_id and lun_id parameters.
7433 * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
7434 * commands pending on the vport associated with SCSI target specified
7435 * by tgt_id parameter.
7436 * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
7437 * commands pending on the vport.
7438 * This function returns the number of iocbs which satisfy the filter.
7439 * This function is called without any lock held.
7440 **/
7441int
7442lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
7443		  lpfc_ctx_cmd ctx_cmd)
7444{
7445	struct lpfc_hba *phba = vport->phba;
7446	struct lpfc_iocbq *iocbq;
7447	int sum, i;
7448
7449	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
7450		iocbq = phba->sli.iocbq_lookup[i];
7451
7452		if (lpfc_sli_validate_fcp_iocb (iocbq, vport, tgt_id, lun_id,
7453						ctx_cmd) == 0)
7454			sum++;
7455	}
7456
7457	return sum;
7458}
7459
7460/**
7461 * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
7462 * @phba: Pointer to HBA context object
7463 * @cmdiocb: Pointer to command iocb object.
7464 * @rspiocb: Pointer to response iocb object.
7465 *
7466 * This function is called when an aborted FCP iocb completes. This
7467 * function is called by the ring event handler with no lock held.
7468 * This function frees the iocb.
7469 **/
7470void
7471lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
7472			struct lpfc_iocbq *rspiocb)
7473{
7474	lpfc_sli_release_iocbq(phba, cmdiocb);
7475	return;
7476}
7477
7478/**
7479 * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
7480 * @vport: Pointer to virtual port.
7481 * @pring: Pointer to driver SLI ring object.
7482 * @tgt_id: SCSI ID of the target.
7483 * @lun_id: LUN ID of the scsi device.
7484 * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
7485 *
7486 * This function sends an abort command for every SCSI command
7487 * associated with the given virtual port pending on the ring
7488 * filtered by lpfc_sli_validate_fcp_iocb function.
7489 * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
7490 * FCP iocbs associated with lun specified by tgt_id and lun_id
7491 * parameters
7492 * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
7493 * FCP iocbs associated with SCSI target specified by tgt_id parameter.
7494 * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
7495 * FCP iocbs associated with virtual port.
7496 * This function returns number of iocbs it failed to abort.
7497 * This function is called with no locks held.
7498 **/
7499int
7500lpfc_sli_abort_iocb(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
7501		    uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd abort_cmd)
7502{
7503	struct lpfc_hba *phba = vport->phba;
7504	struct lpfc_iocbq *iocbq;
7505	struct lpfc_iocbq *abtsiocb;
7506	IOCB_t *cmd = NULL;
7507	int errcnt = 0, ret_val = 0;
7508	int i;
7509
7510	for (i = 1; i <= phba->sli.last_iotag; i++) {
7511		iocbq = phba->sli.iocbq_lookup[i];
7512
7513		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
7514					       abort_cmd) != 0)
7515			continue;
7516
7517		/* issue ABTS for this IOCB based on iotag */
7518		abtsiocb = lpfc_sli_get_iocbq(phba);
7519		if (abtsiocb == NULL) {
7520			errcnt++;
7521			continue;
7522		}
7523
7524		cmd = &iocbq->iocb;
7525		abtsiocb->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
7526		abtsiocb->iocb.un.acxri.abortContextTag = cmd->ulpContext;
7527		if (phba->sli_rev == LPFC_SLI_REV4)
7528			abtsiocb->iocb.un.acxri.abortIoTag = iocbq->sli4_xritag;
7529		else
7530			abtsiocb->iocb.un.acxri.abortIoTag = cmd->ulpIoTag;
7531		abtsiocb->iocb.ulpLe = 1;
7532		abtsiocb->iocb.ulpClass = cmd->ulpClass;
7533		abtsiocb->vport = phba->pport;
7534
7535		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
7536		abtsiocb->fcp_wqidx = iocbq->fcp_wqidx;
7537		if (iocbq->iocb_flag & LPFC_IO_FCP)
7538			abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
7539
7540		if (lpfc_is_link_up(phba))
7541			abtsiocb->iocb.ulpCommand = CMD_ABORT_XRI_CN;
7542		else
7543			abtsiocb->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
7544
7545		/* Setup callback routine and issue the command. */
7546		abtsiocb->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
7547		ret_val = lpfc_sli_issue_iocb(phba, pring->ringno,
7548					      abtsiocb, 0);
7549		if (ret_val == IOCB_ERROR) {
7550			lpfc_sli_release_iocbq(phba, abtsiocb);
7551			errcnt++;
7552			continue;
7553		}
7554	}
7555
7556	return errcnt;
7557}
7558
7559/**
7560 * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
7561 * @phba: Pointer to HBA context object.
7562 * @cmdiocbq: Pointer to command iocb.
7563 * @rspiocbq: Pointer to response iocb.
7564 *
7565 * This function is the completion handler for iocbs issued using
7566 * lpfc_sli_issue_iocb_wait function. This function is called by the
7567 * ring event handler function without any lock held. This function
7568 * can be called from both worker thread context and interrupt
7569 * context. This function also can be called from other thread which
7570 * cleans up the SLI layer objects.
7571 * This function copy the contents of the response iocb to the
7572 * response iocb memory object provided by the caller of
7573 * lpfc_sli_issue_iocb_wait and then wakes up the thread which
7574 * sleeps for the iocb completion.
7575 **/
7576static void
7577lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
7578			struct lpfc_iocbq *cmdiocbq,
7579			struct lpfc_iocbq *rspiocbq)
7580{
7581	wait_queue_head_t *pdone_q;
7582	unsigned long iflags;
7583	struct lpfc_scsi_buf *lpfc_cmd;
7584
7585	spin_lock_irqsave(&phba->hbalock, iflags);
7586	cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
7587	if (cmdiocbq->context2 && rspiocbq)
7588		memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
7589		       &rspiocbq->iocb, sizeof(IOCB_t));
7590
7591	/* Set the exchange busy flag for task management commands */
7592	if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
7593		!(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
7594		lpfc_cmd = container_of(cmdiocbq, struct lpfc_scsi_buf,
7595			cur_iocbq);
7596		lpfc_cmd->exch_busy = rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY;
7597	}
7598
7599	pdone_q = cmdiocbq->context_un.wait_queue;
7600	if (pdone_q)
7601		wake_up(pdone_q);
7602	spin_unlock_irqrestore(&phba->hbalock, iflags);
7603	return;
7604}
7605
7606/**
7607 * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
7608 * @phba: Pointer to HBA context object..
7609 * @piocbq: Pointer to command iocb.
7610 * @flag: Flag to test.
7611 *
7612 * This routine grabs the hbalock and then test the iocb_flag to
7613 * see if the passed in flag is set.
7614 * Returns:
7615 * 1 if flag is set.
7616 * 0 if flag is not set.
7617 **/
7618static int
7619lpfc_chk_iocb_flg(struct lpfc_hba *phba,
7620		 struct lpfc_iocbq *piocbq, uint32_t flag)
7621{
7622	unsigned long iflags;
7623	int ret;
7624
7625	spin_lock_irqsave(&phba->hbalock, iflags);
7626	ret = piocbq->iocb_flag & flag;
7627	spin_unlock_irqrestore(&phba->hbalock, iflags);
7628	return ret;
7629
7630}
7631
7632/**
7633 * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
7634 * @phba: Pointer to HBA context object..
7635 * @pring: Pointer to sli ring.
7636 * @piocb: Pointer to command iocb.
7637 * @prspiocbq: Pointer to response iocb.
7638 * @timeout: Timeout in number of seconds.
7639 *
7640 * This function issues the iocb to firmware and waits for the
7641 * iocb to complete. If the iocb command is not
7642 * completed within timeout seconds, it returns IOCB_TIMEDOUT.
7643 * Caller should not free the iocb resources if this function
7644 * returns IOCB_TIMEDOUT.
7645 * The function waits for the iocb completion using an
7646 * non-interruptible wait.
7647 * This function will sleep while waiting for iocb completion.
7648 * So, this function should not be called from any context which
7649 * does not allow sleeping. Due to the same reason, this function
7650 * cannot be called with interrupt disabled.
7651 * This function assumes that the iocb completions occur while
7652 * this function sleep. So, this function cannot be called from
7653 * the thread which process iocb completion for this ring.
7654 * This function clears the iocb_flag of the iocb object before
7655 * issuing the iocb and the iocb completion handler sets this
7656 * flag and wakes this thread when the iocb completes.
7657 * The contents of the response iocb will be copied to prspiocbq
7658 * by the completion handler when the command completes.
7659 * This function returns IOCB_SUCCESS when success.
7660 * This function is called with no lock held.
7661 **/
7662int
7663lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
7664			 uint32_t ring_number,
7665			 struct lpfc_iocbq *piocb,
7666			 struct lpfc_iocbq *prspiocbq,
7667			 uint32_t timeout)
7668{
7669	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
7670	long timeleft, timeout_req = 0;
7671	int retval = IOCB_SUCCESS;
7672	uint32_t creg_val;
7673	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
7674	/*
7675	 * If the caller has provided a response iocbq buffer, then context2
7676	 * is NULL or its an error.
7677	 */
7678	if (prspiocbq) {
7679		if (piocb->context2)
7680			return IOCB_ERROR;
7681		piocb->context2 = prspiocbq;
7682	}
7683
7684	piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
7685	piocb->context_un.wait_queue = &done_q;
7686	piocb->iocb_flag &= ~LPFC_IO_WAKE;
7687
7688	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
7689		creg_val = readl(phba->HCregaddr);
7690		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
7691		writel(creg_val, phba->HCregaddr);
7692		readl(phba->HCregaddr); /* flush */
7693	}
7694
7695	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
7696				     SLI_IOCB_RET_IOCB);
7697	if (retval == IOCB_SUCCESS) {
7698		timeout_req = timeout * HZ;
7699		timeleft = wait_event_timeout(done_q,
7700				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
7701				timeout_req);
7702
7703		if (piocb->iocb_flag & LPFC_IO_WAKE) {
7704			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
7705					"0331 IOCB wake signaled\n");
7706		} else if (timeleft == 0) {
7707			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7708					"0338 IOCB wait timeout error - no "
7709					"wake response Data x%x\n", timeout);
7710			retval = IOCB_TIMEDOUT;
7711		} else {
7712			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7713					"0330 IOCB wake NOT set, "
7714					"Data x%x x%lx\n",
7715					timeout, (timeleft / jiffies));
7716			retval = IOCB_TIMEDOUT;
7717		}
7718	} else if (retval == IOCB_BUSY) {
7719		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
7720			"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
7721			phba->iocb_cnt, pring->txq_cnt, pring->txcmplq_cnt);
7722		return retval;
7723	} else {
7724		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
7725				"0332 IOCB wait issue failed, Data x%x\n",
7726				retval);
7727		retval = IOCB_ERROR;
7728	}
7729
7730	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
7731		creg_val = readl(phba->HCregaddr);
7732		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
7733		writel(creg_val, phba->HCregaddr);
7734		readl(phba->HCregaddr); /* flush */
7735	}
7736
7737	if (prspiocbq)
7738		piocb->context2 = NULL;
7739
7740	piocb->context_un.wait_queue = NULL;
7741	piocb->iocb_cmpl = NULL;
7742	return retval;
7743}
7744
7745/**
7746 * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
7747 * @phba: Pointer to HBA context object.
7748 * @pmboxq: Pointer to driver mailbox object.
7749 * @timeout: Timeout in number of seconds.
7750 *
7751 * This function issues the mailbox to firmware and waits for the
7752 * mailbox command to complete. If the mailbox command is not
7753 * completed within timeout seconds, it returns MBX_TIMEOUT.
7754 * The function waits for the mailbox completion using an
7755 * interruptible wait. If the thread is woken up due to a
7756 * signal, MBX_TIMEOUT error is returned to the caller. Caller
7757 * should not free the mailbox resources, if this function returns
7758 * MBX_TIMEOUT.
7759 * This function will sleep while waiting for mailbox completion.
7760 * So, this function should not be called from any context which
7761 * does not allow sleeping. Due to the same reason, this function
7762 * cannot be called with interrupt disabled.
7763 * This function assumes that the mailbox completion occurs while
7764 * this function sleep. So, this function cannot be called from
7765 * the worker thread which processes mailbox completion.
7766 * This function is called in the context of HBA management
7767 * applications.
7768 * This function returns MBX_SUCCESS when successful.
7769 * This function is called with no lock held.
7770 **/
7771int
7772lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
7773			 uint32_t timeout)
7774{
7775	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
7776	int retval;
7777	unsigned long flag;
7778
7779	/* The caller must leave context1 empty. */
7780	if (pmboxq->context1)
7781		return MBX_NOT_FINISHED;
7782
7783	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
7784	/* setup wake call as IOCB callback */
7785	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
7786	/* setup context field to pass wait_queue pointer to wake function  */
7787	pmboxq->context1 = &done_q;
7788
7789	/* now issue the command */
7790	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
7791
7792	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
7793		wait_event_interruptible_timeout(done_q,
7794				pmboxq->mbox_flag & LPFC_MBX_WAKE,
7795				timeout * HZ);
7796
7797		spin_lock_irqsave(&phba->hbalock, flag);
7798		pmboxq->context1 = NULL;
7799		/*
7800		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
7801		 * else do not free the resources.
7802		 */
7803		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
7804			retval = MBX_SUCCESS;
7805			lpfc_sli4_swap_str(phba, pmboxq);
7806		} else {
7807			retval = MBX_TIMEOUT;
7808			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
7809		}
7810		spin_unlock_irqrestore(&phba->hbalock, flag);
7811	}
7812
7813	return retval;
7814}
7815
7816/**
7817 * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
7818 * @phba: Pointer to HBA context.
7819 *
7820 * This function is called to shutdown the driver's mailbox sub-system.
7821 * It first marks the mailbox sub-system is in a block state to prevent
7822 * the asynchronous mailbox command from issued off the pending mailbox
7823 * command queue. If the mailbox command sub-system shutdown is due to
7824 * HBA error conditions such as EEH or ERATT, this routine shall invoke
7825 * the mailbox sub-system flush routine to forcefully bring down the
7826 * mailbox sub-system. Otherwise, if it is due to normal condition (such
7827 * as with offline or HBA function reset), this routine will wait for the
7828 * outstanding mailbox command to complete before invoking the mailbox
7829 * sub-system flush routine to gracefully bring down mailbox sub-system.
7830 **/
7831void
7832lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba)
7833{
7834	struct lpfc_sli *psli = &phba->sli;
7835	uint8_t actcmd = MBX_HEARTBEAT;
7836	unsigned long timeout;
7837
7838	spin_lock_irq(&phba->hbalock);
7839	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
7840	spin_unlock_irq(&phba->hbalock);
7841
7842	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
7843		spin_lock_irq(&phba->hbalock);
7844		if (phba->sli.mbox_active)
7845			actcmd = phba->sli.mbox_active->u.mb.mbxCommand;
7846		spin_unlock_irq(&phba->hbalock);
7847		/* Determine how long we might wait for the active mailbox
7848		 * command to be gracefully completed by firmware.
7849		 */
7850		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, actcmd) *
7851					   1000) + jiffies;
7852		while (phba->sli.mbox_active) {
7853			/* Check active mailbox complete status every 2ms */
7854			msleep(2);
7855			if (time_after(jiffies, timeout))
7856				/* Timeout, let the mailbox flush routine to
7857				 * forcefully release active mailbox command
7858				 */
7859				break;
7860		}
7861	}
7862	lpfc_sli_mbox_sys_flush(phba);
7863}
7864
7865/**
7866 * lpfc_sli_eratt_read - read sli-3 error attention events
7867 * @phba: Pointer to HBA context.
7868 *
7869 * This function is called to read the SLI3 device error attention registers
7870 * for possible error attention events. The caller must hold the hostlock
7871 * with spin_lock_irq().
7872 *
7873 * This fucntion returns 1 when there is Error Attention in the Host Attention
7874 * Register and returns 0 otherwise.
7875 **/
7876static int
7877lpfc_sli_eratt_read(struct lpfc_hba *phba)
7878{
7879	uint32_t ha_copy;
7880
7881	/* Read chip Host Attention (HA) register */
7882	ha_copy = readl(phba->HAregaddr);
7883	if (ha_copy & HA_ERATT) {
7884		/* Read host status register to retrieve error event */
7885		lpfc_sli_read_hs(phba);
7886
7887		/* Check if there is a deferred error condition is active */
7888		if ((HS_FFER1 & phba->work_hs) &&
7889		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
7890		     HS_FFER6 | HS_FFER7) & phba->work_hs)) {
7891			phba->hba_flag |= DEFER_ERATT;
7892			/* Clear all interrupt enable conditions */
7893			writel(0, phba->HCregaddr);
7894			readl(phba->HCregaddr);
7895		}
7896
7897		/* Set the driver HA work bitmap */
7898		phba->work_ha |= HA_ERATT;
7899		/* Indicate polling handles this ERATT */
7900		phba->hba_flag |= HBA_ERATT_HANDLED;
7901		return 1;
7902	}
7903	return 0;
7904}
7905
7906/**
7907 * lpfc_sli4_eratt_read - read sli-4 error attention events
7908 * @phba: Pointer to HBA context.
7909 *
7910 * This function is called to read the SLI4 device error attention registers
7911 * for possible error attention events. The caller must hold the hostlock
7912 * with spin_lock_irq().
7913 *
7914 * This fucntion returns 1 when there is Error Attention in the Host Attention
7915 * Register and returns 0 otherwise.
7916 **/
7917static int
7918lpfc_sli4_eratt_read(struct lpfc_hba *phba)
7919{
7920	uint32_t uerr_sta_hi, uerr_sta_lo;
7921
7922	/* For now, use the SLI4 device internal unrecoverable error
7923	 * registers for error attention. This can be changed later.
7924	 */
7925	uerr_sta_lo = readl(phba->sli4_hba.UERRLOregaddr);
7926	uerr_sta_hi = readl(phba->sli4_hba.UERRHIregaddr);
7927	if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
7928	    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
7929		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7930				"1423 HBA Unrecoverable error: "
7931				"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
7932				"ue_mask_lo_reg=0x%x, ue_mask_hi_reg=0x%x\n",
7933				uerr_sta_lo, uerr_sta_hi,
7934				phba->sli4_hba.ue_mask_lo,
7935				phba->sli4_hba.ue_mask_hi);
7936		phba->work_status[0] = uerr_sta_lo;
7937		phba->work_status[1] = uerr_sta_hi;
7938		/* Set the driver HA work bitmap */
7939		phba->work_ha |= HA_ERATT;
7940		/* Indicate polling handles this ERATT */
7941		phba->hba_flag |= HBA_ERATT_HANDLED;
7942		return 1;
7943	}
7944	return 0;
7945}
7946
7947/**
7948 * lpfc_sli_check_eratt - check error attention events
7949 * @phba: Pointer to HBA context.
7950 *
7951 * This function is called from timer soft interrupt context to check HBA's
7952 * error attention register bit for error attention events.
7953 *
7954 * This fucntion returns 1 when there is Error Attention in the Host Attention
7955 * Register and returns 0 otherwise.
7956 **/
7957int
7958lpfc_sli_check_eratt(struct lpfc_hba *phba)
7959{
7960	uint32_t ha_copy;
7961
7962	/* If somebody is waiting to handle an eratt, don't process it
7963	 * here. The brdkill function will do this.
7964	 */
7965	if (phba->link_flag & LS_IGNORE_ERATT)
7966		return 0;
7967
7968	/* Check if interrupt handler handles this ERATT */
7969	spin_lock_irq(&phba->hbalock);
7970	if (phba->hba_flag & HBA_ERATT_HANDLED) {
7971		/* Interrupt handler has handled ERATT */
7972		spin_unlock_irq(&phba->hbalock);
7973		return 0;
7974	}
7975
7976	/*
7977	 * If there is deferred error attention, do not check for error
7978	 * attention
7979	 */
7980	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
7981		spin_unlock_irq(&phba->hbalock);
7982		return 0;
7983	}
7984
7985	/* If PCI channel is offline, don't process it */
7986	if (unlikely(pci_channel_offline(phba->pcidev))) {
7987		spin_unlock_irq(&phba->hbalock);
7988		return 0;
7989	}
7990
7991	switch (phba->sli_rev) {
7992	case LPFC_SLI_REV2:
7993	case LPFC_SLI_REV3:
7994		/* Read chip Host Attention (HA) register */
7995		ha_copy = lpfc_sli_eratt_read(phba);
7996		break;
7997	case LPFC_SLI_REV4:
7998		/* Read devcie Uncoverable Error (UERR) registers */
7999		ha_copy = lpfc_sli4_eratt_read(phba);
8000		break;
8001	default:
8002		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8003				"0299 Invalid SLI revision (%d)\n",
8004				phba->sli_rev);
8005		ha_copy = 0;
8006		break;
8007	}
8008	spin_unlock_irq(&phba->hbalock);
8009
8010	return ha_copy;
8011}
8012
8013/**
8014 * lpfc_intr_state_check - Check device state for interrupt handling
8015 * @phba: Pointer to HBA context.
8016 *
8017 * This inline routine checks whether a device or its PCI slot is in a state
8018 * that the interrupt should be handled.
8019 *
8020 * This function returns 0 if the device or the PCI slot is in a state that
8021 * interrupt should be handled, otherwise -EIO.
8022 */
8023static inline int
8024lpfc_intr_state_check(struct lpfc_hba *phba)
8025{
8026	/* If the pci channel is offline, ignore all the interrupts */
8027	if (unlikely(pci_channel_offline(phba->pcidev)))
8028		return -EIO;
8029
8030	/* Update device level interrupt statistics */
8031	phba->sli.slistat.sli_intr++;
8032
8033	/* Ignore all interrupts during initialization. */
8034	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
8035		return -EIO;
8036
8037	return 0;
8038}
8039
8040/**
8041 * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
8042 * @irq: Interrupt number.
8043 * @dev_id: The device context pointer.
8044 *
8045 * This function is directly called from the PCI layer as an interrupt
8046 * service routine when device with SLI-3 interface spec is enabled with
8047 * MSI-X multi-message interrupt mode and there are slow-path events in
8048 * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
8049 * interrupt mode, this function is called as part of the device-level
8050 * interrupt handler. When the PCI slot is in error recovery or the HBA
8051 * is undergoing initialization, the interrupt handler will not process
8052 * the interrupt. The link attention and ELS ring attention events are
8053 * handled by the worker thread. The interrupt handler signals the worker
8054 * thread and returns for these events. This function is called without
8055 * any lock held. It gets the hbalock to access and update SLI data
8056 * structures.
8057 *
8058 * This function returns IRQ_HANDLED when interrupt is handled else it
8059 * returns IRQ_NONE.
8060 **/
8061irqreturn_t
8062lpfc_sli_sp_intr_handler(int irq, void *dev_id)
8063{
8064	struct lpfc_hba  *phba;
8065	uint32_t ha_copy, hc_copy;
8066	uint32_t work_ha_copy;
8067	unsigned long status;
8068	unsigned long iflag;
8069	uint32_t control;
8070
8071	MAILBOX_t *mbox, *pmbox;
8072	struct lpfc_vport *vport;
8073	struct lpfc_nodelist *ndlp;
8074	struct lpfc_dmabuf *mp;
8075	LPFC_MBOXQ_t *pmb;
8076	int rc;
8077
8078	/*
8079	 * Get the driver's phba structure from the dev_id and
8080	 * assume the HBA is not interrupting.
8081	 */
8082	phba = (struct lpfc_hba *)dev_id;
8083
8084	if (unlikely(!phba))
8085		return IRQ_NONE;
8086
8087	/*
8088	 * Stuff needs to be attented to when this function is invoked as an
8089	 * individual interrupt handler in MSI-X multi-message interrupt mode
8090	 */
8091	if (phba->intr_type == MSIX) {
8092		/* Check device state for handling interrupt */
8093		if (lpfc_intr_state_check(phba))
8094			return IRQ_NONE;
8095		/* Need to read HA REG for slow-path events */
8096		spin_lock_irqsave(&phba->hbalock, iflag);
8097		ha_copy = readl(phba->HAregaddr);
8098		/* If somebody is waiting to handle an eratt don't process it
8099		 * here. The brdkill function will do this.
8100		 */
8101		if (phba->link_flag & LS_IGNORE_ERATT)
8102			ha_copy &= ~HA_ERATT;
8103		/* Check the need for handling ERATT in interrupt handler */
8104		if (ha_copy & HA_ERATT) {
8105			if (phba->hba_flag & HBA_ERATT_HANDLED)
8106				/* ERATT polling has handled ERATT */
8107				ha_copy &= ~HA_ERATT;
8108			else
8109				/* Indicate interrupt handler handles ERATT */
8110				phba->hba_flag |= HBA_ERATT_HANDLED;
8111		}
8112
8113		/*
8114		 * If there is deferred error attention, do not check for any
8115		 * interrupt.
8116		 */
8117		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
8118			spin_unlock_irqrestore(&phba->hbalock, iflag);
8119			return IRQ_NONE;
8120		}
8121
8122		/* Clear up only attention source related to slow-path */
8123		hc_copy = readl(phba->HCregaddr);
8124		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
8125			HC_LAINT_ENA | HC_ERINT_ENA),
8126			phba->HCregaddr);
8127		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
8128			phba->HAregaddr);
8129		writel(hc_copy, phba->HCregaddr);
8130		readl(phba->HAregaddr); /* flush */
8131		spin_unlock_irqrestore(&phba->hbalock, iflag);
8132	} else
8133		ha_copy = phba->ha_copy;
8134
8135	work_ha_copy = ha_copy & phba->work_ha_mask;
8136
8137	if (work_ha_copy) {
8138		if (work_ha_copy & HA_LATT) {
8139			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
8140				/*
8141				 * Turn off Link Attention interrupts
8142				 * until CLEAR_LA done
8143				 */
8144				spin_lock_irqsave(&phba->hbalock, iflag);
8145				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
8146				control = readl(phba->HCregaddr);
8147				control &= ~HC_LAINT_ENA;
8148				writel(control, phba->HCregaddr);
8149				readl(phba->HCregaddr); /* flush */
8150				spin_unlock_irqrestore(&phba->hbalock, iflag);
8151			}
8152			else
8153				work_ha_copy &= ~HA_LATT;
8154		}
8155
8156		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
8157			/*
8158			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
8159			 * the only slow ring.
8160			 */
8161			status = (work_ha_copy &
8162				(HA_RXMASK  << (4*LPFC_ELS_RING)));
8163			status >>= (4*LPFC_ELS_RING);
8164			if (status & HA_RXMASK) {
8165				spin_lock_irqsave(&phba->hbalock, iflag);
8166				control = readl(phba->HCregaddr);
8167
8168				lpfc_debugfs_slow_ring_trc(phba,
8169				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
8170				control, status,
8171				(uint32_t)phba->sli.slistat.sli_intr);
8172
8173				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
8174					lpfc_debugfs_slow_ring_trc(phba,
8175						"ISR Disable ring:"
8176						"pwork:x%x hawork:x%x wait:x%x",
8177						phba->work_ha, work_ha_copy,
8178						(uint32_t)((unsigned long)
8179						&phba->work_waitq));
8180
8181					control &=
8182					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
8183					writel(control, phba->HCregaddr);
8184					readl(phba->HCregaddr); /* flush */
8185				}
8186				else {
8187					lpfc_debugfs_slow_ring_trc(phba,
8188						"ISR slow ring:   pwork:"
8189						"x%x hawork:x%x wait:x%x",
8190						phba->work_ha, work_ha_copy,
8191						(uint32_t)((unsigned long)
8192						&phba->work_waitq));
8193				}
8194				spin_unlock_irqrestore(&phba->hbalock, iflag);
8195			}
8196		}
8197		spin_lock_irqsave(&phba->hbalock, iflag);
8198		if (work_ha_copy & HA_ERATT) {
8199			lpfc_sli_read_hs(phba);
8200			/*
8201			 * Check if there is a deferred error condition
8202			 * is active
8203			 */
8204			if ((HS_FFER1 & phba->work_hs) &&
8205				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
8206				HS_FFER6 | HS_FFER7) & phba->work_hs)) {
8207				phba->hba_flag |= DEFER_ERATT;
8208				/* Clear all interrupt enable conditions */
8209				writel(0, phba->HCregaddr);
8210				readl(phba->HCregaddr);
8211			}
8212		}
8213
8214		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
8215			pmb = phba->sli.mbox_active;
8216			pmbox = &pmb->u.mb;
8217			mbox = phba->mbox;
8218			vport = pmb->vport;
8219
8220			/* First check out the status word */
8221			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
8222			if (pmbox->mbxOwner != OWN_HOST) {
8223				spin_unlock_irqrestore(&phba->hbalock, iflag);
8224				/*
8225				 * Stray Mailbox Interrupt, mbxCommand <cmd>
8226				 * mbxStatus <status>
8227				 */
8228				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
8229						LOG_SLI,
8230						"(%d):0304 Stray Mailbox "
8231						"Interrupt mbxCommand x%x "
8232						"mbxStatus x%x\n",
8233						(vport ? vport->vpi : 0),
8234						pmbox->mbxCommand,
8235						pmbox->mbxStatus);
8236				/* clear mailbox attention bit */
8237				work_ha_copy &= ~HA_MBATT;
8238			} else {
8239				phba->sli.mbox_active = NULL;
8240				spin_unlock_irqrestore(&phba->hbalock, iflag);
8241				phba->last_completion_time = jiffies;
8242				del_timer(&phba->sli.mbox_tmo);
8243				if (pmb->mbox_cmpl) {
8244					lpfc_sli_pcimem_bcopy(mbox, pmbox,
8245							MAILBOX_CMD_SIZE);
8246					if (pmb->out_ext_byte_len &&
8247						pmb->context2)
8248						lpfc_sli_pcimem_bcopy(
8249						phba->mbox_ext,
8250						pmb->context2,
8251						pmb->out_ext_byte_len);
8252				}
8253				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
8254					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
8255
8256					lpfc_debugfs_disc_trc(vport,
8257						LPFC_DISC_TRC_MBOX_VPORT,
8258						"MBOX dflt rpi: : "
8259						"status:x%x rpi:x%x",
8260						(uint32_t)pmbox->mbxStatus,
8261						pmbox->un.varWords[0], 0);
8262
8263					if (!pmbox->mbxStatus) {
8264						mp = (struct lpfc_dmabuf *)
8265							(pmb->context1);
8266						ndlp = (struct lpfc_nodelist *)
8267							pmb->context2;
8268
8269						/* Reg_LOGIN of dflt RPI was
8270						 * successful. new lets get
8271						 * rid of the RPI using the
8272						 * same mbox buffer.
8273						 */
8274						lpfc_unreg_login(phba,
8275							vport->vpi,
8276							pmbox->un.varWords[0],
8277							pmb);
8278						pmb->mbox_cmpl =
8279							lpfc_mbx_cmpl_dflt_rpi;
8280						pmb->context1 = mp;
8281						pmb->context2 = ndlp;
8282						pmb->vport = vport;
8283						rc = lpfc_sli_issue_mbox(phba,
8284								pmb,
8285								MBX_NOWAIT);
8286						if (rc != MBX_BUSY)
8287							lpfc_printf_log(phba,
8288							KERN_ERR,
8289							LOG_MBOX | LOG_SLI,
8290							"0350 rc should have"
8291							"been MBX_BUSY\n");
8292						if (rc != MBX_NOT_FINISHED)
8293							goto send_current_mbox;
8294					}
8295				}
8296				spin_lock_irqsave(
8297						&phba->pport->work_port_lock,
8298						iflag);
8299				phba->pport->work_port_events &=
8300					~WORKER_MBOX_TMO;
8301				spin_unlock_irqrestore(
8302						&phba->pport->work_port_lock,
8303						iflag);
8304				lpfc_mbox_cmpl_put(phba, pmb);
8305			}
8306		} else
8307			spin_unlock_irqrestore(&phba->hbalock, iflag);
8308
8309		if ((work_ha_copy & HA_MBATT) &&
8310		    (phba->sli.mbox_active == NULL)) {
8311send_current_mbox:
8312			/* Process next mailbox command if there is one */
8313			do {
8314				rc = lpfc_sli_issue_mbox(phba, NULL,
8315							 MBX_NOWAIT);
8316			} while (rc == MBX_NOT_FINISHED);
8317			if (rc != MBX_SUCCESS)
8318				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
8319						LOG_SLI, "0349 rc should be "
8320						"MBX_SUCCESS\n");
8321		}
8322
8323		spin_lock_irqsave(&phba->hbalock, iflag);
8324		phba->work_ha |= work_ha_copy;
8325		spin_unlock_irqrestore(&phba->hbalock, iflag);
8326		lpfc_worker_wake_up(phba);
8327	}
8328	return IRQ_HANDLED;
8329
8330} /* lpfc_sli_sp_intr_handler */
8331
8332/**
8333 * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
8334 * @irq: Interrupt number.
8335 * @dev_id: The device context pointer.
8336 *
8337 * This function is directly called from the PCI layer as an interrupt
8338 * service routine when device with SLI-3 interface spec is enabled with
8339 * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
8340 * ring event in the HBA. However, when the device is enabled with either
8341 * MSI or Pin-IRQ interrupt mode, this function is called as part of the
8342 * device-level interrupt handler. When the PCI slot is in error recovery
8343 * or the HBA is undergoing initialization, the interrupt handler will not
8344 * process the interrupt. The SCSI FCP fast-path ring event are handled in
8345 * the intrrupt context. This function is called without any lock held.
8346 * It gets the hbalock to access and update SLI data structures.
8347 *
8348 * This function returns IRQ_HANDLED when interrupt is handled else it
8349 * returns IRQ_NONE.
8350 **/
8351irqreturn_t
8352lpfc_sli_fp_intr_handler(int irq, void *dev_id)
8353{
8354	struct lpfc_hba  *phba;
8355	uint32_t ha_copy;
8356	unsigned long status;
8357	unsigned long iflag;
8358
8359	/* Get the driver's phba structure from the dev_id and
8360	 * assume the HBA is not interrupting.
8361	 */
8362	phba = (struct lpfc_hba *) dev_id;
8363
8364	if (unlikely(!phba))
8365		return IRQ_NONE;
8366
8367	/*
8368	 * Stuff needs to be attented to when this function is invoked as an
8369	 * individual interrupt handler in MSI-X multi-message interrupt mode
8370	 */
8371	if (phba->intr_type == MSIX) {
8372		/* Check device state for handling interrupt */
8373		if (lpfc_intr_state_check(phba))
8374			return IRQ_NONE;
8375		/* Need to read HA REG for FCP ring and other ring events */
8376		ha_copy = readl(phba->HAregaddr);
8377		/* Clear up only attention source related to fast-path */
8378		spin_lock_irqsave(&phba->hbalock, iflag);
8379		/*
8380		 * If there is deferred error attention, do not check for
8381		 * any interrupt.
8382		 */
8383		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
8384			spin_unlock_irqrestore(&phba->hbalock, iflag);
8385			return IRQ_NONE;
8386		}
8387		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
8388			phba->HAregaddr);
8389		readl(phba->HAregaddr); /* flush */
8390		spin_unlock_irqrestore(&phba->hbalock, iflag);
8391	} else
8392		ha_copy = phba->ha_copy;
8393
8394	/*
8395	 * Process all events on FCP ring. Take the optimized path for FCP IO.
8396	 */
8397	ha_copy &= ~(phba->work_ha_mask);
8398
8399	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
8400	status >>= (4*LPFC_FCP_RING);
8401	if (status & HA_RXMASK)
8402		lpfc_sli_handle_fast_ring_event(phba,
8403						&phba->sli.ring[LPFC_FCP_RING],
8404						status);
8405
8406	if (phba->cfg_multi_ring_support == 2) {
8407		/*
8408		 * Process all events on extra ring. Take the optimized path
8409		 * for extra ring IO.
8410		 */
8411		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
8412		status >>= (4*LPFC_EXTRA_RING);
8413		if (status & HA_RXMASK) {
8414			lpfc_sli_handle_fast_ring_event(phba,
8415					&phba->sli.ring[LPFC_EXTRA_RING],
8416					status);
8417		}
8418	}
8419	return IRQ_HANDLED;
8420}  /* lpfc_sli_fp_intr_handler */
8421
8422/**
8423 * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
8424 * @irq: Interrupt number.
8425 * @dev_id: The device context pointer.
8426 *
8427 * This function is the HBA device-level interrupt handler to device with
8428 * SLI-3 interface spec, called from the PCI layer when either MSI or
8429 * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
8430 * requires driver attention. This function invokes the slow-path interrupt
8431 * attention handling function and fast-path interrupt attention handling
8432 * function in turn to process the relevant HBA attention events. This
8433 * function is called without any lock held. It gets the hbalock to access
8434 * and update SLI data structures.
8435 *
8436 * This function returns IRQ_HANDLED when interrupt is handled, else it
8437 * returns IRQ_NONE.
8438 **/
8439irqreturn_t
8440lpfc_sli_intr_handler(int irq, void *dev_id)
8441{
8442	struct lpfc_hba  *phba;
8443	irqreturn_t sp_irq_rc, fp_irq_rc;
8444	unsigned long status1, status2;
8445	uint32_t hc_copy;
8446
8447	/*
8448	 * Get the driver's phba structure from the dev_id and
8449	 * assume the HBA is not interrupting.
8450	 */
8451	phba = (struct lpfc_hba *) dev_id;
8452
8453	if (unlikely(!phba))
8454		return IRQ_NONE;
8455
8456	/* Check device state for handling interrupt */
8457	if (lpfc_intr_state_check(phba))
8458		return IRQ_NONE;
8459
8460	spin_lock(&phba->hbalock);
8461	phba->ha_copy = readl(phba->HAregaddr);
8462	if (unlikely(!phba->ha_copy)) {
8463		spin_unlock(&phba->hbalock);
8464		return IRQ_NONE;
8465	} else if (phba->ha_copy & HA_ERATT) {
8466		if (phba->hba_flag & HBA_ERATT_HANDLED)
8467			/* ERATT polling has handled ERATT */
8468			phba->ha_copy &= ~HA_ERATT;
8469		else
8470			/* Indicate interrupt handler handles ERATT */
8471			phba->hba_flag |= HBA_ERATT_HANDLED;
8472	}
8473
8474	/*
8475	 * If there is deferred error attention, do not check for any interrupt.
8476	 */
8477	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
8478		spin_unlock_irq(&phba->hbalock);
8479		return IRQ_NONE;
8480	}
8481
8482	/* Clear attention sources except link and error attentions */
8483	hc_copy = readl(phba->HCregaddr);
8484	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
8485		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
8486		phba->HCregaddr);
8487	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
8488	writel(hc_copy, phba->HCregaddr);
8489	readl(phba->HAregaddr); /* flush */
8490	spin_unlock(&phba->hbalock);
8491
8492	/*
8493	 * Invokes slow-path host attention interrupt handling as appropriate.
8494	 */
8495
8496	/* status of events with mailbox and link attention */
8497	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
8498
8499	/* status of events with ELS ring */
8500	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
8501	status2 >>= (4*LPFC_ELS_RING);
8502
8503	if (status1 || (status2 & HA_RXMASK))
8504		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
8505	else
8506		sp_irq_rc = IRQ_NONE;
8507
8508	/*
8509	 * Invoke fast-path host attention interrupt handling as appropriate.
8510	 */
8511
8512	/* status of events with FCP ring */
8513	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
8514	status1 >>= (4*LPFC_FCP_RING);
8515
8516	/* status of events with extra ring */
8517	if (phba->cfg_multi_ring_support == 2) {
8518		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
8519		status2 >>= (4*LPFC_EXTRA_RING);
8520	} else
8521		status2 = 0;
8522
8523	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
8524		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
8525	else
8526		fp_irq_rc = IRQ_NONE;
8527
8528	/* Return device-level interrupt handling status */
8529	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
8530}  /* lpfc_sli_intr_handler */
8531
8532/**
8533 * lpfc_sli4_fcp_xri_abort_event_proc - Process fcp xri abort event
8534 * @phba: pointer to lpfc hba data structure.
8535 *
8536 * This routine is invoked by the worker thread to process all the pending
8537 * SLI4 FCP abort XRI events.
8538 **/
8539void lpfc_sli4_fcp_xri_abort_event_proc(struct lpfc_hba *phba)
8540{
8541	struct lpfc_cq_event *cq_event;
8542
8543	/* First, declare the fcp xri abort event has been handled */
8544	spin_lock_irq(&phba->hbalock);
8545	phba->hba_flag &= ~FCP_XRI_ABORT_EVENT;
8546	spin_unlock_irq(&phba->hbalock);
8547	/* Now, handle all the fcp xri abort events */
8548	while (!list_empty(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue)) {
8549		/* Get the first event from the head of the event queue */
8550		spin_lock_irq(&phba->hbalock);
8551		list_remove_head(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue,
8552				 cq_event, struct lpfc_cq_event, list);
8553		spin_unlock_irq(&phba->hbalock);
8554		/* Notify aborted XRI for FCP work queue */
8555		lpfc_sli4_fcp_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
8556		/* Free the event processed back to the free pool */
8557		lpfc_sli4_cq_event_release(phba, cq_event);
8558	}
8559}
8560
8561/**
8562 * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
8563 * @phba: pointer to lpfc hba data structure.
8564 *
8565 * This routine is invoked by the worker thread to process all the pending
8566 * SLI4 els abort xri events.
8567 **/
8568void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
8569{
8570	struct lpfc_cq_event *cq_event;
8571
8572	/* First, declare the els xri abort event has been handled */
8573	spin_lock_irq(&phba->hbalock);
8574	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
8575	spin_unlock_irq(&phba->hbalock);
8576	/* Now, handle all the els xri abort events */
8577	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
8578		/* Get the first event from the head of the event queue */
8579		spin_lock_irq(&phba->hbalock);
8580		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
8581				 cq_event, struct lpfc_cq_event, list);
8582		spin_unlock_irq(&phba->hbalock);
8583		/* Notify aborted XRI for ELS work queue */
8584		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
8585		/* Free the event processed back to the free pool */
8586		lpfc_sli4_cq_event_release(phba, cq_event);
8587	}
8588}
8589
8590/**
8591 * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
8592 * @phba: pointer to lpfc hba data structure
8593 * @pIocbIn: pointer to the rspiocbq
8594 * @pIocbOut: pointer to the cmdiocbq
8595 * @wcqe: pointer to the complete wcqe
8596 *
8597 * This routine transfers the fields of a command iocbq to a response iocbq
8598 * by copying all the IOCB fields from command iocbq and transferring the
8599 * completion status information from the complete wcqe.
8600 **/
8601static void
8602lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
8603			      struct lpfc_iocbq *pIocbIn,
8604			      struct lpfc_iocbq *pIocbOut,
8605			      struct lpfc_wcqe_complete *wcqe)
8606{
8607	unsigned long iflags;
8608	size_t offset = offsetof(struct lpfc_iocbq, iocb);
8609
8610	memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
8611	       sizeof(struct lpfc_iocbq) - offset);
8612	/* Map WCQE parameters into irspiocb parameters */
8613	pIocbIn->iocb.ulpStatus = bf_get(lpfc_wcqe_c_status, wcqe);
8614	if (pIocbOut->iocb_flag & LPFC_IO_FCP)
8615		if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
8616			pIocbIn->iocb.un.fcpi.fcpi_parm =
8617					pIocbOut->iocb.un.fcpi.fcpi_parm -
8618					wcqe->total_data_placed;
8619		else
8620			pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
8621	else {
8622		pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
8623		pIocbIn->iocb.un.genreq64.bdl.bdeSize = wcqe->total_data_placed;
8624	}
8625
8626	/* Pick up HBA exchange busy condition */
8627	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
8628		spin_lock_irqsave(&phba->hbalock, iflags);
8629		pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
8630		spin_unlock_irqrestore(&phba->hbalock, iflags);
8631	}
8632}
8633
8634/**
8635 * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
8636 * @phba: Pointer to HBA context object.
8637 * @wcqe: Pointer to work-queue completion queue entry.
8638 *
8639 * This routine handles an ELS work-queue completion event and construct
8640 * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
8641 * discovery engine to handle.
8642 *
8643 * Return: Pointer to the receive IOCBQ, NULL otherwise.
8644 **/
8645static struct lpfc_iocbq *
8646lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
8647			       struct lpfc_iocbq *irspiocbq)
8648{
8649	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
8650	struct lpfc_iocbq *cmdiocbq;
8651	struct lpfc_wcqe_complete *wcqe;
8652	unsigned long iflags;
8653
8654	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
8655	spin_lock_irqsave(&phba->hbalock, iflags);
8656	pring->stats.iocb_event++;
8657	/* Look up the ELS command IOCB and create pseudo response IOCB */
8658	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
8659				bf_get(lpfc_wcqe_c_request_tag, wcqe));
8660	spin_unlock_irqrestore(&phba->hbalock, iflags);
8661
8662	if (unlikely(!cmdiocbq)) {
8663		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
8664				"0386 ELS complete with no corresponding "
8665				"cmdiocb: iotag (%d)\n",
8666				bf_get(lpfc_wcqe_c_request_tag, wcqe));
8667		lpfc_sli_release_iocbq(phba, irspiocbq);
8668		return NULL;
8669	}
8670
8671	/* Fake the irspiocbq and copy necessary response information */
8672	lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
8673
8674	return irspiocbq;
8675}
8676
8677/**
8678 * lpfc_sli4_sp_handle_async_event - Handle an asynchroous event
8679 * @phba: Pointer to HBA context object.
8680 * @cqe: Pointer to mailbox completion queue entry.
8681 *
8682 * This routine process a mailbox completion queue entry with asynchrous
8683 * event.
8684 *
8685 * Return: true if work posted to worker thread, otherwise false.
8686 **/
8687static bool
8688lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
8689{
8690	struct lpfc_cq_event *cq_event;
8691	unsigned long iflags;
8692
8693	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
8694			"0392 Async Event: word0:x%x, word1:x%x, "
8695			"word2:x%x, word3:x%x\n", mcqe->word0,
8696			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
8697
8698	/* Allocate a new internal CQ_EVENT entry */
8699	cq_event = lpfc_sli4_cq_event_alloc(phba);
8700	if (!cq_event) {
8701		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8702				"0394 Failed to allocate CQ_EVENT entry\n");
8703		return false;
8704	}
8705
8706	/* Move the CQE into an asynchronous event entry */
8707	memcpy(&cq_event->cqe, mcqe, sizeof(struct lpfc_mcqe));
8708	spin_lock_irqsave(&phba->hbalock, iflags);
8709	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
8710	/* Set the async event flag */
8711	phba->hba_flag |= ASYNC_EVENT;
8712	spin_unlock_irqrestore(&phba->hbalock, iflags);
8713
8714	return true;
8715}
8716
8717/**
8718 * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
8719 * @phba: Pointer to HBA context object.
8720 * @cqe: Pointer to mailbox completion queue entry.
8721 *
8722 * This routine process a mailbox completion queue entry with mailbox
8723 * completion event.
8724 *
8725 * Return: true if work posted to worker thread, otherwise false.
8726 **/
8727static bool
8728lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
8729{
8730	uint32_t mcqe_status;
8731	MAILBOX_t *mbox, *pmbox;
8732	struct lpfc_mqe *mqe;
8733	struct lpfc_vport *vport;
8734	struct lpfc_nodelist *ndlp;
8735	struct lpfc_dmabuf *mp;
8736	unsigned long iflags;
8737	LPFC_MBOXQ_t *pmb;
8738	bool workposted = false;
8739	int rc;
8740
8741	/* If not a mailbox complete MCQE, out by checking mailbox consume */
8742	if (!bf_get(lpfc_trailer_completed, mcqe))
8743		goto out_no_mqe_complete;
8744
8745	/* Get the reference to the active mbox command */
8746	spin_lock_irqsave(&phba->hbalock, iflags);
8747	pmb = phba->sli.mbox_active;
8748	if (unlikely(!pmb)) {
8749		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
8750				"1832 No pending MBOX command to handle\n");
8751		spin_unlock_irqrestore(&phba->hbalock, iflags);
8752		goto out_no_mqe_complete;
8753	}
8754	spin_unlock_irqrestore(&phba->hbalock, iflags);
8755	mqe = &pmb->u.mqe;
8756	pmbox = (MAILBOX_t *)&pmb->u.mqe;
8757	mbox = phba->mbox;
8758	vport = pmb->vport;
8759
8760	/* Reset heartbeat timer */
8761	phba->last_completion_time = jiffies;
8762	del_timer(&phba->sli.mbox_tmo);
8763
8764	/* Move mbox data to caller's mailbox region, do endian swapping */
8765	if (pmb->mbox_cmpl && mbox)
8766		lpfc_sli_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
8767	/* Set the mailbox status with SLI4 range 0x4000 */
8768	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
8769	if (mcqe_status != MB_CQE_STATUS_SUCCESS)
8770		bf_set(lpfc_mqe_status, mqe,
8771		       (LPFC_MBX_ERROR_RANGE | mcqe_status));
8772
8773	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
8774		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
8775		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
8776				      "MBOX dflt rpi: status:x%x rpi:x%x",
8777				      mcqe_status,
8778				      pmbox->un.varWords[0], 0);
8779		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
8780			mp = (struct lpfc_dmabuf *)(pmb->context1);
8781			ndlp = (struct lpfc_nodelist *)pmb->context2;
8782			/* Reg_LOGIN of dflt RPI was successful. Now lets get
8783			 * RID of the PPI using the same mbox buffer.
8784			 */
8785			lpfc_unreg_login(phba, vport->vpi,
8786					 pmbox->un.varWords[0], pmb);
8787			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
8788			pmb->context1 = mp;
8789			pmb->context2 = ndlp;
8790			pmb->vport = vport;
8791			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
8792			if (rc != MBX_BUSY)
8793				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
8794						LOG_SLI, "0385 rc should "
8795						"have been MBX_BUSY\n");
8796			if (rc != MBX_NOT_FINISHED)
8797				goto send_current_mbox;
8798		}
8799	}
8800	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
8801	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
8802	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
8803
8804	/* There is mailbox completion work to do */
8805	spin_lock_irqsave(&phba->hbalock, iflags);
8806	__lpfc_mbox_cmpl_put(phba, pmb);
8807	phba->work_ha |= HA_MBATT;
8808	spin_unlock_irqrestore(&phba->hbalock, iflags);
8809	workposted = true;
8810
8811send_current_mbox:
8812	spin_lock_irqsave(&phba->hbalock, iflags);
8813	/* Release the mailbox command posting token */
8814	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8815	/* Setting active mailbox pointer need to be in sync to flag clear */
8816	phba->sli.mbox_active = NULL;
8817	spin_unlock_irqrestore(&phba->hbalock, iflags);
8818	/* Wake up worker thread to post the next pending mailbox command */
8819	lpfc_worker_wake_up(phba);
8820out_no_mqe_complete:
8821	if (bf_get(lpfc_trailer_consumed, mcqe))
8822		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
8823	return workposted;
8824}
8825
8826/**
8827 * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
8828 * @phba: Pointer to HBA context object.
8829 * @cqe: Pointer to mailbox completion queue entry.
8830 *
8831 * This routine process a mailbox completion queue entry, it invokes the
8832 * proper mailbox complete handling or asynchrous event handling routine
8833 * according to the MCQE's async bit.
8834 *
8835 * Return: true if work posted to worker thread, otherwise false.
8836 **/
8837static bool
8838lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_cqe *cqe)
8839{
8840	struct lpfc_mcqe mcqe;
8841	bool workposted;
8842
8843	/* Copy the mailbox MCQE and convert endian order as needed */
8844	lpfc_sli_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
8845
8846	/* Invoke the proper event handling routine */
8847	if (!bf_get(lpfc_trailer_async, &mcqe))
8848		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
8849	else
8850		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
8851	return workposted;
8852}
8853
8854/**
8855 * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
8856 * @phba: Pointer to HBA context object.
8857 * @wcqe: Pointer to work-queue completion queue entry.
8858 *
8859 * This routine handles an ELS work-queue completion event.
8860 *
8861 * Return: true if work posted to worker thread, otherwise false.
8862 **/
8863static bool
8864lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba,
8865			     struct lpfc_wcqe_complete *wcqe)
8866{
8867	struct lpfc_iocbq *irspiocbq;
8868	unsigned long iflags;
8869	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_FCP_RING];
8870
8871	/* Get an irspiocbq for later ELS response processing use */
8872	irspiocbq = lpfc_sli_get_iocbq(phba);
8873	if (!irspiocbq) {
8874		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8875			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
8876			"fcp_txcmplq_cnt=%d, els_txcmplq_cnt=%d\n",
8877			pring->txq_cnt, phba->iocb_cnt,
8878			phba->sli.ring[LPFC_FCP_RING].txcmplq_cnt,
8879			phba->sli.ring[LPFC_ELS_RING].txcmplq_cnt);
8880		return false;
8881	}
8882
8883	/* Save off the slow-path queue event for work thread to process */
8884	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
8885	spin_lock_irqsave(&phba->hbalock, iflags);
8886	list_add_tail(&irspiocbq->cq_event.list,
8887		      &phba->sli4_hba.sp_queue_event);
8888	phba->hba_flag |= HBA_SP_QUEUE_EVT;
8889	spin_unlock_irqrestore(&phba->hbalock, iflags);
8890
8891	return true;
8892}
8893
8894/**
8895 * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
8896 * @phba: Pointer to HBA context object.
8897 * @wcqe: Pointer to work-queue completion queue entry.
8898 *
8899 * This routine handles slow-path WQ entry comsumed event by invoking the
8900 * proper WQ release routine to the slow-path WQ.
8901 **/
8902static void
8903lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
8904			     struct lpfc_wcqe_release *wcqe)
8905{
8906	/* Check for the slow-path ELS work queue */
8907	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
8908		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
8909				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
8910	else
8911		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
8912				"2579 Slow-path wqe consume event carries "
8913				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
8914				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
8915				phba->sli4_hba.els_wq->queue_id);
8916}
8917
8918/**
8919 * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
8920 * @phba: Pointer to HBA context object.
8921 * @cq: Pointer to a WQ completion queue.
8922 * @wcqe: Pointer to work-queue completion queue entry.
8923 *
8924 * This routine handles an XRI abort event.
8925 *
8926 * Return: true if work posted to worker thread, otherwise false.
8927 **/
8928static bool
8929lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
8930				   struct lpfc_queue *cq,
8931				   struct sli4_wcqe_xri_aborted *wcqe)
8932{
8933	bool workposted = false;
8934	struct lpfc_cq_event *cq_event;
8935	unsigned long iflags;
8936
8937	/* Allocate a new internal CQ_EVENT entry */
8938	cq_event = lpfc_sli4_cq_event_alloc(phba);
8939	if (!cq_event) {
8940		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8941				"0602 Failed to allocate CQ_EVENT entry\n");
8942		return false;
8943	}
8944
8945	/* Move the CQE into the proper xri abort event list */
8946	memcpy(&cq_event->cqe, wcqe, sizeof(struct sli4_wcqe_xri_aborted));
8947	switch (cq->subtype) {
8948	case LPFC_FCP:
8949		spin_lock_irqsave(&phba->hbalock, iflags);
8950		list_add_tail(&cq_event->list,
8951			      &phba->sli4_hba.sp_fcp_xri_aborted_work_queue);
8952		/* Set the fcp xri abort event flag */
8953		phba->hba_flag |= FCP_XRI_ABORT_EVENT;
8954		spin_unlock_irqrestore(&phba->hbalock, iflags);
8955		workposted = true;
8956		break;
8957	case LPFC_ELS:
8958		spin_lock_irqsave(&phba->hbalock, iflags);
8959		list_add_tail(&cq_event->list,
8960			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
8961		/* Set the els xri abort event flag */
8962		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
8963		spin_unlock_irqrestore(&phba->hbalock, iflags);
8964		workposted = true;
8965		break;
8966	default:
8967		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8968				"0603 Invalid work queue CQE subtype (x%x)\n",
8969				cq->subtype);
8970		workposted = false;
8971		break;
8972	}
8973	return workposted;
8974}
8975
8976/**
8977 * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
8978 * @phba: Pointer to HBA context object.
8979 * @rcqe: Pointer to receive-queue completion queue entry.
8980 *
8981 * This routine process a receive-queue completion queue entry.
8982 *
8983 * Return: true if work posted to worker thread, otherwise false.
8984 **/
8985static bool
8986lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
8987{
8988	bool workposted = false;
8989	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
8990	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
8991	struct hbq_dmabuf *dma_buf;
8992	uint32_t status;
8993	unsigned long iflags;
8994
8995	if (bf_get(lpfc_rcqe_rq_id, rcqe) != hrq->queue_id)
8996		goto out;
8997
8998	status = bf_get(lpfc_rcqe_status, rcqe);
8999	switch (status) {
9000	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
9001		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9002				"2537 Receive Frame Truncated!!\n");
9003	case FC_STATUS_RQ_SUCCESS:
9004		lpfc_sli4_rq_release(hrq, drq);
9005		spin_lock_irqsave(&phba->hbalock, iflags);
9006		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
9007		if (!dma_buf) {
9008			spin_unlock_irqrestore(&phba->hbalock, iflags);
9009			goto out;
9010		}
9011		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
9012		/* save off the frame for the word thread to process */
9013		list_add_tail(&dma_buf->cq_event.list,
9014			      &phba->sli4_hba.sp_queue_event);
9015		/* Frame received */
9016		phba->hba_flag |= HBA_SP_QUEUE_EVT;
9017		spin_unlock_irqrestore(&phba->hbalock, iflags);
9018		workposted = true;
9019		break;
9020	case FC_STATUS_INSUFF_BUF_NEED_BUF:
9021	case FC_STATUS_INSUFF_BUF_FRM_DISC:
9022		/* Post more buffers if possible */
9023		spin_lock_irqsave(&phba->hbalock, iflags);
9024		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
9025		spin_unlock_irqrestore(&phba->hbalock, iflags);
9026		workposted = true;
9027		break;
9028	}
9029out:
9030	return workposted;
9031}
9032
9033/**
9034 * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
9035 * @phba: Pointer to HBA context object.
9036 * @cq: Pointer to the completion queue.
9037 * @wcqe: Pointer to a completion queue entry.
9038 *
9039 * This routine process a slow-path work-queue or recieve queue completion queue
9040 * entry.
9041 *
9042 * Return: true if work posted to worker thread, otherwise false.
9043 **/
9044static bool
9045lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
9046			 struct lpfc_cqe *cqe)
9047{
9048	struct lpfc_cqe cqevt;
9049	bool workposted = false;
9050
9051	/* Copy the work queue CQE and convert endian order if needed */
9052	lpfc_sli_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
9053
9054	/* Check and process for different type of WCQE and dispatch */
9055	switch (bf_get(lpfc_cqe_code, &cqevt)) {
9056	case CQE_CODE_COMPL_WQE:
9057		/* Process the WQ/RQ complete event */
9058		phba->last_completion_time = jiffies;
9059		workposted = lpfc_sli4_sp_handle_els_wcqe(phba,
9060				(struct lpfc_wcqe_complete *)&cqevt);
9061		break;
9062	case CQE_CODE_RELEASE_WQE:
9063		/* Process the WQ release event */
9064		lpfc_sli4_sp_handle_rel_wcqe(phba,
9065				(struct lpfc_wcqe_release *)&cqevt);
9066		break;
9067	case CQE_CODE_XRI_ABORTED:
9068		/* Process the WQ XRI abort event */
9069		phba->last_completion_time = jiffies;
9070		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
9071				(struct sli4_wcqe_xri_aborted *)&cqevt);
9072		break;
9073	case CQE_CODE_RECEIVE:
9074		/* Process the RQ event */
9075		phba->last_completion_time = jiffies;
9076		workposted = lpfc_sli4_sp_handle_rcqe(phba,
9077				(struct lpfc_rcqe *)&cqevt);
9078		break;
9079	default:
9080		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9081				"0388 Not a valid WCQE code: x%x\n",
9082				bf_get(lpfc_cqe_code, &cqevt));
9083		break;
9084	}
9085	return workposted;
9086}
9087
9088/**
9089 * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
9090 * @phba: Pointer to HBA context object.
9091 * @eqe: Pointer to fast-path event queue entry.
9092 *
9093 * This routine process a event queue entry from the slow-path event queue.
9094 * It will check the MajorCode and MinorCode to determine this is for a
9095 * completion event on a completion queue, if not, an error shall be logged
9096 * and just return. Otherwise, it will get to the corresponding completion
9097 * queue and process all the entries on that completion queue, rearm the
9098 * completion queue, and then return.
9099 *
9100 **/
9101static void
9102lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe)
9103{
9104	struct lpfc_queue *cq = NULL, *childq, *speq;
9105	struct lpfc_cqe *cqe;
9106	bool workposted = false;
9107	int ecount = 0;
9108	uint16_t cqid;
9109
9110	if (bf_get_le32(lpfc_eqe_major_code, eqe) != 0) {
9111		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9112				"0359 Not a valid slow-path completion "
9113				"event: majorcode=x%x, minorcode=x%x\n",
9114				bf_get_le32(lpfc_eqe_major_code, eqe),
9115				bf_get_le32(lpfc_eqe_minor_code, eqe));
9116		return;
9117	}
9118
9119	/* Get the reference to the corresponding CQ */
9120	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
9121
9122	/* Search for completion queue pointer matching this cqid */
9123	speq = phba->sli4_hba.sp_eq;
9124	list_for_each_entry(childq, &speq->child_list, list) {
9125		if (childq->queue_id == cqid) {
9126			cq = childq;
9127			break;
9128		}
9129	}
9130	if (unlikely(!cq)) {
9131		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
9132			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9133					"0365 Slow-path CQ identifier "
9134					"(%d) does not exist\n", cqid);
9135		return;
9136	}
9137
9138	/* Process all the entries to the CQ */
9139	switch (cq->type) {
9140	case LPFC_MCQ:
9141		while ((cqe = lpfc_sli4_cq_get(cq))) {
9142			workposted |= lpfc_sli4_sp_handle_mcqe(phba, cqe);
9143			if (!(++ecount % LPFC_GET_QE_REL_INT))
9144				lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
9145		}
9146		break;
9147	case LPFC_WCQ:
9148		while ((cqe = lpfc_sli4_cq_get(cq))) {
9149			workposted |= lpfc_sli4_sp_handle_cqe(phba, cq, cqe);
9150			if (!(++ecount % LPFC_GET_QE_REL_INT))
9151				lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
9152		}
9153		break;
9154	default:
9155		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9156				"0370 Invalid completion queue type (%d)\n",
9157				cq->type);
9158		return;
9159	}
9160
9161	/* Catch the no cq entry condition, log an error */
9162	if (unlikely(ecount == 0))
9163		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9164				"0371 No entry from the CQ: identifier "
9165				"(x%x), type (%d)\n", cq->queue_id, cq->type);
9166
9167	/* In any case, flash and re-arm the RCQ */
9168	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
9169
9170	/* wake up worker thread if there are works to be done */
9171	if (workposted)
9172		lpfc_worker_wake_up(phba);
9173}
9174
9175/**
9176 * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
9177 * @eqe: Pointer to fast-path completion queue entry.
9178 *
9179 * This routine process a fast-path work queue completion entry from fast-path
9180 * event queue for FCP command response completion.
9181 **/
9182static void
9183lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba,
9184			     struct lpfc_wcqe_complete *wcqe)
9185{
9186	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_FCP_RING];
9187	struct lpfc_iocbq *cmdiocbq;
9188	struct lpfc_iocbq irspiocbq;
9189	unsigned long iflags;
9190
9191	spin_lock_irqsave(&phba->hbalock, iflags);
9192	pring->stats.iocb_event++;
9193	spin_unlock_irqrestore(&phba->hbalock, iflags);
9194
9195	/* Check for response status */
9196	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
9197		/* If resource errors reported from HBA, reduce queue
9198		 * depth of the SCSI device.
9199		 */
9200		if ((bf_get(lpfc_wcqe_c_status, wcqe) ==
9201		     IOSTAT_LOCAL_REJECT) &&
9202		    (wcqe->parameter == IOERR_NO_RESOURCES)) {
9203			phba->lpfc_rampdown_queue_depth(phba);
9204		}
9205		/* Log the error status */
9206		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9207				"0373 FCP complete error: status=x%x, "
9208				"hw_status=x%x, total_data_specified=%d, "
9209				"parameter=x%x, word3=x%x\n",
9210				bf_get(lpfc_wcqe_c_status, wcqe),
9211				bf_get(lpfc_wcqe_c_hw_status, wcqe),
9212				wcqe->total_data_placed, wcqe->parameter,
9213				wcqe->word3);
9214	}
9215
9216	/* Look up the FCP command IOCB and create pseudo response IOCB */
9217	spin_lock_irqsave(&phba->hbalock, iflags);
9218	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
9219				bf_get(lpfc_wcqe_c_request_tag, wcqe));
9220	spin_unlock_irqrestore(&phba->hbalock, iflags);
9221	if (unlikely(!cmdiocbq)) {
9222		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9223				"0374 FCP complete with no corresponding "
9224				"cmdiocb: iotag (%d)\n",
9225				bf_get(lpfc_wcqe_c_request_tag, wcqe));
9226		return;
9227	}
9228	if (unlikely(!cmdiocbq->iocb_cmpl)) {
9229		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9230				"0375 FCP cmdiocb not callback function "
9231				"iotag: (%d)\n",
9232				bf_get(lpfc_wcqe_c_request_tag, wcqe));
9233		return;
9234	}
9235
9236	/* Fake the irspiocb and copy necessary response information */
9237	lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
9238
9239	if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
9240		spin_lock_irqsave(&phba->hbalock, iflags);
9241		cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
9242		spin_unlock_irqrestore(&phba->hbalock, iflags);
9243	}
9244
9245	/* Pass the cmd_iocb and the rsp state to the upper layer */
9246	(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
9247}
9248
9249/**
9250 * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
9251 * @phba: Pointer to HBA context object.
9252 * @cq: Pointer to completion queue.
9253 * @wcqe: Pointer to work-queue completion queue entry.
9254 *
9255 * This routine handles an fast-path WQ entry comsumed event by invoking the
9256 * proper WQ release routine to the slow-path WQ.
9257 **/
9258static void
9259lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
9260			     struct lpfc_wcqe_release *wcqe)
9261{
9262	struct lpfc_queue *childwq;
9263	bool wqid_matched = false;
9264	uint16_t fcp_wqid;
9265
9266	/* Check for fast-path FCP work queue release */
9267	fcp_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
9268	list_for_each_entry(childwq, &cq->child_list, list) {
9269		if (childwq->queue_id == fcp_wqid) {
9270			lpfc_sli4_wq_release(childwq,
9271					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
9272			wqid_matched = true;
9273			break;
9274		}
9275	}
9276	/* Report warning log message if no match found */
9277	if (wqid_matched != true)
9278		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9279				"2580 Fast-path wqe consume event carries "
9280				"miss-matched qid: wcqe-qid=x%x\n", fcp_wqid);
9281}
9282
9283/**
9284 * lpfc_sli4_fp_handle_wcqe - Process fast-path work queue completion entry
9285 * @cq: Pointer to the completion queue.
9286 * @eqe: Pointer to fast-path completion queue entry.
9287 *
9288 * This routine process a fast-path work queue completion entry from fast-path
9289 * event queue for FCP command response completion.
9290 **/
9291static int
9292lpfc_sli4_fp_handle_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
9293			 struct lpfc_cqe *cqe)
9294{
9295	struct lpfc_wcqe_release wcqe;
9296	bool workposted = false;
9297
9298	/* Copy the work queue CQE and convert endian order if needed */
9299	lpfc_sli_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
9300
9301	/* Check and process for different type of WCQE and dispatch */
9302	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
9303	case CQE_CODE_COMPL_WQE:
9304		/* Process the WQ complete event */
9305		phba->last_completion_time = jiffies;
9306		lpfc_sli4_fp_handle_fcp_wcqe(phba,
9307				(struct lpfc_wcqe_complete *)&wcqe);
9308		break;
9309	case CQE_CODE_RELEASE_WQE:
9310		/* Process the WQ release event */
9311		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
9312				(struct lpfc_wcqe_release *)&wcqe);
9313		break;
9314	case CQE_CODE_XRI_ABORTED:
9315		/* Process the WQ XRI abort event */
9316		phba->last_completion_time = jiffies;
9317		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
9318				(struct sli4_wcqe_xri_aborted *)&wcqe);
9319		break;
9320	default:
9321		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9322				"0144 Not a valid WCQE code: x%x\n",
9323				bf_get(lpfc_wcqe_c_code, &wcqe));
9324		break;
9325	}
9326	return workposted;
9327}
9328
9329/**
9330 * lpfc_sli4_fp_handle_eqe - Process a fast-path event queue entry
9331 * @phba: Pointer to HBA context object.
9332 * @eqe: Pointer to fast-path event queue entry.
9333 *
9334 * This routine process a event queue entry from the fast-path event queue.
9335 * It will check the MajorCode and MinorCode to determine this is for a
9336 * completion event on a completion queue, if not, an error shall be logged
9337 * and just return. Otherwise, it will get to the corresponding completion
9338 * queue and process all the entries on the completion queue, rearm the
9339 * completion queue, and then return.
9340 **/
9341static void
9342lpfc_sli4_fp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
9343			uint32_t fcp_cqidx)
9344{
9345	struct lpfc_queue *cq;
9346	struct lpfc_cqe *cqe;
9347	bool workposted = false;
9348	uint16_t cqid;
9349	int ecount = 0;
9350
9351	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
9352		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9353				"0366 Not a valid fast-path completion "
9354				"event: majorcode=x%x, minorcode=x%x\n",
9355				bf_get_le32(lpfc_eqe_major_code, eqe),
9356				bf_get_le32(lpfc_eqe_minor_code, eqe));
9357		return;
9358	}
9359
9360	cq = phba->sli4_hba.fcp_cq[fcp_cqidx];
9361	if (unlikely(!cq)) {
9362		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
9363			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9364					"0367 Fast-path completion queue "
9365					"does not exist\n");
9366		return;
9367	}
9368
9369	/* Get the reference to the corresponding CQ */
9370	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
9371	if (unlikely(cqid != cq->queue_id)) {
9372		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9373				"0368 Miss-matched fast-path completion "
9374				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
9375				cqid, cq->queue_id);
9376		return;
9377	}
9378
9379	/* Process all the entries to the CQ */
9380	while ((cqe = lpfc_sli4_cq_get(cq))) {
9381		workposted |= lpfc_sli4_fp_handle_wcqe(phba, cq, cqe);
9382		if (!(++ecount % LPFC_GET_QE_REL_INT))
9383			lpfc_sli4_cq_release(cq, LPFC_QUEUE_NOARM);
9384	}
9385
9386	/* Catch the no cq entry condition */
9387	if (unlikely(ecount == 0))
9388		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9389				"0369 No entry from fast-path completion "
9390				"queue fcpcqid=%d\n", cq->queue_id);
9391
9392	/* In any case, flash and re-arm the CQ */
9393	lpfc_sli4_cq_release(cq, LPFC_QUEUE_REARM);
9394
9395	/* wake up worker thread if there are works to be done */
9396	if (workposted)
9397		lpfc_worker_wake_up(phba);
9398}
9399
9400static void
9401lpfc_sli4_eq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
9402{
9403	struct lpfc_eqe *eqe;
9404
9405	/* walk all the EQ entries and drop on the floor */
9406	while ((eqe = lpfc_sli4_eq_get(eq)))
9407		;
9408
9409	/* Clear and re-arm the EQ */
9410	lpfc_sli4_eq_release(eq, LPFC_QUEUE_REARM);
9411}
9412
9413/**
9414 * lpfc_sli4_sp_intr_handler - Slow-path interrupt handler to SLI-4 device
9415 * @irq: Interrupt number.
9416 * @dev_id: The device context pointer.
9417 *
9418 * This function is directly called from the PCI layer as an interrupt
9419 * service routine when device with SLI-4 interface spec is enabled with
9420 * MSI-X multi-message interrupt mode and there are slow-path events in
9421 * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
9422 * interrupt mode, this function is called as part of the device-level
9423 * interrupt handler. When the PCI slot is in error recovery or the HBA is
9424 * undergoing initialization, the interrupt handler will not process the
9425 * interrupt. The link attention and ELS ring attention events are handled
9426 * by the worker thread. The interrupt handler signals the worker thread
9427 * and returns for these events. This function is called without any lock
9428 * held. It gets the hbalock to access and update SLI data structures.
9429 *
9430 * This function returns IRQ_HANDLED when interrupt is handled else it
9431 * returns IRQ_NONE.
9432 **/
9433irqreturn_t
9434lpfc_sli4_sp_intr_handler(int irq, void *dev_id)
9435{
9436	struct lpfc_hba *phba;
9437	struct lpfc_queue *speq;
9438	struct lpfc_eqe *eqe;
9439	unsigned long iflag;
9440	int ecount = 0;
9441
9442	/*
9443	 * Get the driver's phba structure from the dev_id
9444	 */
9445	phba = (struct lpfc_hba *)dev_id;
9446
9447	if (unlikely(!phba))
9448		return IRQ_NONE;
9449
9450	/* Get to the EQ struct associated with this vector */
9451	speq = phba->sli4_hba.sp_eq;
9452
9453	/* Check device state for handling interrupt */
9454	if (unlikely(lpfc_intr_state_check(phba))) {
9455		/* Check again for link_state with lock held */
9456		spin_lock_irqsave(&phba->hbalock, iflag);
9457		if (phba->link_state < LPFC_LINK_DOWN)
9458			/* Flush, clear interrupt, and rearm the EQ */
9459			lpfc_sli4_eq_flush(phba, speq);
9460		spin_unlock_irqrestore(&phba->hbalock, iflag);
9461		return IRQ_NONE;
9462	}
9463
9464	/*
9465	 * Process all the event on FCP slow-path EQ
9466	 */
9467	while ((eqe = lpfc_sli4_eq_get(speq))) {
9468		lpfc_sli4_sp_handle_eqe(phba, eqe);
9469		if (!(++ecount % LPFC_GET_QE_REL_INT))
9470			lpfc_sli4_eq_release(speq, LPFC_QUEUE_NOARM);
9471	}
9472
9473	/* Always clear and re-arm the slow-path EQ */
9474	lpfc_sli4_eq_release(speq, LPFC_QUEUE_REARM);
9475
9476	/* Catch the no cq entry condition */
9477	if (unlikely(ecount == 0)) {
9478		if (phba->intr_type == MSIX)
9479			/* MSI-X treated interrupt served as no EQ share INT */
9480			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9481					"0357 MSI-X interrupt with no EQE\n");
9482		else
9483			/* Non MSI-X treated on interrupt as EQ share INT */
9484			return IRQ_NONE;
9485	}
9486
9487	return IRQ_HANDLED;
9488} /* lpfc_sli4_sp_intr_handler */
9489
9490/**
9491 * lpfc_sli4_fp_intr_handler - Fast-path interrupt handler to SLI-4 device
9492 * @irq: Interrupt number.
9493 * @dev_id: The device context pointer.
9494 *
9495 * This function is directly called from the PCI layer as an interrupt
9496 * service routine when device with SLI-4 interface spec is enabled with
9497 * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
9498 * ring event in the HBA. However, when the device is enabled with either
9499 * MSI or Pin-IRQ interrupt mode, this function is called as part of the
9500 * device-level interrupt handler. When the PCI slot is in error recovery
9501 * or the HBA is undergoing initialization, the interrupt handler will not
9502 * process the interrupt. The SCSI FCP fast-path ring event are handled in
9503 * the intrrupt context. This function is called without any lock held.
9504 * It gets the hbalock to access and update SLI data structures. Note that,
9505 * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
9506 * equal to that of FCP CQ index.
9507 *
9508 * This function returns IRQ_HANDLED when interrupt is handled else it
9509 * returns IRQ_NONE.
9510 **/
9511irqreturn_t
9512lpfc_sli4_fp_intr_handler(int irq, void *dev_id)
9513{
9514	struct lpfc_hba *phba;
9515	struct lpfc_fcp_eq_hdl *fcp_eq_hdl;
9516	struct lpfc_queue *fpeq;
9517	struct lpfc_eqe *eqe;
9518	unsigned long iflag;
9519	int ecount = 0;
9520	uint32_t fcp_eqidx;
9521
9522	/* Get the driver's phba structure from the dev_id */
9523	fcp_eq_hdl = (struct lpfc_fcp_eq_hdl *)dev_id;
9524	phba = fcp_eq_hdl->phba;
9525	fcp_eqidx = fcp_eq_hdl->idx;
9526
9527	if (unlikely(!phba))
9528		return IRQ_NONE;
9529
9530	/* Get to the EQ struct associated with this vector */
9531	fpeq = phba->sli4_hba.fp_eq[fcp_eqidx];
9532
9533	/* Check device state for handling interrupt */
9534	if (unlikely(lpfc_intr_state_check(phba))) {
9535		/* Check again for link_state with lock held */
9536		spin_lock_irqsave(&phba->hbalock, iflag);
9537		if (phba->link_state < LPFC_LINK_DOWN)
9538			/* Flush, clear interrupt, and rearm the EQ */
9539			lpfc_sli4_eq_flush(phba, fpeq);
9540		spin_unlock_irqrestore(&phba->hbalock, iflag);
9541		return IRQ_NONE;
9542	}
9543
9544	/*
9545	 * Process all the event on FCP fast-path EQ
9546	 */
9547	while ((eqe = lpfc_sli4_eq_get(fpeq))) {
9548		lpfc_sli4_fp_handle_eqe(phba, eqe, fcp_eqidx);
9549		if (!(++ecount % LPFC_GET_QE_REL_INT))
9550			lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_NOARM);
9551	}
9552
9553	/* Always clear and re-arm the fast-path EQ */
9554	lpfc_sli4_eq_release(fpeq, LPFC_QUEUE_REARM);
9555
9556	if (unlikely(ecount == 0)) {
9557		if (phba->intr_type == MSIX)
9558			/* MSI-X treated interrupt served as no EQ share INT */
9559			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
9560					"0358 MSI-X interrupt with no EQE\n");
9561		else
9562			/* Non MSI-X treated on interrupt as EQ share INT */
9563			return IRQ_NONE;
9564	}
9565
9566	return IRQ_HANDLED;
9567} /* lpfc_sli4_fp_intr_handler */
9568
9569/**
9570 * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
9571 * @irq: Interrupt number.
9572 * @dev_id: The device context pointer.
9573 *
9574 * This function is the device-level interrupt handler to device with SLI-4
9575 * interface spec, called from the PCI layer when either MSI or Pin-IRQ
9576 * interrupt mode is enabled and there is an event in the HBA which requires
9577 * driver attention. This function invokes the slow-path interrupt attention
9578 * handling function and fast-path interrupt attention handling function in
9579 * turn to process the relevant HBA attention events. This function is called
9580 * without any lock held. It gets the hbalock to access and update SLI data
9581 * structures.
9582 *
9583 * This function returns IRQ_HANDLED when interrupt is handled, else it
9584 * returns IRQ_NONE.
9585 **/
9586irqreturn_t
9587lpfc_sli4_intr_handler(int irq, void *dev_id)
9588{
9589	struct lpfc_hba  *phba;
9590	irqreturn_t sp_irq_rc, fp_irq_rc;
9591	bool fp_handled = false;
9592	uint32_t fcp_eqidx;
9593
9594	/* Get the driver's phba structure from the dev_id */
9595	phba = (struct lpfc_hba *)dev_id;
9596
9597	if (unlikely(!phba))
9598		return IRQ_NONE;
9599
9600	/*
9601	 * Invokes slow-path host attention interrupt handling as appropriate.
9602	 */
9603	sp_irq_rc = lpfc_sli4_sp_intr_handler(irq, dev_id);
9604
9605	/*
9606	 * Invoke fast-path host attention interrupt handling as appropriate.
9607	 */
9608	for (fcp_eqidx = 0; fcp_eqidx < phba->cfg_fcp_eq_count; fcp_eqidx++) {
9609		fp_irq_rc = lpfc_sli4_fp_intr_handler(irq,
9610					&phba->sli4_hba.fcp_eq_hdl[fcp_eqidx]);
9611		if (fp_irq_rc == IRQ_HANDLED)
9612			fp_handled |= true;
9613	}
9614
9615	return (fp_handled == true) ? IRQ_HANDLED : sp_irq_rc;
9616} /* lpfc_sli4_intr_handler */
9617
9618/**
9619 * lpfc_sli4_queue_free - free a queue structure and associated memory
9620 * @queue: The queue structure to free.
9621 *
9622 * This function frees a queue structure and the DMAable memeory used for
9623 * the host resident queue. This function must be called after destroying the
9624 * queue on the HBA.
9625 **/
9626void
9627lpfc_sli4_queue_free(struct lpfc_queue *queue)
9628{
9629	struct lpfc_dmabuf *dmabuf;
9630
9631	if (!queue)
9632		return;
9633
9634	while (!list_empty(&queue->page_list)) {
9635		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
9636				 list);
9637		dma_free_coherent(&queue->phba->pcidev->dev, SLI4_PAGE_SIZE,
9638				  dmabuf->virt, dmabuf->phys);
9639		kfree(dmabuf);
9640	}
9641	kfree(queue);
9642	return;
9643}
9644
9645/**
9646 * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
9647 * @phba: The HBA that this queue is being created on.
9648 * @entry_size: The size of each queue entry for this queue.
9649 * @entry count: The number of entries that this queue will handle.
9650 *
9651 * This function allocates a queue structure and the DMAable memory used for
9652 * the host resident queue. This function must be called before creating the
9653 * queue on the HBA.
9654 **/
9655struct lpfc_queue *
9656lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t entry_size,
9657		      uint32_t entry_count)
9658{
9659	struct lpfc_queue *queue;
9660	struct lpfc_dmabuf *dmabuf;
9661	int x, total_qe_count;
9662	void *dma_pointer;
9663	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
9664
9665	if (!phba->sli4_hba.pc_sli4_params.supported)
9666		hw_page_size = SLI4_PAGE_SIZE;
9667
9668	queue = kzalloc(sizeof(struct lpfc_queue) +
9669			(sizeof(union sli4_qe) * entry_count), GFP_KERNEL);
9670	if (!queue)
9671		return NULL;
9672	queue->page_count = (ALIGN(entry_size * entry_count,
9673			hw_page_size))/hw_page_size;
9674	INIT_LIST_HEAD(&queue->list);
9675	INIT_LIST_HEAD(&queue->page_list);
9676	INIT_LIST_HEAD(&queue->child_list);
9677	for (x = 0, total_qe_count = 0; x < queue->page_count; x++) {
9678		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
9679		if (!dmabuf)
9680			goto out_fail;
9681		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
9682						  hw_page_size, &dmabuf->phys,
9683						  GFP_KERNEL);
9684		if (!dmabuf->virt) {
9685			kfree(dmabuf);
9686			goto out_fail;
9687		}
9688		memset(dmabuf->virt, 0, hw_page_size);
9689		dmabuf->buffer_tag = x;
9690		list_add_tail(&dmabuf->list, &queue->page_list);
9691		/* initialize queue's entry array */
9692		dma_pointer = dmabuf->virt;
9693		for (; total_qe_count < entry_count &&
9694		     dma_pointer < (hw_page_size + dmabuf->virt);
9695		     total_qe_count++, dma_pointer += entry_size) {
9696			queue->qe[total_qe_count].address = dma_pointer;
9697		}
9698	}
9699	queue->entry_size = entry_size;
9700	queue->entry_count = entry_count;
9701	queue->phba = phba;
9702
9703	return queue;
9704out_fail:
9705	lpfc_sli4_queue_free(queue);
9706	return NULL;
9707}
9708
9709/**
9710 * lpfc_eq_create - Create an Event Queue on the HBA
9711 * @phba: HBA structure that indicates port to create a queue on.
9712 * @eq: The queue structure to use to create the event queue.
9713 * @imax: The maximum interrupt per second limit.
9714 *
9715 * This function creates an event queue, as detailed in @eq, on a port,
9716 * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
9717 *
9718 * The @phba struct is used to send mailbox command to HBA. The @eq struct
9719 * is used to get the entry count and entry size that are necessary to
9720 * determine the number of pages to allocate and use for this queue. This
9721 * function will send the EQ_CREATE mailbox command to the HBA to setup the
9722 * event queue. This function is asynchronous and will wait for the mailbox
9723 * command to finish before continuing.
9724 *
9725 * On success this function will return a zero. If unable to allocate enough
9726 * memory this function will return ENOMEM. If the queue create mailbox command
9727 * fails this function will return ENXIO.
9728 **/
9729uint32_t
9730lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint16_t imax)
9731{
9732	struct lpfc_mbx_eq_create *eq_create;
9733	LPFC_MBOXQ_t *mbox;
9734	int rc, length, status = 0;
9735	struct lpfc_dmabuf *dmabuf;
9736	uint32_t shdr_status, shdr_add_status;
9737	union lpfc_sli4_cfg_shdr *shdr;
9738	uint16_t dmult;
9739	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
9740
9741	if (!phba->sli4_hba.pc_sli4_params.supported)
9742		hw_page_size = SLI4_PAGE_SIZE;
9743
9744	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
9745	if (!mbox)
9746		return -ENOMEM;
9747	length = (sizeof(struct lpfc_mbx_eq_create) -
9748		  sizeof(struct lpfc_sli4_cfg_mhdr));
9749	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
9750			 LPFC_MBOX_OPCODE_EQ_CREATE,
9751			 length, LPFC_SLI4_MBX_EMBED);
9752	eq_create = &mbox->u.mqe.un.eq_create;
9753	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
9754	       eq->page_count);
9755	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
9756	       LPFC_EQE_SIZE);
9757	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
9758	/* Calculate delay multiper from maximum interrupt per second */
9759	dmult = LPFC_DMULT_CONST/imax - 1;
9760	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
9761	       dmult);
9762	switch (eq->entry_count) {
9763	default:
9764		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9765				"0360 Unsupported EQ count. (%d)\n",
9766				eq->entry_count);
9767		if (eq->entry_count < 256)
9768			return -EINVAL;
9769		/* otherwise default to smallest count (drop through) */
9770	case 256:
9771		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
9772		       LPFC_EQ_CNT_256);
9773		break;
9774	case 512:
9775		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
9776		       LPFC_EQ_CNT_512);
9777		break;
9778	case 1024:
9779		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
9780		       LPFC_EQ_CNT_1024);
9781		break;
9782	case 2048:
9783		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
9784		       LPFC_EQ_CNT_2048);
9785		break;
9786	case 4096:
9787		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
9788		       LPFC_EQ_CNT_4096);
9789		break;
9790	}
9791	list_for_each_entry(dmabuf, &eq->page_list, list) {
9792		memset(dmabuf->virt, 0, hw_page_size);
9793		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
9794					putPaddrLow(dmabuf->phys);
9795		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
9796					putPaddrHigh(dmabuf->phys);
9797	}
9798	mbox->vport = phba->pport;
9799	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
9800	mbox->context1 = NULL;
9801	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
9802	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
9803	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
9804	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
9805	if (shdr_status || shdr_add_status || rc) {
9806		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9807				"2500 EQ_CREATE mailbox failed with "
9808				"status x%x add_status x%x, mbx status x%x\n",
9809				shdr_status, shdr_add_status, rc);
9810		status = -ENXIO;
9811	}
9812	eq->type = LPFC_EQ;
9813	eq->subtype = LPFC_NONE;
9814	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
9815	if (eq->queue_id == 0xFFFF)
9816		status = -ENXIO;
9817	eq->host_index = 0;
9818	eq->hba_index = 0;
9819
9820	mempool_free(mbox, phba->mbox_mem_pool);
9821	return status;
9822}
9823
9824/**
9825 * lpfc_cq_create - Create a Completion Queue on the HBA
9826 * @phba: HBA structure that indicates port to create a queue on.
9827 * @cq: The queue structure to use to create the completion queue.
9828 * @eq: The event queue to bind this completion queue to.
9829 *
9830 * This function creates a completion queue, as detailed in @wq, on a port,
9831 * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
9832 *
9833 * The @phba struct is used to send mailbox command to HBA. The @cq struct
9834 * is used to get the entry count and entry size that are necessary to
9835 * determine the number of pages to allocate and use for this queue. The @eq
9836 * is used to indicate which event queue to bind this completion queue to. This
9837 * function will send the CQ_CREATE mailbox command to the HBA to setup the
9838 * completion queue. This function is asynchronous and will wait for the mailbox
9839 * command to finish before continuing.
9840 *
9841 * On success this function will return a zero. If unable to allocate enough
9842 * memory this function will return ENOMEM. If the queue create mailbox command
9843 * fails this function will return ENXIO.
9844 **/
9845uint32_t
9846lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
9847	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
9848{
9849	struct lpfc_mbx_cq_create *cq_create;
9850	struct lpfc_dmabuf *dmabuf;
9851	LPFC_MBOXQ_t *mbox;
9852	int rc, length, status = 0;
9853	uint32_t shdr_status, shdr_add_status;
9854	union lpfc_sli4_cfg_shdr *shdr;
9855	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
9856
9857	if (!phba->sli4_hba.pc_sli4_params.supported)
9858		hw_page_size = SLI4_PAGE_SIZE;
9859
9860
9861	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
9862	if (!mbox)
9863		return -ENOMEM;
9864	length = (sizeof(struct lpfc_mbx_cq_create) -
9865		  sizeof(struct lpfc_sli4_cfg_mhdr));
9866	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
9867			 LPFC_MBOX_OPCODE_CQ_CREATE,
9868			 length, LPFC_SLI4_MBX_EMBED);
9869	cq_create = &mbox->u.mqe.un.cq_create;
9870	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
9871		    cq->page_count);
9872	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
9873	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
9874	bf_set(lpfc_cq_eq_id, &cq_create->u.request.context, eq->queue_id);
9875	switch (cq->entry_count) {
9876	default:
9877		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9878				"0361 Unsupported CQ count. (%d)\n",
9879				cq->entry_count);
9880		if (cq->entry_count < 256)
9881			return -EINVAL;
9882		/* otherwise default to smallest count (drop through) */
9883	case 256:
9884		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
9885		       LPFC_CQ_CNT_256);
9886		break;
9887	case 512:
9888		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
9889		       LPFC_CQ_CNT_512);
9890		break;
9891	case 1024:
9892		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
9893		       LPFC_CQ_CNT_1024);
9894		break;
9895	}
9896	list_for_each_entry(dmabuf, &cq->page_list, list) {
9897		memset(dmabuf->virt, 0, hw_page_size);
9898		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
9899					putPaddrLow(dmabuf->phys);
9900		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
9901					putPaddrHigh(dmabuf->phys);
9902	}
9903	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
9904
9905	/* The IOCTL status is embedded in the mailbox subheader. */
9906	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
9907	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
9908	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
9909	if (shdr_status || shdr_add_status || rc) {
9910		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9911				"2501 CQ_CREATE mailbox failed with "
9912				"status x%x add_status x%x, mbx status x%x\n",
9913				shdr_status, shdr_add_status, rc);
9914		status = -ENXIO;
9915		goto out;
9916	}
9917	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
9918	if (cq->queue_id == 0xFFFF) {
9919		status = -ENXIO;
9920		goto out;
9921	}
9922	/* link the cq onto the parent eq child list */
9923	list_add_tail(&cq->list, &eq->child_list);
9924	/* Set up completion queue's type and subtype */
9925	cq->type = type;
9926	cq->subtype = subtype;
9927	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
9928	cq->host_index = 0;
9929	cq->hba_index = 0;
9930
9931out:
9932	mempool_free(mbox, phba->mbox_mem_pool);
9933	return status;
9934}
9935
9936/**
9937 * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
9938 * @phba: HBA structure that indicates port to create a queue on.
9939 * @mq: The queue structure to use to create the mailbox queue.
9940 * @mbox: An allocated pointer to type LPFC_MBOXQ_t
9941 * @cq: The completion queue to associate with this cq.
9942 *
9943 * This function provides failback (fb) functionality when the
9944 * mq_create_ext fails on older FW generations.  It's purpose is identical
9945 * to mq_create_ext otherwise.
9946 *
9947 * This routine cannot fail as all attributes were previously accessed and
9948 * initialized in mq_create_ext.
9949 **/
9950static void
9951lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
9952		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
9953{
9954	struct lpfc_mbx_mq_create *mq_create;
9955	struct lpfc_dmabuf *dmabuf;
9956	int length;
9957
9958	length = (sizeof(struct lpfc_mbx_mq_create) -
9959		  sizeof(struct lpfc_sli4_cfg_mhdr));
9960	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
9961			 LPFC_MBOX_OPCODE_MQ_CREATE,
9962			 length, LPFC_SLI4_MBX_EMBED);
9963	mq_create = &mbox->u.mqe.un.mq_create;
9964	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
9965	       mq->page_count);
9966	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
9967	       cq->queue_id);
9968	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
9969	switch (mq->entry_count) {
9970	case 16:
9971		bf_set(lpfc_mq_context_count, &mq_create->u.request.context,
9972		       LPFC_MQ_CNT_16);
9973		break;
9974	case 32:
9975		bf_set(lpfc_mq_context_count, &mq_create->u.request.context,
9976		       LPFC_MQ_CNT_32);
9977		break;
9978	case 64:
9979		bf_set(lpfc_mq_context_count, &mq_create->u.request.context,
9980		       LPFC_MQ_CNT_64);
9981		break;
9982	case 128:
9983		bf_set(lpfc_mq_context_count, &mq_create->u.request.context,
9984		       LPFC_MQ_CNT_128);
9985		break;
9986	}
9987	list_for_each_entry(dmabuf, &mq->page_list, list) {
9988		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
9989			putPaddrLow(dmabuf->phys);
9990		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
9991			putPaddrHigh(dmabuf->phys);
9992	}
9993}
9994
9995/**
9996 * lpfc_mq_create - Create a mailbox Queue on the HBA
9997 * @phba: HBA structure that indicates port to create a queue on.
9998 * @mq: The queue structure to use to create the mailbox queue.
9999 * @cq: The completion queue to associate with this cq.
10000 * @subtype: The queue's subtype.
10001 *
10002 * This function creates a mailbox queue, as detailed in @mq, on a port,
10003 * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
10004 *
10005 * The @phba struct is used to send mailbox command to HBA. The @cq struct
10006 * is used to get the entry count and entry size that are necessary to
10007 * determine the number of pages to allocate and use for this queue. This
10008 * function will send the MQ_CREATE mailbox command to the HBA to setup the
10009 * mailbox queue. This function is asynchronous and will wait for the mailbox
10010 * command to finish before continuing.
10011 *
10012 * On success this function will return a zero. If unable to allocate enough
10013 * memory this function will return ENOMEM. If the queue create mailbox command
10014 * fails this function will return ENXIO.
10015 **/
10016int32_t
10017lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
10018	       struct lpfc_queue *cq, uint32_t subtype)
10019{
10020	struct lpfc_mbx_mq_create *mq_create;
10021	struct lpfc_mbx_mq_create_ext *mq_create_ext;
10022	struct lpfc_dmabuf *dmabuf;
10023	LPFC_MBOXQ_t *mbox;
10024	int rc, length, status = 0;
10025	uint32_t shdr_status, shdr_add_status;
10026	union lpfc_sli4_cfg_shdr *shdr;
10027	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
10028
10029	if (!phba->sli4_hba.pc_sli4_params.supported)
10030		hw_page_size = SLI4_PAGE_SIZE;
10031
10032	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
10033	if (!mbox)
10034		return -ENOMEM;
10035	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
10036		  sizeof(struct lpfc_sli4_cfg_mhdr));
10037	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
10038			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
10039			 length, LPFC_SLI4_MBX_EMBED);
10040
10041	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
10042	bf_set(lpfc_mbx_mq_create_ext_num_pages, &mq_create_ext->u.request,
10043		    mq->page_count);
10044	bf_set(lpfc_mbx_mq_create_ext_async_evt_link, &mq_create_ext->u.request,
10045	       1);
10046	bf_set(lpfc_mbx_mq_create_ext_async_evt_fcfste,
10047	       &mq_create_ext->u.request, 1);
10048	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
10049	       &mq_create_ext->u.request, 1);
10050	bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
10051	       cq->queue_id);
10052	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
10053	switch (mq->entry_count) {
10054	default:
10055		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10056				"0362 Unsupported MQ count. (%d)\n",
10057				mq->entry_count);
10058		if (mq->entry_count < 16)
10059			return -EINVAL;
10060		/* otherwise default to smallest count (drop through) */
10061	case 16:
10062		bf_set(lpfc_mq_context_count, &mq_create_ext->u.request.context,
10063		       LPFC_MQ_CNT_16);
10064		break;
10065	case 32:
10066		bf_set(lpfc_mq_context_count, &mq_create_ext->u.request.context,
10067		       LPFC_MQ_CNT_32);
10068		break;
10069	case 64:
10070		bf_set(lpfc_mq_context_count, &mq_create_ext->u.request.context,
10071		       LPFC_MQ_CNT_64);
10072		break;
10073	case 128:
10074		bf_set(lpfc_mq_context_count, &mq_create_ext->u.request.context,
10075		       LPFC_MQ_CNT_128);
10076		break;
10077	}
10078	list_for_each_entry(dmabuf, &mq->page_list, list) {
10079		memset(dmabuf->virt, 0, hw_page_size);
10080		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
10081					putPaddrLow(dmabuf->phys);
10082		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
10083					putPaddrHigh(dmabuf->phys);
10084	}
10085	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
10086	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
10087	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
10088			      &mq_create_ext->u.response);
10089	if (rc != MBX_SUCCESS) {
10090		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
10091				"2795 MQ_CREATE_EXT failed with "
10092				"status x%x. Failback to MQ_CREATE.\n",
10093				rc);
10094		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
10095		mq_create = &mbox->u.mqe.un.mq_create;
10096		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
10097		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
10098		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
10099				      &mq_create->u.response);
10100	}
10101
10102	/* The IOCTL status is embedded in the mailbox subheader. */
10103	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10104	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10105	if (shdr_status || shdr_add_status || rc) {
10106		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10107				"2502 MQ_CREATE mailbox failed with "
10108				"status x%x add_status x%x, mbx status x%x\n",
10109				shdr_status, shdr_add_status, rc);
10110		status = -ENXIO;
10111		goto out;
10112	}
10113	if (mq->queue_id == 0xFFFF) {
10114		status = -ENXIO;
10115		goto out;
10116	}
10117	mq->type = LPFC_MQ;
10118	mq->subtype = subtype;
10119	mq->host_index = 0;
10120	mq->hba_index = 0;
10121
10122	/* link the mq onto the parent cq child list */
10123	list_add_tail(&mq->list, &cq->child_list);
10124out:
10125	mempool_free(mbox, phba->mbox_mem_pool);
10126	return status;
10127}
10128
10129/**
10130 * lpfc_wq_create - Create a Work Queue on the HBA
10131 * @phba: HBA structure that indicates port to create a queue on.
10132 * @wq: The queue structure to use to create the work queue.
10133 * @cq: The completion queue to bind this work queue to.
10134 * @subtype: The subtype of the work queue indicating its functionality.
10135 *
10136 * This function creates a work queue, as detailed in @wq, on a port, described
10137 * by @phba by sending a WQ_CREATE mailbox command to the HBA.
10138 *
10139 * The @phba struct is used to send mailbox command to HBA. The @wq struct
10140 * is used to get the entry count and entry size that are necessary to
10141 * determine the number of pages to allocate and use for this queue. The @cq
10142 * is used to indicate which completion queue to bind this work queue to. This
10143 * function will send the WQ_CREATE mailbox command to the HBA to setup the
10144 * work queue. This function is asynchronous and will wait for the mailbox
10145 * command to finish before continuing.
10146 *
10147 * On success this function will return a zero. If unable to allocate enough
10148 * memory this function will return ENOMEM. If the queue create mailbox command
10149 * fails this function will return ENXIO.
10150 **/
10151uint32_t
10152lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
10153	       struct lpfc_queue *cq, uint32_t subtype)
10154{
10155	struct lpfc_mbx_wq_create *wq_create;
10156	struct lpfc_dmabuf *dmabuf;
10157	LPFC_MBOXQ_t *mbox;
10158	int rc, length, status = 0;
10159	uint32_t shdr_status, shdr_add_status;
10160	union lpfc_sli4_cfg_shdr *shdr;
10161	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
10162
10163	if (!phba->sli4_hba.pc_sli4_params.supported)
10164		hw_page_size = SLI4_PAGE_SIZE;
10165
10166	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
10167	if (!mbox)
10168		return -ENOMEM;
10169	length = (sizeof(struct lpfc_mbx_wq_create) -
10170		  sizeof(struct lpfc_sli4_cfg_mhdr));
10171	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
10172			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
10173			 length, LPFC_SLI4_MBX_EMBED);
10174	wq_create = &mbox->u.mqe.un.wq_create;
10175	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
10176		    wq->page_count);
10177	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
10178		    cq->queue_id);
10179	list_for_each_entry(dmabuf, &wq->page_list, list) {
10180		memset(dmabuf->virt, 0, hw_page_size);
10181		wq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
10182					putPaddrLow(dmabuf->phys);
10183		wq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
10184					putPaddrHigh(dmabuf->phys);
10185	}
10186	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
10187	/* The IOCTL status is embedded in the mailbox subheader. */
10188	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
10189	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10190	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10191	if (shdr_status || shdr_add_status || rc) {
10192		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10193				"2503 WQ_CREATE mailbox failed with "
10194				"status x%x add_status x%x, mbx status x%x\n",
10195				shdr_status, shdr_add_status, rc);
10196		status = -ENXIO;
10197		goto out;
10198	}
10199	wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id, &wq_create->u.response);
10200	if (wq->queue_id == 0xFFFF) {
10201		status = -ENXIO;
10202		goto out;
10203	}
10204	wq->type = LPFC_WQ;
10205	wq->subtype = subtype;
10206	wq->host_index = 0;
10207	wq->hba_index = 0;
10208
10209	/* link the wq onto the parent cq child list */
10210	list_add_tail(&wq->list, &cq->child_list);
10211out:
10212	mempool_free(mbox, phba->mbox_mem_pool);
10213	return status;
10214}
10215
10216/**
10217 * lpfc_rq_create - Create a Receive Queue on the HBA
10218 * @phba: HBA structure that indicates port to create a queue on.
10219 * @hrq: The queue structure to use to create the header receive queue.
10220 * @drq: The queue structure to use to create the data receive queue.
10221 * @cq: The completion queue to bind this work queue to.
10222 *
10223 * This function creates a receive buffer queue pair , as detailed in @hrq and
10224 * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
10225 * to the HBA.
10226 *
10227 * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
10228 * struct is used to get the entry count that is necessary to determine the
10229 * number of pages to use for this queue. The @cq is used to indicate which
10230 * completion queue to bind received buffers that are posted to these queues to.
10231 * This function will send the RQ_CREATE mailbox command to the HBA to setup the
10232 * receive queue pair. This function is asynchronous and will wait for the
10233 * mailbox command to finish before continuing.
10234 *
10235 * On success this function will return a zero. If unable to allocate enough
10236 * memory this function will return ENOMEM. If the queue create mailbox command
10237 * fails this function will return ENXIO.
10238 **/
10239uint32_t
10240lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
10241	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
10242{
10243	struct lpfc_mbx_rq_create *rq_create;
10244	struct lpfc_dmabuf *dmabuf;
10245	LPFC_MBOXQ_t *mbox;
10246	int rc, length, status = 0;
10247	uint32_t shdr_status, shdr_add_status;
10248	union lpfc_sli4_cfg_shdr *shdr;
10249	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
10250
10251	if (!phba->sli4_hba.pc_sli4_params.supported)
10252		hw_page_size = SLI4_PAGE_SIZE;
10253
10254	if (hrq->entry_count != drq->entry_count)
10255		return -EINVAL;
10256	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
10257	if (!mbox)
10258		return -ENOMEM;
10259	length = (sizeof(struct lpfc_mbx_rq_create) -
10260		  sizeof(struct lpfc_sli4_cfg_mhdr));
10261	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
10262			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
10263			 length, LPFC_SLI4_MBX_EMBED);
10264	rq_create = &mbox->u.mqe.un.rq_create;
10265	switch (hrq->entry_count) {
10266	default:
10267		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10268				"2535 Unsupported RQ count. (%d)\n",
10269				hrq->entry_count);
10270		if (hrq->entry_count < 512)
10271			return -EINVAL;
10272		/* otherwise default to smallest count (drop through) */
10273	case 512:
10274		bf_set(lpfc_rq_context_rq_size, &rq_create->u.request.context,
10275		       LPFC_RQ_RING_SIZE_512);
10276		break;
10277	case 1024:
10278		bf_set(lpfc_rq_context_rq_size, &rq_create->u.request.context,
10279		       LPFC_RQ_RING_SIZE_1024);
10280		break;
10281	case 2048:
10282		bf_set(lpfc_rq_context_rq_size, &rq_create->u.request.context,
10283		       LPFC_RQ_RING_SIZE_2048);
10284		break;
10285	case 4096:
10286		bf_set(lpfc_rq_context_rq_size, &rq_create->u.request.context,
10287		       LPFC_RQ_RING_SIZE_4096);
10288		break;
10289	}
10290	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
10291	       cq->queue_id);
10292	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
10293	       hrq->page_count);
10294	bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
10295	       LPFC_HDR_BUF_SIZE);
10296	list_for_each_entry(dmabuf, &hrq->page_list, list) {
10297		memset(dmabuf->virt, 0, hw_page_size);
10298		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
10299					putPaddrLow(dmabuf->phys);
10300		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
10301					putPaddrHigh(dmabuf->phys);
10302	}
10303	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
10304	/* The IOCTL status is embedded in the mailbox subheader. */
10305	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
10306	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10307	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10308	if (shdr_status || shdr_add_status || rc) {
10309		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10310				"2504 RQ_CREATE mailbox failed with "
10311				"status x%x add_status x%x, mbx status x%x\n",
10312				shdr_status, shdr_add_status, rc);
10313		status = -ENXIO;
10314		goto out;
10315	}
10316	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
10317	if (hrq->queue_id == 0xFFFF) {
10318		status = -ENXIO;
10319		goto out;
10320	}
10321	hrq->type = LPFC_HRQ;
10322	hrq->subtype = subtype;
10323	hrq->host_index = 0;
10324	hrq->hba_index = 0;
10325
10326	/* now create the data queue */
10327	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
10328			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
10329			 length, LPFC_SLI4_MBX_EMBED);
10330	switch (drq->entry_count) {
10331	default:
10332		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10333				"2536 Unsupported RQ count. (%d)\n",
10334				drq->entry_count);
10335		if (drq->entry_count < 512)
10336			return -EINVAL;
10337		/* otherwise default to smallest count (drop through) */
10338	case 512:
10339		bf_set(lpfc_rq_context_rq_size, &rq_create->u.request.context,
10340		       LPFC_RQ_RING_SIZE_512);
10341		break;
10342	case 1024:
10343		bf_set(lpfc_rq_context_rq_size, &rq_create->u.request.context,
10344		       LPFC_RQ_RING_SIZE_1024);
10345		break;
10346	case 2048:
10347		bf_set(lpfc_rq_context_rq_size, &rq_create->u.request.context,
10348		       LPFC_RQ_RING_SIZE_2048);
10349		break;
10350	case 4096:
10351		bf_set(lpfc_rq_context_rq_size, &rq_create->u.request.context,
10352		       LPFC_RQ_RING_SIZE_4096);
10353		break;
10354	}
10355	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
10356	       cq->queue_id);
10357	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
10358	       drq->page_count);
10359	bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
10360	       LPFC_DATA_BUF_SIZE);
10361	list_for_each_entry(dmabuf, &drq->page_list, list) {
10362		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
10363					putPaddrLow(dmabuf->phys);
10364		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
10365					putPaddrHigh(dmabuf->phys);
10366	}
10367	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
10368	/* The IOCTL status is embedded in the mailbox subheader. */
10369	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
10370	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10371	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10372	if (shdr_status || shdr_add_status || rc) {
10373		status = -ENXIO;
10374		goto out;
10375	}
10376	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
10377	if (drq->queue_id == 0xFFFF) {
10378		status = -ENXIO;
10379		goto out;
10380	}
10381	drq->type = LPFC_DRQ;
10382	drq->subtype = subtype;
10383	drq->host_index = 0;
10384	drq->hba_index = 0;
10385
10386	/* link the header and data RQs onto the parent cq child list */
10387	list_add_tail(&hrq->list, &cq->child_list);
10388	list_add_tail(&drq->list, &cq->child_list);
10389
10390out:
10391	mempool_free(mbox, phba->mbox_mem_pool);
10392	return status;
10393}
10394
10395/**
10396 * lpfc_eq_destroy - Destroy an event Queue on the HBA
10397 * @eq: The queue structure associated with the queue to destroy.
10398 *
10399 * This function destroys a queue, as detailed in @eq by sending an mailbox
10400 * command, specific to the type of queue, to the HBA.
10401 *
10402 * The @eq struct is used to get the queue ID of the queue to destroy.
10403 *
10404 * On success this function will return a zero. If the queue destroy mailbox
10405 * command fails this function will return ENXIO.
10406 **/
10407uint32_t
10408lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
10409{
10410	LPFC_MBOXQ_t *mbox;
10411	int rc, length, status = 0;
10412	uint32_t shdr_status, shdr_add_status;
10413	union lpfc_sli4_cfg_shdr *shdr;
10414
10415	if (!eq)
10416		return -ENODEV;
10417	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
10418	if (!mbox)
10419		return -ENOMEM;
10420	length = (sizeof(struct lpfc_mbx_eq_destroy) -
10421		  sizeof(struct lpfc_sli4_cfg_mhdr));
10422	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
10423			 LPFC_MBOX_OPCODE_EQ_DESTROY,
10424			 length, LPFC_SLI4_MBX_EMBED);
10425	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
10426	       eq->queue_id);
10427	mbox->vport = eq->phba->pport;
10428	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
10429
10430	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
10431	/* The IOCTL status is embedded in the mailbox subheader. */
10432	shdr = (union lpfc_sli4_cfg_shdr *)
10433		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
10434	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10435	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10436	if (shdr_status || shdr_add_status || rc) {
10437		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10438				"2505 EQ_DESTROY mailbox failed with "
10439				"status x%x add_status x%x, mbx status x%x\n",
10440				shdr_status, shdr_add_status, rc);
10441		status = -ENXIO;
10442	}
10443
10444	/* Remove eq from any list */
10445	list_del_init(&eq->list);
10446	mempool_free(mbox, eq->phba->mbox_mem_pool);
10447	return status;
10448}
10449
10450/**
10451 * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
10452 * @cq: The queue structure associated with the queue to destroy.
10453 *
10454 * This function destroys a queue, as detailed in @cq by sending an mailbox
10455 * command, specific to the type of queue, to the HBA.
10456 *
10457 * The @cq struct is used to get the queue ID of the queue to destroy.
10458 *
10459 * On success this function will return a zero. If the queue destroy mailbox
10460 * command fails this function will return ENXIO.
10461 **/
10462uint32_t
10463lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
10464{
10465	LPFC_MBOXQ_t *mbox;
10466	int rc, length, status = 0;
10467	uint32_t shdr_status, shdr_add_status;
10468	union lpfc_sli4_cfg_shdr *shdr;
10469
10470	if (!cq)
10471		return -ENODEV;
10472	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
10473	if (!mbox)
10474		return -ENOMEM;
10475	length = (sizeof(struct lpfc_mbx_cq_destroy) -
10476		  sizeof(struct lpfc_sli4_cfg_mhdr));
10477	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
10478			 LPFC_MBOX_OPCODE_CQ_DESTROY,
10479			 length, LPFC_SLI4_MBX_EMBED);
10480	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
10481	       cq->queue_id);
10482	mbox->vport = cq->phba->pport;
10483	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
10484	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
10485	/* The IOCTL status is embedded in the mailbox subheader. */
10486	shdr = (union lpfc_sli4_cfg_shdr *)
10487		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
10488	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10489	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10490	if (shdr_status || shdr_add_status || rc) {
10491		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10492				"2506 CQ_DESTROY mailbox failed with "
10493				"status x%x add_status x%x, mbx status x%x\n",
10494				shdr_status, shdr_add_status, rc);
10495		status = -ENXIO;
10496	}
10497	/* Remove cq from any list */
10498	list_del_init(&cq->list);
10499	mempool_free(mbox, cq->phba->mbox_mem_pool);
10500	return status;
10501}
10502
10503/**
10504 * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
10505 * @qm: The queue structure associated with the queue to destroy.
10506 *
10507 * This function destroys a queue, as detailed in @mq by sending an mailbox
10508 * command, specific to the type of queue, to the HBA.
10509 *
10510 * The @mq struct is used to get the queue ID of the queue to destroy.
10511 *
10512 * On success this function will return a zero. If the queue destroy mailbox
10513 * command fails this function will return ENXIO.
10514 **/
10515uint32_t
10516lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
10517{
10518	LPFC_MBOXQ_t *mbox;
10519	int rc, length, status = 0;
10520	uint32_t shdr_status, shdr_add_status;
10521	union lpfc_sli4_cfg_shdr *shdr;
10522
10523	if (!mq)
10524		return -ENODEV;
10525	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
10526	if (!mbox)
10527		return -ENOMEM;
10528	length = (sizeof(struct lpfc_mbx_mq_destroy) -
10529		  sizeof(struct lpfc_sli4_cfg_mhdr));
10530	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
10531			 LPFC_MBOX_OPCODE_MQ_DESTROY,
10532			 length, LPFC_SLI4_MBX_EMBED);
10533	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
10534	       mq->queue_id);
10535	mbox->vport = mq->phba->pport;
10536	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
10537	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
10538	/* The IOCTL status is embedded in the mailbox subheader. */
10539	shdr = (union lpfc_sli4_cfg_shdr *)
10540		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
10541	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10542	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10543	if (shdr_status || shdr_add_status || rc) {
10544		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10545				"2507 MQ_DESTROY mailbox failed with "
10546				"status x%x add_status x%x, mbx status x%x\n",
10547				shdr_status, shdr_add_status, rc);
10548		status = -ENXIO;
10549	}
10550	/* Remove mq from any list */
10551	list_del_init(&mq->list);
10552	mempool_free(mbox, mq->phba->mbox_mem_pool);
10553	return status;
10554}
10555
10556/**
10557 * lpfc_wq_destroy - Destroy a Work Queue on the HBA
10558 * @wq: The queue structure associated with the queue to destroy.
10559 *
10560 * This function destroys a queue, as detailed in @wq by sending an mailbox
10561 * command, specific to the type of queue, to the HBA.
10562 *
10563 * The @wq struct is used to get the queue ID of the queue to destroy.
10564 *
10565 * On success this function will return a zero. If the queue destroy mailbox
10566 * command fails this function will return ENXIO.
10567 **/
10568uint32_t
10569lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
10570{
10571	LPFC_MBOXQ_t *mbox;
10572	int rc, length, status = 0;
10573	uint32_t shdr_status, shdr_add_status;
10574	union lpfc_sli4_cfg_shdr *shdr;
10575
10576	if (!wq)
10577		return -ENODEV;
10578	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
10579	if (!mbox)
10580		return -ENOMEM;
10581	length = (sizeof(struct lpfc_mbx_wq_destroy) -
10582		  sizeof(struct lpfc_sli4_cfg_mhdr));
10583	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
10584			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
10585			 length, LPFC_SLI4_MBX_EMBED);
10586	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
10587	       wq->queue_id);
10588	mbox->vport = wq->phba->pport;
10589	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
10590	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
10591	shdr = (union lpfc_sli4_cfg_shdr *)
10592		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
10593	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10594	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10595	if (shdr_status || shdr_add_status || rc) {
10596		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10597				"2508 WQ_DESTROY mailbox failed with "
10598				"status x%x add_status x%x, mbx status x%x\n",
10599				shdr_status, shdr_add_status, rc);
10600		status = -ENXIO;
10601	}
10602	/* Remove wq from any list */
10603	list_del_init(&wq->list);
10604	mempool_free(mbox, wq->phba->mbox_mem_pool);
10605	return status;
10606}
10607
10608/**
10609 * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
10610 * @rq: The queue structure associated with the queue to destroy.
10611 *
10612 * This function destroys a queue, as detailed in @rq by sending an mailbox
10613 * command, specific to the type of queue, to the HBA.
10614 *
10615 * The @rq struct is used to get the queue ID of the queue to destroy.
10616 *
10617 * On success this function will return a zero. If the queue destroy mailbox
10618 * command fails this function will return ENXIO.
10619 **/
10620uint32_t
10621lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
10622		struct lpfc_queue *drq)
10623{
10624	LPFC_MBOXQ_t *mbox;
10625	int rc, length, status = 0;
10626	uint32_t shdr_status, shdr_add_status;
10627	union lpfc_sli4_cfg_shdr *shdr;
10628
10629	if (!hrq || !drq)
10630		return -ENODEV;
10631	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
10632	if (!mbox)
10633		return -ENOMEM;
10634	length = (sizeof(struct lpfc_mbx_rq_destroy) -
10635		  sizeof(struct mbox_header));
10636	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
10637			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
10638			 length, LPFC_SLI4_MBX_EMBED);
10639	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
10640	       hrq->queue_id);
10641	mbox->vport = hrq->phba->pport;
10642	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
10643	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
10644	/* The IOCTL status is embedded in the mailbox subheader. */
10645	shdr = (union lpfc_sli4_cfg_shdr *)
10646		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
10647	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10648	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10649	if (shdr_status || shdr_add_status || rc) {
10650		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10651				"2509 RQ_DESTROY mailbox failed with "
10652				"status x%x add_status x%x, mbx status x%x\n",
10653				shdr_status, shdr_add_status, rc);
10654		if (rc != MBX_TIMEOUT)
10655			mempool_free(mbox, hrq->phba->mbox_mem_pool);
10656		return -ENXIO;
10657	}
10658	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
10659	       drq->queue_id);
10660	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
10661	shdr = (union lpfc_sli4_cfg_shdr *)
10662		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
10663	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10664	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10665	if (shdr_status || shdr_add_status || rc) {
10666		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10667				"2510 RQ_DESTROY mailbox failed with "
10668				"status x%x add_status x%x, mbx status x%x\n",
10669				shdr_status, shdr_add_status, rc);
10670		status = -ENXIO;
10671	}
10672	list_del_init(&hrq->list);
10673	list_del_init(&drq->list);
10674	mempool_free(mbox, hrq->phba->mbox_mem_pool);
10675	return status;
10676}
10677
10678/**
10679 * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
10680 * @phba: The virtual port for which this call being executed.
10681 * @pdma_phys_addr0: Physical address of the 1st SGL page.
10682 * @pdma_phys_addr1: Physical address of the 2nd SGL page.
10683 * @xritag: the xritag that ties this io to the SGL pages.
10684 *
10685 * This routine will post the sgl pages for the IO that has the xritag
10686 * that is in the iocbq structure. The xritag is assigned during iocbq
10687 * creation and persists for as long as the driver is loaded.
10688 * if the caller has fewer than 256 scatter gather segments to map then
10689 * pdma_phys_addr1 should be 0.
10690 * If the caller needs to map more than 256 scatter gather segment then
10691 * pdma_phys_addr1 should be a valid physical address.
10692 * physical address for SGLs must be 64 byte aligned.
10693 * If you are going to map 2 SGL's then the first one must have 256 entries
10694 * the second sgl can have between 1 and 256 entries.
10695 *
10696 * Return codes:
10697 * 	0 - Success
10698 * 	-ENXIO, -ENOMEM - Failure
10699 **/
10700int
10701lpfc_sli4_post_sgl(struct lpfc_hba *phba,
10702		dma_addr_t pdma_phys_addr0,
10703		dma_addr_t pdma_phys_addr1,
10704		uint16_t xritag)
10705{
10706	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
10707	LPFC_MBOXQ_t *mbox;
10708	int rc;
10709	uint32_t shdr_status, shdr_add_status;
10710	union lpfc_sli4_cfg_shdr *shdr;
10711
10712	if (xritag == NO_XRI) {
10713		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10714				"0364 Invalid param:\n");
10715		return -EINVAL;
10716	}
10717
10718	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
10719	if (!mbox)
10720		return -ENOMEM;
10721
10722	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
10723			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
10724			sizeof(struct lpfc_mbx_post_sgl_pages) -
10725			sizeof(struct mbox_header), LPFC_SLI4_MBX_EMBED);
10726
10727	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
10728				&mbox->u.mqe.un.post_sgl_pages;
10729	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
10730	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
10731
10732	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
10733				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
10734	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
10735				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
10736
10737	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
10738				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
10739	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
10740				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
10741	if (!phba->sli4_hba.intr_enable)
10742		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
10743	else
10744		rc = lpfc_sli_issue_mbox_wait(phba, mbox, LPFC_MBOX_TMO);
10745	/* The IOCTL status is embedded in the mailbox subheader. */
10746	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
10747	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10748	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10749	if (rc != MBX_TIMEOUT)
10750		mempool_free(mbox, phba->mbox_mem_pool);
10751	if (shdr_status || shdr_add_status || rc) {
10752		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10753				"2511 POST_SGL mailbox failed with "
10754				"status x%x add_status x%x, mbx status x%x\n",
10755				shdr_status, shdr_add_status, rc);
10756		rc = -ENXIO;
10757	}
10758	return 0;
10759}
10760/**
10761 * lpfc_sli4_remove_all_sgl_pages - Post scatter gather list for an XRI to HBA
10762 * @phba: The virtual port for which this call being executed.
10763 *
10764 * This routine will remove all of the sgl pages registered with the hba.
10765 *
10766 * Return codes:
10767 * 	0 - Success
10768 * 	-ENXIO, -ENOMEM - Failure
10769 **/
10770int
10771lpfc_sli4_remove_all_sgl_pages(struct lpfc_hba *phba)
10772{
10773	LPFC_MBOXQ_t *mbox;
10774	int rc;
10775	uint32_t shdr_status, shdr_add_status;
10776	union lpfc_sli4_cfg_shdr *shdr;
10777
10778	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
10779	if (!mbox)
10780		return -ENOMEM;
10781
10782	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
10783			LPFC_MBOX_OPCODE_FCOE_REMOVE_SGL_PAGES, 0,
10784			LPFC_SLI4_MBX_EMBED);
10785	if (!phba->sli4_hba.intr_enable)
10786		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
10787	else
10788		rc = lpfc_sli_issue_mbox_wait(phba, mbox, LPFC_MBOX_TMO);
10789	/* The IOCTL status is embedded in the mailbox subheader. */
10790	shdr = (union lpfc_sli4_cfg_shdr *)
10791		&mbox->u.mqe.un.sli4_config.header.cfg_shdr;
10792	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10793	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10794	if (rc != MBX_TIMEOUT)
10795		mempool_free(mbox, phba->mbox_mem_pool);
10796	if (shdr_status || shdr_add_status || rc) {
10797		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10798				"2512 REMOVE_ALL_SGL_PAGES mailbox failed with "
10799				"status x%x add_status x%x, mbx status x%x\n",
10800				shdr_status, shdr_add_status, rc);
10801		rc = -ENXIO;
10802	}
10803	return rc;
10804}
10805
10806/**
10807 * lpfc_sli4_next_xritag - Get an xritag for the io
10808 * @phba: Pointer to HBA context object.
10809 *
10810 * This function gets an xritag for the iocb. If there is no unused xritag
10811 * it will return 0xffff.
10812 * The function returns the allocated xritag if successful, else returns zero.
10813 * Zero is not a valid xritag.
10814 * The caller is not required to hold any lock.
10815 **/
10816uint16_t
10817lpfc_sli4_next_xritag(struct lpfc_hba *phba)
10818{
10819	uint16_t xritag;
10820
10821	spin_lock_irq(&phba->hbalock);
10822	xritag = phba->sli4_hba.next_xri;
10823	if ((xritag != (uint16_t) -1) && xritag <
10824		(phba->sli4_hba.max_cfg_param.max_xri
10825			+ phba->sli4_hba.max_cfg_param.xri_base)) {
10826		phba->sli4_hba.next_xri++;
10827		phba->sli4_hba.max_cfg_param.xri_used++;
10828		spin_unlock_irq(&phba->hbalock);
10829		return xritag;
10830	}
10831	spin_unlock_irq(&phba->hbalock);
10832	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10833			"2004 Failed to allocate XRI.last XRITAG is %d"
10834			" Max XRI is %d, Used XRI is %d\n",
10835			phba->sli4_hba.next_xri,
10836			phba->sli4_hba.max_cfg_param.max_xri,
10837			phba->sli4_hba.max_cfg_param.xri_used);
10838	return -1;
10839}
10840
10841/**
10842 * lpfc_sli4_post_sgl_list - post a block of sgl list to the firmware.
10843 * @phba: pointer to lpfc hba data structure.
10844 *
10845 * This routine is invoked to post a block of driver's sgl pages to the
10846 * HBA using non-embedded mailbox command. No Lock is held. This routine
10847 * is only called when the driver is loading and after all IO has been
10848 * stopped.
10849 **/
10850int
10851lpfc_sli4_post_sgl_list(struct lpfc_hba *phba)
10852{
10853	struct lpfc_sglq *sglq_entry;
10854	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
10855	struct sgl_page_pairs *sgl_pg_pairs;
10856	void *viraddr;
10857	LPFC_MBOXQ_t *mbox;
10858	uint32_t reqlen, alloclen, pg_pairs;
10859	uint32_t mbox_tmo;
10860	uint16_t xritag_start = 0;
10861	int els_xri_cnt, rc = 0;
10862	uint32_t shdr_status, shdr_add_status;
10863	union lpfc_sli4_cfg_shdr *shdr;
10864
10865	/* The number of sgls to be posted */
10866	els_xri_cnt = lpfc_sli4_get_els_iocb_cnt(phba);
10867
10868	reqlen = els_xri_cnt * sizeof(struct sgl_page_pairs) +
10869		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
10870	if (reqlen > SLI4_PAGE_SIZE) {
10871		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
10872				"2559 Block sgl registration required DMA "
10873				"size (%d) great than a page\n", reqlen);
10874		return -ENOMEM;
10875	}
10876	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
10877	if (!mbox) {
10878		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10879				"2560 Failed to allocate mbox cmd memory\n");
10880		return -ENOMEM;
10881	}
10882
10883	/* Allocate DMA memory and set up the non-embedded mailbox command */
10884	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
10885			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
10886			 LPFC_SLI4_MBX_NEMBED);
10887
10888	if (alloclen < reqlen) {
10889		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10890				"0285 Allocated DMA memory size (%d) is "
10891				"less than the requested DMA memory "
10892				"size (%d)\n", alloclen, reqlen);
10893		lpfc_sli4_mbox_cmd_free(phba, mbox);
10894		return -ENOMEM;
10895	}
10896	/* Get the first SGE entry from the non-embedded DMA memory */
10897	viraddr = mbox->sge_array->addr[0];
10898
10899	/* Set up the SGL pages in the non-embedded DMA pages */
10900	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
10901	sgl_pg_pairs = &sgl->sgl_pg_pairs;
10902
10903	for (pg_pairs = 0; pg_pairs < els_xri_cnt; pg_pairs++) {
10904		sglq_entry = phba->sli4_hba.lpfc_els_sgl_array[pg_pairs];
10905		/* Set up the sge entry */
10906		sgl_pg_pairs->sgl_pg0_addr_lo =
10907				cpu_to_le32(putPaddrLow(sglq_entry->phys));
10908		sgl_pg_pairs->sgl_pg0_addr_hi =
10909				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
10910		sgl_pg_pairs->sgl_pg1_addr_lo =
10911				cpu_to_le32(putPaddrLow(0));
10912		sgl_pg_pairs->sgl_pg1_addr_hi =
10913				cpu_to_le32(putPaddrHigh(0));
10914		/* Keep the first xritag on the list */
10915		if (pg_pairs == 0)
10916			xritag_start = sglq_entry->sli4_xritag;
10917		sgl_pg_pairs++;
10918	}
10919	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
10920	bf_set(lpfc_post_sgl_pages_xricnt, sgl, els_xri_cnt);
10921	/* Perform endian conversion if necessary */
10922	sgl->word0 = cpu_to_le32(sgl->word0);
10923
10924	if (!phba->sli4_hba.intr_enable)
10925		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
10926	else {
10927		mbox_tmo = lpfc_mbox_tmo_val(phba, MBX_SLI4_CONFIG);
10928		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
10929	}
10930	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
10931	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
10932	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
10933	if (rc != MBX_TIMEOUT)
10934		lpfc_sli4_mbox_cmd_free(phba, mbox);
10935	if (shdr_status || shdr_add_status || rc) {
10936		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10937				"2513 POST_SGL_BLOCK mailbox command failed "
10938				"status x%x add_status x%x mbx status x%x\n",
10939				shdr_status, shdr_add_status, rc);
10940		rc = -ENXIO;
10941	}
10942	return rc;
10943}
10944
10945/**
10946 * lpfc_sli4_post_scsi_sgl_block - post a block of scsi sgl list to firmware
10947 * @phba: pointer to lpfc hba data structure.
10948 * @sblist: pointer to scsi buffer list.
10949 * @count: number of scsi buffers on the list.
10950 *
10951 * This routine is invoked to post a block of @count scsi sgl pages from a
10952 * SCSI buffer list @sblist to the HBA using non-embedded mailbox command.
10953 * No Lock is held.
10954 *
10955 **/
10956int
10957lpfc_sli4_post_scsi_sgl_block(struct lpfc_hba *phba, struct list_head *sblist,
10958			      int cnt)
10959{
10960	struct lpfc_scsi_buf *psb;
10961	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
10962	struct sgl_page_pairs *sgl_pg_pairs;
10963	void *viraddr;
10964	LPFC_MBOXQ_t *mbox;
10965	uint32_t reqlen, alloclen, pg_pairs;
10966	uint32_t mbox_tmo;
10967	uint16_t xritag_start = 0;
10968	int rc = 0;
10969	uint32_t shdr_status, shdr_add_status;
10970	dma_addr_t pdma_phys_bpl1;
10971	union lpfc_sli4_cfg_shdr *shdr;
10972
10973	/* Calculate the requested length of the dma memory */
10974	reqlen = cnt * sizeof(struct sgl_page_pairs) +
10975		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
10976	if (reqlen > SLI4_PAGE_SIZE) {
10977		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
10978				"0217 Block sgl registration required DMA "
10979				"size (%d) great than a page\n", reqlen);
10980		return -ENOMEM;
10981	}
10982	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
10983	if (!mbox) {
10984		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10985				"0283 Failed to allocate mbox cmd memory\n");
10986		return -ENOMEM;
10987	}
10988
10989	/* Allocate DMA memory and set up the non-embedded mailbox command */
10990	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
10991				LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
10992				LPFC_SLI4_MBX_NEMBED);
10993
10994	if (alloclen < reqlen) {
10995		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10996				"2561 Allocated DMA memory size (%d) is "
10997				"less than the requested DMA memory "
10998				"size (%d)\n", alloclen, reqlen);
10999		lpfc_sli4_mbox_cmd_free(phba, mbox);
11000		return -ENOMEM;
11001	}
11002	/* Get the first SGE entry from the non-embedded DMA memory */
11003	viraddr = mbox->sge_array->addr[0];
11004
11005	/* Set up the SGL pages in the non-embedded DMA pages */
11006	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
11007	sgl_pg_pairs = &sgl->sgl_pg_pairs;
11008
11009	pg_pairs = 0;
11010	list_for_each_entry(psb, sblist, list) {
11011		/* Set up the sge entry */
11012		sgl_pg_pairs->sgl_pg0_addr_lo =
11013			cpu_to_le32(putPaddrLow(psb->dma_phys_bpl));
11014		sgl_pg_pairs->sgl_pg0_addr_hi =
11015			cpu_to_le32(putPaddrHigh(psb->dma_phys_bpl));
11016		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
11017			pdma_phys_bpl1 = psb->dma_phys_bpl + SGL_PAGE_SIZE;
11018		else
11019			pdma_phys_bpl1 = 0;
11020		sgl_pg_pairs->sgl_pg1_addr_lo =
11021			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
11022		sgl_pg_pairs->sgl_pg1_addr_hi =
11023			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
11024		/* Keep the first xritag on the list */
11025		if (pg_pairs == 0)
11026			xritag_start = psb->cur_iocbq.sli4_xritag;
11027		sgl_pg_pairs++;
11028		pg_pairs++;
11029	}
11030	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
11031	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
11032	/* Perform endian conversion if necessary */
11033	sgl->word0 = cpu_to_le32(sgl->word0);
11034
11035	if (!phba->sli4_hba.intr_enable)
11036		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
11037	else {
11038		mbox_tmo = lpfc_mbox_tmo_val(phba, MBX_SLI4_CONFIG);
11039		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
11040	}
11041	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
11042	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11043	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
11044	if (rc != MBX_TIMEOUT)
11045		lpfc_sli4_mbox_cmd_free(phba, mbox);
11046	if (shdr_status || shdr_add_status || rc) {
11047		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11048				"2564 POST_SGL_BLOCK mailbox command failed "
11049				"status x%x add_status x%x mbx status x%x\n",
11050				shdr_status, shdr_add_status, rc);
11051		rc = -ENXIO;
11052	}
11053	return rc;
11054}
11055
11056/**
11057 * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
11058 * @phba: pointer to lpfc_hba struct that the frame was received on
11059 * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
11060 *
11061 * This function checks the fields in the @fc_hdr to see if the FC frame is a
11062 * valid type of frame that the LPFC driver will handle. This function will
11063 * return a zero if the frame is a valid frame or a non zero value when the
11064 * frame does not pass the check.
11065 **/
11066static int
11067lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
11068{
11069	char *rctl_names[] = FC_RCTL_NAMES_INIT;
11070	char *type_names[] = FC_TYPE_NAMES_INIT;
11071	struct fc_vft_header *fc_vft_hdr;
11072
11073	switch (fc_hdr->fh_r_ctl) {
11074	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
11075	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
11076	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
11077	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
11078	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
11079	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
11080	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
11081	case FC_RCTL_DD_CMD_STATUS:	/* command status */
11082	case FC_RCTL_ELS_REQ:	/* extended link services request */
11083	case FC_RCTL_ELS_REP:	/* extended link services reply */
11084	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
11085	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
11086	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
11087	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
11088	case FC_RCTL_BA_RMC: 	/* remove connection */
11089	case FC_RCTL_BA_ACC:	/* basic accept */
11090	case FC_RCTL_BA_RJT:	/* basic reject */
11091	case FC_RCTL_BA_PRMT:
11092	case FC_RCTL_ACK_1:	/* acknowledge_1 */
11093	case FC_RCTL_ACK_0:	/* acknowledge_0 */
11094	case FC_RCTL_P_RJT:	/* port reject */
11095	case FC_RCTL_F_RJT:	/* fabric reject */
11096	case FC_RCTL_P_BSY:	/* port busy */
11097	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
11098	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
11099	case FC_RCTL_LCR:	/* link credit reset */
11100	case FC_RCTL_END:	/* end */
11101		break;
11102	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
11103		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
11104		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
11105		return lpfc_fc_frame_check(phba, fc_hdr);
11106	default:
11107		goto drop;
11108	}
11109	switch (fc_hdr->fh_type) {
11110	case FC_TYPE_BLS:
11111	case FC_TYPE_ELS:
11112	case FC_TYPE_FCP:
11113	case FC_TYPE_CT:
11114		break;
11115	case FC_TYPE_IP:
11116	case FC_TYPE_ILS:
11117	default:
11118		goto drop;
11119	}
11120	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
11121			"2538 Received frame rctl:%s type:%s\n",
11122			rctl_names[fc_hdr->fh_r_ctl],
11123			type_names[fc_hdr->fh_type]);
11124	return 0;
11125drop:
11126	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
11127			"2539 Dropped frame rctl:%s type:%s\n",
11128			rctl_names[fc_hdr->fh_r_ctl],
11129			type_names[fc_hdr->fh_type]);
11130	return 1;
11131}
11132
11133/**
11134 * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
11135 * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
11136 *
11137 * This function processes the FC header to retrieve the VFI from the VF
11138 * header, if one exists. This function will return the VFI if one exists
11139 * or 0 if no VSAN Header exists.
11140 **/
11141static uint32_t
11142lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
11143{
11144	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
11145
11146	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
11147		return 0;
11148	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
11149}
11150
11151/**
11152 * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
11153 * @phba: Pointer to the HBA structure to search for the vport on
11154 * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
11155 * @fcfi: The FC Fabric ID that the frame came from
11156 *
11157 * This function searches the @phba for a vport that matches the content of the
11158 * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
11159 * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
11160 * returns the matching vport pointer or NULL if unable to match frame to a
11161 * vport.
11162 **/
11163static struct lpfc_vport *
11164lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
11165		       uint16_t fcfi)
11166{
11167	struct lpfc_vport **vports;
11168	struct lpfc_vport *vport = NULL;
11169	int i;
11170	uint32_t did = (fc_hdr->fh_d_id[0] << 16 |
11171			fc_hdr->fh_d_id[1] << 8 |
11172			fc_hdr->fh_d_id[2]);
11173
11174	vports = lpfc_create_vport_work_array(phba);
11175	if (vports != NULL)
11176		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
11177			if (phba->fcf.fcfi == fcfi &&
11178			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
11179			    vports[i]->fc_myDID == did) {
11180				vport = vports[i];
11181				break;
11182			}
11183		}
11184	lpfc_destroy_vport_work_array(phba, vports);
11185	return vport;
11186}
11187
11188/**
11189 * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
11190 * @vport: The vport to work on.
11191 *
11192 * This function updates the receive sequence time stamp for this vport. The
11193 * receive sequence time stamp indicates the time that the last frame of the
11194 * the sequence that has been idle for the longest amount of time was received.
11195 * the driver uses this time stamp to indicate if any received sequences have
11196 * timed out.
11197 **/
11198void
11199lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
11200{
11201	struct lpfc_dmabuf *h_buf;
11202	struct hbq_dmabuf *dmabuf = NULL;
11203
11204	/* get the oldest sequence on the rcv list */
11205	h_buf = list_get_first(&vport->rcv_buffer_list,
11206			       struct lpfc_dmabuf, list);
11207	if (!h_buf)
11208		return;
11209	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
11210	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
11211}
11212
11213/**
11214 * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
11215 * @vport: The vport that the received sequences were sent to.
11216 *
11217 * This function cleans up all outstanding received sequences. This is called
11218 * by the driver when a link event or user action invalidates all the received
11219 * sequences.
11220 **/
11221void
11222lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
11223{
11224	struct lpfc_dmabuf *h_buf, *hnext;
11225	struct lpfc_dmabuf *d_buf, *dnext;
11226	struct hbq_dmabuf *dmabuf = NULL;
11227
11228	/* start with the oldest sequence on the rcv list */
11229	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
11230		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
11231		list_del_init(&dmabuf->hbuf.list);
11232		list_for_each_entry_safe(d_buf, dnext,
11233					 &dmabuf->dbuf.list, list) {
11234			list_del_init(&d_buf->list);
11235			lpfc_in_buf_free(vport->phba, d_buf);
11236		}
11237		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
11238	}
11239}
11240
11241/**
11242 * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
11243 * @vport: The vport that the received sequences were sent to.
11244 *
11245 * This function determines whether any received sequences have timed out by
11246 * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
11247 * indicates that there is at least one timed out sequence this routine will
11248 * go through the received sequences one at a time from most inactive to most
11249 * active to determine which ones need to be cleaned up. Once it has determined
11250 * that a sequence needs to be cleaned up it will simply free up the resources
11251 * without sending an abort.
11252 **/
11253void
11254lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
11255{
11256	struct lpfc_dmabuf *h_buf, *hnext;
11257	struct lpfc_dmabuf *d_buf, *dnext;
11258	struct hbq_dmabuf *dmabuf = NULL;
11259	unsigned long timeout;
11260	int abort_count = 0;
11261
11262	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
11263		   vport->rcv_buffer_time_stamp);
11264	if (list_empty(&vport->rcv_buffer_list) ||
11265	    time_before(jiffies, timeout))
11266		return;
11267	/* start with the oldest sequence on the rcv list */
11268	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
11269		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
11270		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
11271			   dmabuf->time_stamp);
11272		if (time_before(jiffies, timeout))
11273			break;
11274		abort_count++;
11275		list_del_init(&dmabuf->hbuf.list);
11276		list_for_each_entry_safe(d_buf, dnext,
11277					 &dmabuf->dbuf.list, list) {
11278			list_del_init(&d_buf->list);
11279			lpfc_in_buf_free(vport->phba, d_buf);
11280		}
11281		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
11282	}
11283	if (abort_count)
11284		lpfc_update_rcv_time_stamp(vport);
11285}
11286
11287/**
11288 * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
11289 * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
11290 *
11291 * This function searches through the existing incomplete sequences that have
11292 * been sent to this @vport. If the frame matches one of the incomplete
11293 * sequences then the dbuf in the @dmabuf is added to the list of frames that
11294 * make up that sequence. If no sequence is found that matches this frame then
11295 * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
11296 * This function returns a pointer to the first dmabuf in the sequence list that
11297 * the frame was linked to.
11298 **/
11299static struct hbq_dmabuf *
11300lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
11301{
11302	struct fc_frame_header *new_hdr;
11303	struct fc_frame_header *temp_hdr;
11304	struct lpfc_dmabuf *d_buf;
11305	struct lpfc_dmabuf *h_buf;
11306	struct hbq_dmabuf *seq_dmabuf = NULL;
11307	struct hbq_dmabuf *temp_dmabuf = NULL;
11308
11309	INIT_LIST_HEAD(&dmabuf->dbuf.list);
11310	dmabuf->time_stamp = jiffies;
11311	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
11312	/* Use the hdr_buf to find the sequence that this frame belongs to */
11313	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
11314		temp_hdr = (struct fc_frame_header *)h_buf->virt;
11315		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
11316		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
11317		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
11318			continue;
11319		/* found a pending sequence that matches this frame */
11320		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
11321		break;
11322	}
11323	if (!seq_dmabuf) {
11324		/*
11325		 * This indicates first frame received for this sequence.
11326		 * Queue the buffer on the vport's rcv_buffer_list.
11327		 */
11328		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
11329		lpfc_update_rcv_time_stamp(vport);
11330		return dmabuf;
11331	}
11332	temp_hdr = seq_dmabuf->hbuf.virt;
11333	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
11334		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
11335		list_del_init(&seq_dmabuf->hbuf.list);
11336		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
11337		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
11338		lpfc_update_rcv_time_stamp(vport);
11339		return dmabuf;
11340	}
11341	/* move this sequence to the tail to indicate a young sequence */
11342	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
11343	seq_dmabuf->time_stamp = jiffies;
11344	lpfc_update_rcv_time_stamp(vport);
11345	if (list_empty(&seq_dmabuf->dbuf.list)) {
11346		temp_hdr = dmabuf->hbuf.virt;
11347		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
11348		return seq_dmabuf;
11349	}
11350	/* find the correct place in the sequence to insert this frame */
11351	list_for_each_entry_reverse(d_buf, &seq_dmabuf->dbuf.list, list) {
11352		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
11353		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
11354		/*
11355		 * If the frame's sequence count is greater than the frame on
11356		 * the list then insert the frame right after this frame
11357		 */
11358		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
11359			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
11360			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
11361			return seq_dmabuf;
11362		}
11363	}
11364	return NULL;
11365}
11366
11367/**
11368 * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
11369 * @vport: pointer to a vitural port
11370 * @dmabuf: pointer to a dmabuf that describes the FC sequence
11371 *
11372 * This function tries to abort from the partially assembed sequence, described
11373 * by the information from basic abbort @dmabuf. It checks to see whether such
11374 * partially assembled sequence held by the driver. If so, it shall free up all
11375 * the frames from the partially assembled sequence.
11376 *
11377 * Return
11378 * true  -- if there is matching partially assembled sequence present and all
11379 *          the frames freed with the sequence;
11380 * false -- if there is no matching partially assembled sequence present so
11381 *          nothing got aborted in the lower layer driver
11382 **/
11383static bool
11384lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
11385			    struct hbq_dmabuf *dmabuf)
11386{
11387	struct fc_frame_header *new_hdr;
11388	struct fc_frame_header *temp_hdr;
11389	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
11390	struct hbq_dmabuf *seq_dmabuf = NULL;
11391
11392	/* Use the hdr_buf to find the sequence that matches this frame */
11393	INIT_LIST_HEAD(&dmabuf->dbuf.list);
11394	INIT_LIST_HEAD(&dmabuf->hbuf.list);
11395	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
11396	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
11397		temp_hdr = (struct fc_frame_header *)h_buf->virt;
11398		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
11399		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
11400		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
11401			continue;
11402		/* found a pending sequence that matches this frame */
11403		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
11404		break;
11405	}
11406
11407	/* Free up all the frames from the partially assembled sequence */
11408	if (seq_dmabuf) {
11409		list_for_each_entry_safe(d_buf, n_buf,
11410					 &seq_dmabuf->dbuf.list, list) {
11411			list_del_init(&d_buf->list);
11412			lpfc_in_buf_free(vport->phba, d_buf);
11413		}
11414		return true;
11415	}
11416	return false;
11417}
11418
11419/**
11420 * lpfc_sli4_seq_abort_acc_cmpl - Accept seq abort iocb complete handler
11421 * @phba: Pointer to HBA context object.
11422 * @cmd_iocbq: pointer to the command iocbq structure.
11423 * @rsp_iocbq: pointer to the response iocbq structure.
11424 *
11425 * This function handles the sequence abort accept iocb command complete
11426 * event. It properly releases the memory allocated to the sequence abort
11427 * accept iocb.
11428 **/
11429static void
11430lpfc_sli4_seq_abort_acc_cmpl(struct lpfc_hba *phba,
11431			     struct lpfc_iocbq *cmd_iocbq,
11432			     struct lpfc_iocbq *rsp_iocbq)
11433{
11434	if (cmd_iocbq)
11435		lpfc_sli_release_iocbq(phba, cmd_iocbq);
11436}
11437
11438/**
11439 * lpfc_sli4_seq_abort_acc - Accept sequence abort
11440 * @phba: Pointer to HBA context object.
11441 * @fc_hdr: pointer to a FC frame header.
11442 *
11443 * This function sends a basic accept to a previous unsol sequence abort
11444 * event after aborting the sequence handling.
11445 **/
11446static void
11447lpfc_sli4_seq_abort_acc(struct lpfc_hba *phba,
11448			struct fc_frame_header *fc_hdr)
11449{
11450	struct lpfc_iocbq *ctiocb = NULL;
11451	struct lpfc_nodelist *ndlp;
11452	uint16_t oxid, rxid;
11453	uint32_t sid, fctl;
11454	IOCB_t *icmd;
11455
11456	if (!lpfc_is_link_up(phba))
11457		return;
11458
11459	sid = sli4_sid_from_fc_hdr(fc_hdr);
11460	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
11461	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
11462
11463	ndlp = lpfc_findnode_did(phba->pport, sid);
11464	if (!ndlp) {
11465		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
11466				"1268 Find ndlp returned NULL for oxid:x%x "
11467				"SID:x%x\n", oxid, sid);
11468		return;
11469	}
11470
11471	/* Allocate buffer for acc iocb */
11472	ctiocb = lpfc_sli_get_iocbq(phba);
11473	if (!ctiocb)
11474		return;
11475
11476	/* Extract the F_CTL field from FC_HDR */
11477	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
11478
11479	icmd = &ctiocb->iocb;
11480	icmd->un.xseq64.bdl.bdeSize = 0;
11481	icmd->un.xseq64.bdl.ulpIoTag32 = 0;
11482	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
11483	icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
11484	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
11485
11486	/* Fill in the rest of iocb fields */
11487	icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
11488	icmd->ulpBdeCount = 0;
11489	icmd->ulpLe = 1;
11490	icmd->ulpClass = CLASS3;
11491	icmd->ulpContext = ndlp->nlp_rpi;
11492
11493	ctiocb->iocb_cmpl = NULL;
11494	ctiocb->vport = phba->pport;
11495	ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_acc_cmpl;
11496
11497	if (fctl & FC_FC_EX_CTX) {
11498		/* ABTS sent by responder to CT exchange, construction
11499		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
11500		 * field and RX_ID from ABTS for RX_ID field.
11501		 */
11502		bf_set(lpfc_abts_orig, &icmd->un.bls_acc, LPFC_ABTS_UNSOL_RSP);
11503		bf_set(lpfc_abts_rxid, &icmd->un.bls_acc, rxid);
11504		ctiocb->sli4_xritag = oxid;
11505	} else {
11506		/* ABTS sent by initiator to CT exchange, construction
11507		 * of BA_ACC will need to allocate a new XRI as for the
11508		 * XRI_TAG and RX_ID fields.
11509		 */
11510		bf_set(lpfc_abts_orig, &icmd->un.bls_acc, LPFC_ABTS_UNSOL_INT);
11511		bf_set(lpfc_abts_rxid, &icmd->un.bls_acc, NO_XRI);
11512		ctiocb->sli4_xritag = NO_XRI;
11513	}
11514	bf_set(lpfc_abts_oxid, &icmd->un.bls_acc, oxid);
11515
11516	/* Xmit CT abts accept on exchange <xid> */
11517	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
11518			"1200 Xmit CT ABTS ACC on exchange x%x Data: x%x\n",
11519			CMD_XMIT_BLS_RSP64_CX, phba->link_state);
11520	lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
11521}
11522
11523/**
11524 * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
11525 * @vport: Pointer to the vport on which this sequence was received
11526 * @dmabuf: pointer to a dmabuf that describes the FC sequence
11527 *
11528 * This function handles an SLI-4 unsolicited abort event. If the unsolicited
11529 * receive sequence is only partially assembed by the driver, it shall abort
11530 * the partially assembled frames for the sequence. Otherwise, if the
11531 * unsolicited receive sequence has been completely assembled and passed to
11532 * the Upper Layer Protocol (UPL), it then mark the per oxid status for the
11533 * unsolicited sequence has been aborted. After that, it will issue a basic
11534 * accept to accept the abort.
11535 **/
11536void
11537lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
11538			     struct hbq_dmabuf *dmabuf)
11539{
11540	struct lpfc_hba *phba = vport->phba;
11541	struct fc_frame_header fc_hdr;
11542	uint32_t fctl;
11543	bool abts_par;
11544
11545	/* Make a copy of fc_hdr before the dmabuf being released */
11546	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
11547	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
11548
11549	if (fctl & FC_FC_EX_CTX) {
11550		/*
11551		 * ABTS sent by responder to exchange, just free the buffer
11552		 */
11553		lpfc_in_buf_free(phba, &dmabuf->dbuf);
11554	} else {
11555		/*
11556		 * ABTS sent by initiator to exchange, need to do cleanup
11557		 */
11558		/* Try to abort partially assembled seq */
11559		abts_par = lpfc_sli4_abort_partial_seq(vport, dmabuf);
11560
11561		/* Send abort to ULP if partially seq abort failed */
11562		if (abts_par == false)
11563			lpfc_sli4_send_seq_to_ulp(vport, dmabuf);
11564		else
11565			lpfc_in_buf_free(phba, &dmabuf->dbuf);
11566	}
11567	/* Send basic accept (BA_ACC) to the abort requester */
11568	lpfc_sli4_seq_abort_acc(phba, &fc_hdr);
11569}
11570
11571/**
11572 * lpfc_seq_complete - Indicates if a sequence is complete
11573 * @dmabuf: pointer to a dmabuf that describes the FC sequence
11574 *
11575 * This function checks the sequence, starting with the frame described by
11576 * @dmabuf, to see if all the frames associated with this sequence are present.
11577 * the frames associated with this sequence are linked to the @dmabuf using the
11578 * dbuf list. This function looks for two major things. 1) That the first frame
11579 * has a sequence count of zero. 2) There is a frame with last frame of sequence
11580 * set. 3) That there are no holes in the sequence count. The function will
11581 * return 1 when the sequence is complete, otherwise it will return 0.
11582 **/
11583static int
11584lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
11585{
11586	struct fc_frame_header *hdr;
11587	struct lpfc_dmabuf *d_buf;
11588	struct hbq_dmabuf *seq_dmabuf;
11589	uint32_t fctl;
11590	int seq_count = 0;
11591
11592	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
11593	/* make sure first fame of sequence has a sequence count of zero */
11594	if (hdr->fh_seq_cnt != seq_count)
11595		return 0;
11596	fctl = (hdr->fh_f_ctl[0] << 16 |
11597		hdr->fh_f_ctl[1] << 8 |
11598		hdr->fh_f_ctl[2]);
11599	/* If last frame of sequence we can return success. */
11600	if (fctl & FC_FC_END_SEQ)
11601		return 1;
11602	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
11603		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
11604		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
11605		/* If there is a hole in the sequence count then fail. */
11606		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
11607			return 0;
11608		fctl = (hdr->fh_f_ctl[0] << 16 |
11609			hdr->fh_f_ctl[1] << 8 |
11610			hdr->fh_f_ctl[2]);
11611		/* If last frame of sequence we can return success. */
11612		if (fctl & FC_FC_END_SEQ)
11613			return 1;
11614	}
11615	return 0;
11616}
11617
11618/**
11619 * lpfc_prep_seq - Prep sequence for ULP processing
11620 * @vport: Pointer to the vport on which this sequence was received
11621 * @dmabuf: pointer to a dmabuf that describes the FC sequence
11622 *
11623 * This function takes a sequence, described by a list of frames, and creates
11624 * a list of iocbq structures to describe the sequence. This iocbq list will be
11625 * used to issue to the generic unsolicited sequence handler. This routine
11626 * returns a pointer to the first iocbq in the list. If the function is unable
11627 * to allocate an iocbq then it throw out the received frames that were not
11628 * able to be described and return a pointer to the first iocbq. If unable to
11629 * allocate any iocbqs (including the first) this function will return NULL.
11630 **/
11631static struct lpfc_iocbq *
11632lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
11633{
11634	struct lpfc_dmabuf *d_buf, *n_buf;
11635	struct lpfc_iocbq *first_iocbq, *iocbq;
11636	struct fc_frame_header *fc_hdr;
11637	uint32_t sid;
11638	struct ulp_bde64 *pbde;
11639
11640	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
11641	/* remove from receive buffer list */
11642	list_del_init(&seq_dmabuf->hbuf.list);
11643	lpfc_update_rcv_time_stamp(vport);
11644	/* get the Remote Port's SID */
11645	sid = sli4_sid_from_fc_hdr(fc_hdr);
11646	/* Get an iocbq struct to fill in. */
11647	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
11648	if (first_iocbq) {
11649		/* Initialize the first IOCB. */
11650		first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
11651		first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
11652		first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
11653		first_iocbq->iocb.ulpContext = be16_to_cpu(fc_hdr->fh_ox_id);
11654		first_iocbq->iocb.unsli3.rcvsli3.vpi =
11655					vport->vpi + vport->phba->vpi_base;
11656		/* put the first buffer into the first IOCBq */
11657		first_iocbq->context2 = &seq_dmabuf->dbuf;
11658		first_iocbq->context3 = NULL;
11659		first_iocbq->iocb.ulpBdeCount = 1;
11660		first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
11661							LPFC_DATA_BUF_SIZE;
11662		first_iocbq->iocb.un.rcvels.remoteID = sid;
11663		first_iocbq->iocb.unsli3.rcvsli3.acc_len +=
11664				bf_get(lpfc_rcqe_length,
11665				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
11666	}
11667	iocbq = first_iocbq;
11668	/*
11669	 * Each IOCBq can have two Buffers assigned, so go through the list
11670	 * of buffers for this sequence and save two buffers in each IOCBq
11671	 */
11672	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
11673		if (!iocbq) {
11674			lpfc_in_buf_free(vport->phba, d_buf);
11675			continue;
11676		}
11677		if (!iocbq->context3) {
11678			iocbq->context3 = d_buf;
11679			iocbq->iocb.ulpBdeCount++;
11680			pbde = (struct ulp_bde64 *)
11681					&iocbq->iocb.unsli3.sli3Words[4];
11682			pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
11683			first_iocbq->iocb.unsli3.rcvsli3.acc_len +=
11684				bf_get(lpfc_rcqe_length,
11685				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
11686		} else {
11687			iocbq = lpfc_sli_get_iocbq(vport->phba);
11688			if (!iocbq) {
11689				if (first_iocbq) {
11690					first_iocbq->iocb.ulpStatus =
11691							IOSTAT_FCP_RSP_ERROR;
11692					first_iocbq->iocb.un.ulpWord[4] =
11693							IOERR_NO_RESOURCES;
11694				}
11695				lpfc_in_buf_free(vport->phba, d_buf);
11696				continue;
11697			}
11698			iocbq->context2 = d_buf;
11699			iocbq->context3 = NULL;
11700			iocbq->iocb.ulpBdeCount = 1;
11701			iocbq->iocb.un.cont64[0].tus.f.bdeSize =
11702							LPFC_DATA_BUF_SIZE;
11703			first_iocbq->iocb.unsli3.rcvsli3.acc_len +=
11704				bf_get(lpfc_rcqe_length,
11705				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
11706			iocbq->iocb.un.rcvels.remoteID = sid;
11707			list_add_tail(&iocbq->list, &first_iocbq->list);
11708		}
11709	}
11710	return first_iocbq;
11711}
11712
11713static void
11714lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
11715			  struct hbq_dmabuf *seq_dmabuf)
11716{
11717	struct fc_frame_header *fc_hdr;
11718	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
11719	struct lpfc_hba *phba = vport->phba;
11720
11721	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
11722	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
11723	if (!iocbq) {
11724		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11725				"2707 Ring %d handler: Failed to allocate "
11726				"iocb Rctl x%x Type x%x received\n",
11727				LPFC_ELS_RING,
11728				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
11729		return;
11730	}
11731	if (!lpfc_complete_unsol_iocb(phba,
11732				      &phba->sli.ring[LPFC_ELS_RING],
11733				      iocbq, fc_hdr->fh_r_ctl,
11734				      fc_hdr->fh_type))
11735		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11736				"2540 Ring %d handler: unexpected Rctl "
11737				"x%x Type x%x received\n",
11738				LPFC_ELS_RING,
11739				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
11740
11741	/* Free iocb created in lpfc_prep_seq */
11742	list_for_each_entry_safe(curr_iocb, next_iocb,
11743		&iocbq->list, list) {
11744		list_del_init(&curr_iocb->list);
11745		lpfc_sli_release_iocbq(phba, curr_iocb);
11746	}
11747	lpfc_sli_release_iocbq(phba, iocbq);
11748}
11749
11750/**
11751 * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
11752 * @phba: Pointer to HBA context object.
11753 *
11754 * This function is called with no lock held. This function processes all
11755 * the received buffers and gives it to upper layers when a received buffer
11756 * indicates that it is the final frame in the sequence. The interrupt
11757 * service routine processes received buffers at interrupt contexts and adds
11758 * received dma buffers to the rb_pend_list queue and signals the worker thread.
11759 * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
11760 * appropriate receive function when the final frame in a sequence is received.
11761 **/
11762void
11763lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
11764				 struct hbq_dmabuf *dmabuf)
11765{
11766	struct hbq_dmabuf *seq_dmabuf;
11767	struct fc_frame_header *fc_hdr;
11768	struct lpfc_vport *vport;
11769	uint32_t fcfi;
11770
11771	/* Process each received buffer */
11772	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
11773	/* check to see if this a valid type of frame */
11774	if (lpfc_fc_frame_check(phba, fc_hdr)) {
11775		lpfc_in_buf_free(phba, &dmabuf->dbuf);
11776		return;
11777	}
11778	fcfi = bf_get(lpfc_rcqe_fcf_id, &dmabuf->cq_event.cqe.rcqe_cmpl);
11779	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi);
11780	if (!vport || !(vport->vpi_state & LPFC_VPI_REGISTERED)) {
11781		/* throw out the frame */
11782		lpfc_in_buf_free(phba, &dmabuf->dbuf);
11783		return;
11784	}
11785	/* Handle the basic abort sequence (BA_ABTS) event */
11786	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
11787		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
11788		return;
11789	}
11790
11791	/* Link this frame */
11792	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
11793	if (!seq_dmabuf) {
11794		/* unable to add frame to vport - throw it out */
11795		lpfc_in_buf_free(phba, &dmabuf->dbuf);
11796		return;
11797	}
11798	/* If not last frame in sequence continue processing frames. */
11799	if (!lpfc_seq_complete(seq_dmabuf))
11800		return;
11801
11802	/* Send the complete sequence to the upper layer protocol */
11803	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
11804}
11805
11806/**
11807 * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
11808 * @phba: pointer to lpfc hba data structure.
11809 *
11810 * This routine is invoked to post rpi header templates to the
11811 * HBA consistent with the SLI-4 interface spec.  This routine
11812 * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
11813 * SLI4_PAGE_SIZE modulo 64 rpi context headers.
11814 *
11815 * This routine does not require any locks.  It's usage is expected
11816 * to be driver load or reset recovery when the driver is
11817 * sequential.
11818 *
11819 * Return codes
11820 * 	0 - successful
11821 *      EIO - The mailbox failed to complete successfully.
11822 * 	When this error occurs, the driver is not guaranteed
11823 *	to have any rpi regions posted to the device and
11824 *	must either attempt to repost the regions or take a
11825 *	fatal error.
11826 **/
11827int
11828lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
11829{
11830	struct lpfc_rpi_hdr *rpi_page;
11831	uint32_t rc = 0;
11832
11833	/* Post all rpi memory regions to the port. */
11834	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
11835		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
11836		if (rc != MBX_SUCCESS) {
11837			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11838					"2008 Error %d posting all rpi "
11839					"headers\n", rc);
11840			rc = -EIO;
11841			break;
11842		}
11843	}
11844
11845	return rc;
11846}
11847
11848/**
11849 * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
11850 * @phba: pointer to lpfc hba data structure.
11851 * @rpi_page:  pointer to the rpi memory region.
11852 *
11853 * This routine is invoked to post a single rpi header to the
11854 * HBA consistent with the SLI-4 interface spec.  This memory region
11855 * maps up to 64 rpi context regions.
11856 *
11857 * Return codes
11858 * 	0 - successful
11859 * 	ENOMEM - No available memory
11860 *      EIO - The mailbox failed to complete successfully.
11861 **/
11862int
11863lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
11864{
11865	LPFC_MBOXQ_t *mboxq;
11866	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
11867	uint32_t rc = 0;
11868	uint32_t mbox_tmo;
11869	uint32_t shdr_status, shdr_add_status;
11870	union lpfc_sli4_cfg_shdr *shdr;
11871
11872	/* The port is notified of the header region via a mailbox command. */
11873	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
11874	if (!mboxq) {
11875		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11876				"2001 Unable to allocate memory for issuing "
11877				"SLI_CONFIG_SPECIAL mailbox command\n");
11878		return -ENOMEM;
11879	}
11880
11881	/* Post all rpi memory regions to the port. */
11882	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
11883	mbox_tmo = lpfc_mbox_tmo_val(phba, MBX_SLI4_CONFIG);
11884	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
11885			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
11886			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
11887			 sizeof(struct mbox_header), LPFC_SLI4_MBX_EMBED);
11888	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
11889	       hdr_tmpl, rpi_page->page_count);
11890	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
11891	       rpi_page->start_rpi);
11892	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
11893	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
11894	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
11895	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
11896	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
11897	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
11898	if (rc != MBX_TIMEOUT)
11899		mempool_free(mboxq, phba->mbox_mem_pool);
11900	if (shdr_status || shdr_add_status || rc) {
11901		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11902				"2514 POST_RPI_HDR mailbox failed with "
11903				"status x%x add_status x%x, mbx status x%x\n",
11904				shdr_status, shdr_add_status, rc);
11905		rc = -ENXIO;
11906	}
11907	return rc;
11908}
11909
11910/**
11911 * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
11912 * @phba: pointer to lpfc hba data structure.
11913 *
11914 * This routine is invoked to post rpi header templates to the
11915 * HBA consistent with the SLI-4 interface spec.  This routine
11916 * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
11917 * SLI4_PAGE_SIZE modulo 64 rpi context headers.
11918 *
11919 * Returns
11920 * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
11921 * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
11922 **/
11923int
11924lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
11925{
11926	int rpi;
11927	uint16_t max_rpi, rpi_base, rpi_limit;
11928	uint16_t rpi_remaining;
11929	struct lpfc_rpi_hdr *rpi_hdr;
11930
11931	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
11932	rpi_base = phba->sli4_hba.max_cfg_param.rpi_base;
11933	rpi_limit = phba->sli4_hba.next_rpi;
11934
11935	/*
11936	 * The valid rpi range is not guaranteed to be zero-based.  Start
11937	 * the search at the rpi_base as reported by the port.
11938	 */
11939	spin_lock_irq(&phba->hbalock);
11940	rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, rpi_base);
11941	if (rpi >= rpi_limit || rpi < rpi_base)
11942		rpi = LPFC_RPI_ALLOC_ERROR;
11943	else {
11944		set_bit(rpi, phba->sli4_hba.rpi_bmask);
11945		phba->sli4_hba.max_cfg_param.rpi_used++;
11946		phba->sli4_hba.rpi_count++;
11947	}
11948
11949	/*
11950	 * Don't try to allocate more rpi header regions if the device limit
11951	 * on available rpis max has been exhausted.
11952	 */
11953	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
11954	    (phba->sli4_hba.rpi_count >= max_rpi)) {
11955		spin_unlock_irq(&phba->hbalock);
11956		return rpi;
11957	}
11958
11959	/*
11960	 * If the driver is running low on rpi resources, allocate another
11961	 * page now.  Note that the next_rpi value is used because
11962	 * it represents how many are actually in use whereas max_rpi notes
11963	 * how many are supported max by the device.
11964	 */
11965	rpi_remaining = phba->sli4_hba.next_rpi - rpi_base -
11966		phba->sli4_hba.rpi_count;
11967	spin_unlock_irq(&phba->hbalock);
11968	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
11969		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
11970		if (!rpi_hdr) {
11971			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11972					"2002 Error Could not grow rpi "
11973					"count\n");
11974		} else {
11975			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
11976		}
11977	}
11978
11979	return rpi;
11980}
11981
11982/**
11983 * lpfc_sli4_free_rpi - Release an rpi for reuse.
11984 * @phba: pointer to lpfc hba data structure.
11985 *
11986 * This routine is invoked to release an rpi to the pool of
11987 * available rpis maintained by the driver.
11988 **/
11989void
11990__lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
11991{
11992	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
11993		phba->sli4_hba.rpi_count--;
11994		phba->sli4_hba.max_cfg_param.rpi_used--;
11995	}
11996}
11997
11998/**
11999 * lpfc_sli4_free_rpi - Release an rpi for reuse.
12000 * @phba: pointer to lpfc hba data structure.
12001 *
12002 * This routine is invoked to release an rpi to the pool of
12003 * available rpis maintained by the driver.
12004 **/
12005void
12006lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
12007{
12008	spin_lock_irq(&phba->hbalock);
12009	__lpfc_sli4_free_rpi(phba, rpi);
12010	spin_unlock_irq(&phba->hbalock);
12011}
12012
12013/**
12014 * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
12015 * @phba: pointer to lpfc hba data structure.
12016 *
12017 * This routine is invoked to remove the memory region that
12018 * provided rpi via a bitmask.
12019 **/
12020void
12021lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
12022{
12023	kfree(phba->sli4_hba.rpi_bmask);
12024}
12025
12026/**
12027 * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
12028 * @phba: pointer to lpfc hba data structure.
12029 *
12030 * This routine is invoked to remove the memory region that
12031 * provided rpi via a bitmask.
12032 **/
12033int
12034lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp)
12035{
12036	LPFC_MBOXQ_t *mboxq;
12037	struct lpfc_hba *phba = ndlp->phba;
12038	int rc;
12039
12040	/* The port is notified of the header region via a mailbox command. */
12041	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12042	if (!mboxq)
12043		return -ENOMEM;
12044
12045	/* Post all rpi memory regions to the port. */
12046	lpfc_resume_rpi(mboxq, ndlp);
12047	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
12048	if (rc == MBX_NOT_FINISHED) {
12049		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12050				"2010 Resume RPI Mailbox failed "
12051				"status %d, mbxStatus x%x\n", rc,
12052				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
12053		mempool_free(mboxq, phba->mbox_mem_pool);
12054		return -EIO;
12055	}
12056	return 0;
12057}
12058
12059/**
12060 * lpfc_sli4_init_vpi - Initialize a vpi with the port
12061 * @phba: pointer to lpfc hba data structure.
12062 * @vpi: vpi value to activate with the port.
12063 *
12064 * This routine is invoked to activate a vpi with the
12065 * port when the host intends to use vports with a
12066 * nonzero vpi.
12067 *
12068 * Returns:
12069 *    0 success
12070 *    -Evalue otherwise
12071 **/
12072int
12073lpfc_sli4_init_vpi(struct lpfc_hba *phba, uint16_t vpi)
12074{
12075	LPFC_MBOXQ_t *mboxq;
12076	int rc = 0;
12077	int retval = MBX_SUCCESS;
12078	uint32_t mbox_tmo;
12079
12080	if (vpi == 0)
12081		return -EINVAL;
12082	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12083	if (!mboxq)
12084		return -ENOMEM;
12085	lpfc_init_vpi(phba, mboxq, vpi);
12086	mbox_tmo = lpfc_mbox_tmo_val(phba, MBX_INIT_VPI);
12087	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
12088	if (rc != MBX_SUCCESS) {
12089		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12090				"2022 INIT VPI Mailbox failed "
12091				"status %d, mbxStatus x%x\n", rc,
12092				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
12093		retval = -EIO;
12094	}
12095	if (rc != MBX_TIMEOUT)
12096		mempool_free(mboxq, phba->mbox_mem_pool);
12097
12098	return retval;
12099}
12100
12101/**
12102 * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
12103 * @phba: pointer to lpfc hba data structure.
12104 * @mboxq: Pointer to mailbox object.
12105 *
12106 * This routine is invoked to manually add a single FCF record. The caller
12107 * must pass a completely initialized FCF_Record.  This routine takes
12108 * care of the nonembedded mailbox operations.
12109 **/
12110static void
12111lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
12112{
12113	void *virt_addr;
12114	union lpfc_sli4_cfg_shdr *shdr;
12115	uint32_t shdr_status, shdr_add_status;
12116
12117	virt_addr = mboxq->sge_array->addr[0];
12118	/* The IOCTL status is embedded in the mailbox subheader. */
12119	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
12120	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
12121	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
12122
12123	if ((shdr_status || shdr_add_status) &&
12124		(shdr_status != STATUS_FCF_IN_USE))
12125		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12126			"2558 ADD_FCF_RECORD mailbox failed with "
12127			"status x%x add_status x%x\n",
12128			shdr_status, shdr_add_status);
12129
12130	lpfc_sli4_mbox_cmd_free(phba, mboxq);
12131}
12132
12133/**
12134 * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
12135 * @phba: pointer to lpfc hba data structure.
12136 * @fcf_record:  pointer to the initialized fcf record to add.
12137 *
12138 * This routine is invoked to manually add a single FCF record. The caller
12139 * must pass a completely initialized FCF_Record.  This routine takes
12140 * care of the nonembedded mailbox operations.
12141 **/
12142int
12143lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
12144{
12145	int rc = 0;
12146	LPFC_MBOXQ_t *mboxq;
12147	uint8_t *bytep;
12148	void *virt_addr;
12149	dma_addr_t phys_addr;
12150	struct lpfc_mbx_sge sge;
12151	uint32_t alloc_len, req_len;
12152	uint32_t fcfindex;
12153
12154	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12155	if (!mboxq) {
12156		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12157			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
12158		return -ENOMEM;
12159	}
12160
12161	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
12162		  sizeof(uint32_t);
12163
12164	/* Allocate DMA memory and set up the non-embedded mailbox command */
12165	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
12166				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
12167				     req_len, LPFC_SLI4_MBX_NEMBED);
12168	if (alloc_len < req_len) {
12169		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12170			"2523 Allocated DMA memory size (x%x) is "
12171			"less than the requested DMA memory "
12172			"size (x%x)\n", alloc_len, req_len);
12173		lpfc_sli4_mbox_cmd_free(phba, mboxq);
12174		return -ENOMEM;
12175	}
12176
12177	/*
12178	 * Get the first SGE entry from the non-embedded DMA memory.  This
12179	 * routine only uses a single SGE.
12180	 */
12181	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
12182	phys_addr = getPaddr(sge.pa_hi, sge.pa_lo);
12183	virt_addr = mboxq->sge_array->addr[0];
12184	/*
12185	 * Configure the FCF record for FCFI 0.  This is the driver's
12186	 * hardcoded default and gets used in nonFIP mode.
12187	 */
12188	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
12189	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
12190	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
12191
12192	/*
12193	 * Copy the fcf_index and the FCF Record Data. The data starts after
12194	 * the FCoE header plus word10. The data copy needs to be endian
12195	 * correct.
12196	 */
12197	bytep += sizeof(uint32_t);
12198	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
12199	mboxq->vport = phba->pport;
12200	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
12201	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
12202	if (rc == MBX_NOT_FINISHED) {
12203		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12204			"2515 ADD_FCF_RECORD mailbox failed with "
12205			"status 0x%x\n", rc);
12206		lpfc_sli4_mbox_cmd_free(phba, mboxq);
12207		rc = -EIO;
12208	} else
12209		rc = 0;
12210
12211	return rc;
12212}
12213
12214/**
12215 * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
12216 * @phba: pointer to lpfc hba data structure.
12217 * @fcf_record:  pointer to the fcf record to write the default data.
12218 * @fcf_index: FCF table entry index.
12219 *
12220 * This routine is invoked to build the driver's default FCF record.  The
12221 * values used are hardcoded.  This routine handles memory initialization.
12222 *
12223 **/
12224void
12225lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
12226				struct fcf_record *fcf_record,
12227				uint16_t fcf_index)
12228{
12229	memset(fcf_record, 0, sizeof(struct fcf_record));
12230	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
12231	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
12232	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
12233	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
12234	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
12235	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
12236	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
12237	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
12238	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
12239	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
12240	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
12241	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
12242	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
12243	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
12244	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
12245	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
12246		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
12247	/* Set the VLAN bit map */
12248	if (phba->valid_vlan) {
12249		fcf_record->vlan_bitmap[phba->vlan_id / 8]
12250			= 1 << (phba->vlan_id % 8);
12251	}
12252}
12253
12254/**
12255 * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
12256 * @phba: pointer to lpfc hba data structure.
12257 * @fcf_index: FCF table entry offset.
12258 *
12259 * This routine is invoked to scan the entire FCF table by reading FCF
12260 * record and processing it one at a time starting from the @fcf_index
12261 * for initial FCF discovery or fast FCF failover rediscovery.
12262 *
12263 * Return 0 if the mailbox command is submitted sucessfully, none 0
12264 * otherwise.
12265 **/
12266int
12267lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
12268{
12269	int rc = 0, error;
12270	LPFC_MBOXQ_t *mboxq;
12271
12272	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
12273	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12274	if (!mboxq) {
12275		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12276				"2000 Failed to allocate mbox for "
12277				"READ_FCF cmd\n");
12278		error = -ENOMEM;
12279		goto fail_fcf_scan;
12280	}
12281	/* Construct the read FCF record mailbox command */
12282	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
12283	if (rc) {
12284		error = -EINVAL;
12285		goto fail_fcf_scan;
12286	}
12287	/* Issue the mailbox command asynchronously */
12288	mboxq->vport = phba->pport;
12289	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
12290	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
12291	if (rc == MBX_NOT_FINISHED)
12292		error = -EIO;
12293	else {
12294		spin_lock_irq(&phba->hbalock);
12295		phba->hba_flag |= FCF_DISC_INPROGRESS;
12296		spin_unlock_irq(&phba->hbalock);
12297		/* Reset eligible FCF count for new scan */
12298		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
12299			phba->fcf.eligible_fcf_cnt = 0;
12300		error = 0;
12301	}
12302fail_fcf_scan:
12303	if (error) {
12304		if (mboxq)
12305			lpfc_sli4_mbox_cmd_free(phba, mboxq);
12306		/* FCF scan failed, clear FCF_DISC_INPROGRESS flag */
12307		spin_lock_irq(&phba->hbalock);
12308		phba->hba_flag &= ~FCF_DISC_INPROGRESS;
12309		spin_unlock_irq(&phba->hbalock);
12310	}
12311	return error;
12312}
12313
12314/**
12315 * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for round robin fcf.
12316 * @phba: pointer to lpfc hba data structure.
12317 * @fcf_index: FCF table entry offset.
12318 *
12319 * This routine is invoked to read an FCF record indicated by @fcf_index
12320 * and to use it for FLOGI round robin FCF failover.
12321 *
12322 * Return 0 if the mailbox command is submitted sucessfully, none 0
12323 * otherwise.
12324 **/
12325int
12326lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
12327{
12328	int rc = 0, error;
12329	LPFC_MBOXQ_t *mboxq;
12330
12331	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12332	if (!mboxq) {
12333		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
12334				"2763 Failed to allocate mbox for "
12335				"READ_FCF cmd\n");
12336		error = -ENOMEM;
12337		goto fail_fcf_read;
12338	}
12339	/* Construct the read FCF record mailbox command */
12340	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
12341	if (rc) {
12342		error = -EINVAL;
12343		goto fail_fcf_read;
12344	}
12345	/* Issue the mailbox command asynchronously */
12346	mboxq->vport = phba->pport;
12347	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
12348	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
12349	if (rc == MBX_NOT_FINISHED)
12350		error = -EIO;
12351	else
12352		error = 0;
12353
12354fail_fcf_read:
12355	if (error && mboxq)
12356		lpfc_sli4_mbox_cmd_free(phba, mboxq);
12357	return error;
12358}
12359
12360/**
12361 * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
12362 * @phba: pointer to lpfc hba data structure.
12363 * @fcf_index: FCF table entry offset.
12364 *
12365 * This routine is invoked to read an FCF record indicated by @fcf_index to
12366 * determine whether it's eligible for FLOGI round robin failover list.
12367 *
12368 * Return 0 if the mailbox command is submitted sucessfully, none 0
12369 * otherwise.
12370 **/
12371int
12372lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
12373{
12374	int rc = 0, error;
12375	LPFC_MBOXQ_t *mboxq;
12376
12377	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12378	if (!mboxq) {
12379		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
12380				"2758 Failed to allocate mbox for "
12381				"READ_FCF cmd\n");
12382				error = -ENOMEM;
12383				goto fail_fcf_read;
12384	}
12385	/* Construct the read FCF record mailbox command */
12386	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
12387	if (rc) {
12388		error = -EINVAL;
12389		goto fail_fcf_read;
12390	}
12391	/* Issue the mailbox command asynchronously */
12392	mboxq->vport = phba->pport;
12393	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
12394	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
12395	if (rc == MBX_NOT_FINISHED)
12396		error = -EIO;
12397	else
12398		error = 0;
12399
12400fail_fcf_read:
12401	if (error && mboxq)
12402		lpfc_sli4_mbox_cmd_free(phba, mboxq);
12403	return error;
12404}
12405
12406/**
12407 * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
12408 * @phba: pointer to lpfc hba data structure.
12409 *
12410 * This routine is to get the next eligible FCF record index in a round
12411 * robin fashion. If the next eligible FCF record index equals to the
12412 * initial round robin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
12413 * shall be returned, otherwise, the next eligible FCF record's index
12414 * shall be returned.
12415 **/
12416uint16_t
12417lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
12418{
12419	uint16_t next_fcf_index;
12420
12421	/* Search start from next bit of currently registered FCF index */
12422	next_fcf_index = (phba->fcf.current_rec.fcf_indx + 1) %
12423					LPFC_SLI4_FCF_TBL_INDX_MAX;
12424	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
12425				       LPFC_SLI4_FCF_TBL_INDX_MAX,
12426				       next_fcf_index);
12427
12428	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
12429	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX)
12430		next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
12431					       LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
12432
12433	/* Check roundrobin failover list empty condition */
12434	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
12435		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
12436				"2844 No roundrobin failover FCF available\n");
12437		return LPFC_FCOE_FCF_NEXT_NONE;
12438	}
12439
12440	/* Check roundrobin failover index bmask stop condition */
12441	if (next_fcf_index == phba->fcf.fcf_rr_init_indx) {
12442		if (!(phba->fcf.fcf_flag & FCF_REDISC_RRU)) {
12443			lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
12444					"2847 Round robin failover FCF index "
12445					"search hit stop condition:x%x\n",
12446					next_fcf_index);
12447			return LPFC_FCOE_FCF_NEXT_NONE;
12448		}
12449		/* The roundrobin failover index bmask updated, start over */
12450		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
12451				"2848 Round robin failover FCF index bmask "
12452				"updated, start over\n");
12453		spin_lock_irq(&phba->hbalock);
12454		phba->fcf.fcf_flag &= ~FCF_REDISC_RRU;
12455		spin_unlock_irq(&phba->hbalock);
12456		return phba->fcf.fcf_rr_init_indx;
12457	}
12458
12459	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
12460			"2845 Get next round robin failover "
12461			"FCF index x%x\n", next_fcf_index);
12462	return next_fcf_index;
12463}
12464
12465/**
12466 * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
12467 * @phba: pointer to lpfc hba data structure.
12468 *
12469 * This routine sets the FCF record index in to the eligible bmask for
12470 * round robin failover search. It checks to make sure that the index
12471 * does not go beyond the range of the driver allocated bmask dimension
12472 * before setting the bit.
12473 *
12474 * Returns 0 if the index bit successfully set, otherwise, it returns
12475 * -EINVAL.
12476 **/
12477int
12478lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
12479{
12480	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
12481		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
12482				"2610 HBA FCF index reached driver's "
12483				"book keeping dimension: fcf_index:%d, "
12484				"driver_bmask_max:%d\n",
12485				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
12486		return -EINVAL;
12487	}
12488	/* Set the eligible FCF record index bmask */
12489	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
12490
12491	/* Set the roundrobin index bmask updated */
12492	spin_lock_irq(&phba->hbalock);
12493	phba->fcf.fcf_flag |= FCF_REDISC_RRU;
12494	spin_unlock_irq(&phba->hbalock);
12495
12496	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
12497			"2790 Set FCF index x%x to round robin failover "
12498			"bmask\n", fcf_index);
12499
12500	return 0;
12501}
12502
12503/**
12504 * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
12505 * @phba: pointer to lpfc hba data structure.
12506 *
12507 * This routine clears the FCF record index from the eligible bmask for
12508 * round robin failover search. It checks to make sure that the index
12509 * does not go beyond the range of the driver allocated bmask dimension
12510 * before clearing the bit.
12511 **/
12512void
12513lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
12514{
12515	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
12516		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
12517				"2762 HBA FCF index goes beyond driver's "
12518				"book keeping dimension: fcf_index:%d, "
12519				"driver_bmask_max:%d\n",
12520				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
12521		return;
12522	}
12523	/* Clear the eligible FCF record index bmask */
12524	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
12525
12526	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
12527			"2791 Clear FCF index x%x from round robin failover "
12528			"bmask\n", fcf_index);
12529}
12530
12531/**
12532 * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
12533 * @phba: pointer to lpfc hba data structure.
12534 *
12535 * This routine is the completion routine for the rediscover FCF table mailbox
12536 * command. If the mailbox command returned failure, it will try to stop the
12537 * FCF rediscover wait timer.
12538 **/
12539void
12540lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
12541{
12542	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
12543	uint32_t shdr_status, shdr_add_status;
12544
12545	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
12546
12547	shdr_status = bf_get(lpfc_mbox_hdr_status,
12548			     &redisc_fcf->header.cfg_shdr.response);
12549	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
12550			     &redisc_fcf->header.cfg_shdr.response);
12551	if (shdr_status || shdr_add_status) {
12552		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
12553				"2746 Requesting for FCF rediscovery failed "
12554				"status x%x add_status x%x\n",
12555				shdr_status, shdr_add_status);
12556		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
12557			spin_lock_irq(&phba->hbalock);
12558			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
12559			spin_unlock_irq(&phba->hbalock);
12560			/*
12561			 * CVL event triggered FCF rediscover request failed,
12562			 * last resort to re-try current registered FCF entry.
12563			 */
12564			lpfc_retry_pport_discovery(phba);
12565		} else {
12566			spin_lock_irq(&phba->hbalock);
12567			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
12568			spin_unlock_irq(&phba->hbalock);
12569			/*
12570			 * DEAD FCF event triggered FCF rediscover request
12571			 * failed, last resort to fail over as a link down
12572			 * to FCF registration.
12573			 */
12574			lpfc_sli4_fcf_dead_failthrough(phba);
12575		}
12576	} else {
12577		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
12578				"2775 Start FCF rediscovery quiescent period "
12579				"wait timer before scaning FCF table\n");
12580		/*
12581		 * Start FCF rediscovery wait timer for pending FCF
12582		 * before rescan FCF record table.
12583		 */
12584		lpfc_fcf_redisc_wait_start_timer(phba);
12585	}
12586
12587	mempool_free(mbox, phba->mbox_mem_pool);
12588}
12589
12590/**
12591 * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
12592 * @phba: pointer to lpfc hba data structure.
12593 *
12594 * This routine is invoked to request for rediscovery of the entire FCF table
12595 * by the port.
12596 **/
12597int
12598lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
12599{
12600	LPFC_MBOXQ_t *mbox;
12601	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
12602	int rc, length;
12603
12604	/* Cancel retry delay timers to all vports before FCF rediscover */
12605	lpfc_cancel_all_vport_retry_delay_timer(phba);
12606
12607	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12608	if (!mbox) {
12609		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12610				"2745 Failed to allocate mbox for "
12611				"requesting FCF rediscover.\n");
12612		return -ENOMEM;
12613	}
12614
12615	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
12616		  sizeof(struct lpfc_sli4_cfg_mhdr));
12617	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
12618			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
12619			 length, LPFC_SLI4_MBX_EMBED);
12620
12621	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
12622	/* Set count to 0 for invalidating the entire FCF database */
12623	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
12624
12625	/* Issue the mailbox command asynchronously */
12626	mbox->vport = phba->pport;
12627	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
12628	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
12629
12630	if (rc == MBX_NOT_FINISHED) {
12631		mempool_free(mbox, phba->mbox_mem_pool);
12632		return -EIO;
12633	}
12634	return 0;
12635}
12636
12637/**
12638 * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
12639 * @phba: pointer to lpfc hba data structure.
12640 *
12641 * This function is the failover routine as a last resort to the FCF DEAD
12642 * event when driver failed to perform fast FCF failover.
12643 **/
12644void
12645lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
12646{
12647	uint32_t link_state;
12648
12649	/*
12650	 * Last resort as FCF DEAD event failover will treat this as
12651	 * a link down, but save the link state because we don't want
12652	 * it to be changed to Link Down unless it is already down.
12653	 */
12654	link_state = phba->link_state;
12655	lpfc_linkdown(phba);
12656	phba->link_state = link_state;
12657
12658	/* Unregister FCF if no devices connected to it */
12659	lpfc_unregister_unused_fcf(phba);
12660}
12661
12662/**
12663 * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
12664 * @phba: pointer to lpfc hba data structure.
12665 *
12666 * This function read region 23 and parse TLV for port status to
12667 * decide if the user disaled the port. If the TLV indicates the
12668 * port is disabled, the hba_flag is set accordingly.
12669 **/
12670void
12671lpfc_sli_read_link_ste(struct lpfc_hba *phba)
12672{
12673	LPFC_MBOXQ_t *pmb = NULL;
12674	MAILBOX_t *mb;
12675	uint8_t *rgn23_data = NULL;
12676	uint32_t offset = 0, data_size, sub_tlv_len, tlv_offset;
12677	int rc;
12678
12679	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
12680	if (!pmb) {
12681		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12682			"2600 lpfc_sli_read_serdes_param failed to"
12683			" allocate mailbox memory\n");
12684		goto out;
12685	}
12686	mb = &pmb->u.mb;
12687
12688	/* Get adapter Region 23 data */
12689	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
12690	if (!rgn23_data)
12691		goto out;
12692
12693	do {
12694		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
12695		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
12696
12697		if (rc != MBX_SUCCESS) {
12698			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
12699				"2601 lpfc_sli_read_link_ste failed to"
12700				" read config region 23 rc 0x%x Status 0x%x\n",
12701				rc, mb->mbxStatus);
12702			mb->un.varDmp.word_cnt = 0;
12703		}
12704		/*
12705		 * dump mem may return a zero when finished or we got a
12706		 * mailbox error, either way we are done.
12707		 */
12708		if (mb->un.varDmp.word_cnt == 0)
12709			break;
12710		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
12711			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
12712
12713		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
12714			rgn23_data + offset,
12715			mb->un.varDmp.word_cnt);
12716		offset += mb->un.varDmp.word_cnt;
12717	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
12718
12719	data_size = offset;
12720	offset = 0;
12721
12722	if (!data_size)
12723		goto out;
12724
12725	/* Check the region signature first */
12726	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
12727		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12728			"2619 Config region 23 has bad signature\n");
12729			goto out;
12730	}
12731	offset += 4;
12732
12733	/* Check the data structure version */
12734	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
12735		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12736			"2620 Config region 23 has bad version\n");
12737		goto out;
12738	}
12739	offset += 4;
12740
12741	/* Parse TLV entries in the region */
12742	while (offset < data_size) {
12743		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
12744			break;
12745		/*
12746		 * If the TLV is not driver specific TLV or driver id is
12747		 * not linux driver id, skip the record.
12748		 */
12749		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
12750		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
12751		    (rgn23_data[offset + 3] != 0)) {
12752			offset += rgn23_data[offset + 1] * 4 + 4;
12753			continue;
12754		}
12755
12756		/* Driver found a driver specific TLV in the config region */
12757		sub_tlv_len = rgn23_data[offset + 1] * 4;
12758		offset += 4;
12759		tlv_offset = 0;
12760
12761		/*
12762		 * Search for configured port state sub-TLV.
12763		 */
12764		while ((offset < data_size) &&
12765			(tlv_offset < sub_tlv_len)) {
12766			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
12767				offset += 4;
12768				tlv_offset += 4;
12769				break;
12770			}
12771			if (rgn23_data[offset] != PORT_STE_TYPE) {
12772				offset += rgn23_data[offset + 1] * 4 + 4;
12773				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
12774				continue;
12775			}
12776
12777			/* This HBA contains PORT_STE configured */
12778			if (!rgn23_data[offset + 2])
12779				phba->hba_flag |= LINK_DISABLED;
12780
12781			goto out;
12782		}
12783	}
12784out:
12785	if (pmb)
12786		mempool_free(pmb, phba->mbox_mem_pool);
12787	kfree(rgn23_data);
12788	return;
12789}
12790
12791/**
12792 * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
12793 * @vport: pointer to vport data structure.
12794 *
12795 * This function iterate through the mailboxq and clean up all REG_LOGIN
12796 * and REG_VPI mailbox commands associated with the vport. This function
12797 * is called when driver want to restart discovery of the vport due to
12798 * a Clear Virtual Link event.
12799 **/
12800void
12801lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
12802{
12803	struct lpfc_hba *phba = vport->phba;
12804	LPFC_MBOXQ_t *mb, *nextmb;
12805	struct lpfc_dmabuf *mp;
12806	struct lpfc_nodelist *ndlp;
12807	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
12808
12809	spin_lock_irq(&phba->hbalock);
12810	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
12811		if (mb->vport != vport)
12812			continue;
12813
12814		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
12815			(mb->u.mb.mbxCommand != MBX_REG_VPI))
12816			continue;
12817
12818		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
12819			if (phba->sli_rev == LPFC_SLI_REV4)
12820				__lpfc_sli4_free_rpi(phba,
12821						mb->u.mb.un.varRegLogin.rpi);
12822			mp = (struct lpfc_dmabuf *) (mb->context1);
12823			if (mp) {
12824				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
12825				kfree(mp);
12826			}
12827			ndlp = (struct lpfc_nodelist *) mb->context2;
12828			if (ndlp) {
12829				spin_lock_irq(shost->host_lock);
12830				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
12831				spin_unlock_irq(shost->host_lock);
12832				lpfc_nlp_put(ndlp);
12833				mb->context2 = NULL;
12834			}
12835		}
12836		list_del(&mb->list);
12837		mempool_free(mb, phba->mbox_mem_pool);
12838	}
12839	mb = phba->sli.mbox_active;
12840	if (mb && (mb->vport == vport)) {
12841		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
12842			(mb->u.mb.mbxCommand == MBX_REG_VPI))
12843			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
12844		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
12845			ndlp = (struct lpfc_nodelist *) mb->context2;
12846			if (ndlp) {
12847				spin_lock_irq(shost->host_lock);
12848				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
12849				spin_unlock_irq(shost->host_lock);
12850				lpfc_nlp_put(ndlp);
12851				mb->context2 = NULL;
12852			}
12853			/* Unregister the RPI when mailbox complete */
12854			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
12855		}
12856	}
12857	spin_unlock_irq(&phba->hbalock);
12858}
12859
12860/**
12861 * lpfc_drain_txq - Drain the txq
12862 * @phba: Pointer to HBA context object.
12863 *
12864 * This function attempt to submit IOCBs on the txq
12865 * to the adapter.  For SLI4 adapters, the txq contains
12866 * ELS IOCBs that have been deferred because the there
12867 * are no SGLs.  This congestion can occur with large
12868 * vport counts during node discovery.
12869 **/
12870
12871uint32_t
12872lpfc_drain_txq(struct lpfc_hba *phba)
12873{
12874	LIST_HEAD(completions);
12875	struct lpfc_sli_ring *pring = &phba->sli.ring[LPFC_ELS_RING];
12876	struct lpfc_iocbq *piocbq = 0;
12877	unsigned long iflags = 0;
12878	char *fail_msg = NULL;
12879	struct lpfc_sglq *sglq;
12880	union lpfc_wqe wqe;
12881
12882	spin_lock_irqsave(&phba->hbalock, iflags);
12883	if (pring->txq_cnt > pring->txq_max)
12884		pring->txq_max = pring->txq_cnt;
12885
12886	spin_unlock_irqrestore(&phba->hbalock, iflags);
12887
12888	while (pring->txq_cnt) {
12889		spin_lock_irqsave(&phba->hbalock, iflags);
12890
12891		sglq = __lpfc_sli_get_sglq(phba);
12892		if (!sglq) {
12893			spin_unlock_irqrestore(&phba->hbalock, iflags);
12894			break;
12895		} else {
12896			piocbq = lpfc_sli_ringtx_get(phba, pring);
12897			if (!piocbq) {
12898				/* The txq_cnt out of sync. This should
12899				 * never happen
12900				 */
12901				sglq = __lpfc_clear_active_sglq(phba,
12902						 sglq->sli4_xritag);
12903				spin_unlock_irqrestore(&phba->hbalock, iflags);
12904				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12905					"2823 txq empty and txq_cnt is %d\n ",
12906					pring->txq_cnt);
12907				break;
12908			}
12909		}
12910
12911		/* The xri and iocb resources secured,
12912		 * attempt to issue request
12913		 */
12914		piocbq->sli4_xritag = sglq->sli4_xritag;
12915		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
12916			fail_msg = "to convert bpl to sgl";
12917		else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
12918			fail_msg = "to convert iocb to wqe";
12919		else if (lpfc_sli4_wq_put(phba->sli4_hba.els_wq, &wqe))
12920			fail_msg = " - Wq is full";
12921		else
12922			lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
12923
12924		if (fail_msg) {
12925			/* Failed means we can't issue and need to cancel */
12926			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12927					"2822 IOCB failed %s iotag 0x%x "
12928					"xri 0x%x\n",
12929					fail_msg,
12930					piocbq->iotag, piocbq->sli4_xritag);
12931			list_add_tail(&piocbq->list, &completions);
12932		}
12933		spin_unlock_irqrestore(&phba->hbalock, iflags);
12934	}
12935
12936	/* Cancel all the IOCBs that cannot be issued */
12937	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
12938				IOERR_SLI_ABORTED);
12939
12940	return pring->txq_cnt;
12941}
12942