xref: /linux/drivers/scsi/lpfc/lpfc_sli.c (revision 55c70bffc772897f00336b36ff74a4007f7a346d)
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2018 Broadcom. All Rights Reserved. The term *
5  * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.  *
6  * Copyright (C) 2004-2016 Emulex.  All rights reserved.           *
7  * EMULEX and SLI are trademarks of Emulex.                        *
8  * www.broadcom.com                                                *
9  * Portions Copyright (C) 2004-2005 Christoph Hellwig              *
10  *                                                                 *
11  * This program is free software; you can redistribute it and/or   *
12  * modify it under the terms of version 2 of the GNU General       *
13  * Public License as published by the Free Software Foundation.    *
14  * This program is distributed in the hope that it will be useful. *
15  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND          *
16  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,  *
17  * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE      *
18  * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
19  * TO BE LEGALLY INVALID.  See the GNU General Public License for  *
20  * more details, a copy of which can be found in the file COPYING  *
21  * included with this package.                                     *
22  *******************************************************************/
23 
24 #include <linux/blkdev.h>
25 #include <linux/pci.h>
26 #include <linux/interrupt.h>
27 #include <linux/delay.h>
28 #include <linux/slab.h>
29 #include <linux/lockdep.h>
30 
31 #include <scsi/scsi.h>
32 #include <scsi/scsi_cmnd.h>
33 #include <scsi/scsi_device.h>
34 #include <scsi/scsi_host.h>
35 #include <scsi/scsi_transport_fc.h>
36 #include <scsi/fc/fc_fs.h>
37 #include <linux/aer.h>
38 #ifdef CONFIG_X86
39 #include <asm/set_memory.h>
40 #endif
41 
42 #include <linux/nvme-fc-driver.h>
43 
44 #include "lpfc_hw4.h"
45 #include "lpfc_hw.h"
46 #include "lpfc_sli.h"
47 #include "lpfc_sli4.h"
48 #include "lpfc_nl.h"
49 #include "lpfc_disc.h"
50 #include "lpfc.h"
51 #include "lpfc_scsi.h"
52 #include "lpfc_nvme.h"
53 #include "lpfc_nvmet.h"
54 #include "lpfc_crtn.h"
55 #include "lpfc_logmsg.h"
56 #include "lpfc_compat.h"
57 #include "lpfc_debugfs.h"
58 #include "lpfc_vport.h"
59 #include "lpfc_version.h"
60 
61 /* There are only four IOCB completion types. */
62 typedef enum _lpfc_iocb_type {
63 	LPFC_UNKNOWN_IOCB,
64 	LPFC_UNSOL_IOCB,
65 	LPFC_SOL_IOCB,
66 	LPFC_ABORT_IOCB
67 } lpfc_iocb_type;
68 
69 
70 /* Provide function prototypes local to this module. */
71 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
72 				  uint32_t);
73 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
74 			      uint8_t *, uint32_t *);
75 static struct lpfc_iocbq *lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *,
76 							 struct lpfc_iocbq *);
77 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
78 				      struct hbq_dmabuf *);
79 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
80 					  struct hbq_dmabuf *dmabuf);
81 static int lpfc_sli4_fp_handle_cqe(struct lpfc_hba *, struct lpfc_queue *,
82 				    struct lpfc_cqe *);
83 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
84 				       int);
85 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
86 				     struct lpfc_eqe *eqe, uint32_t qidx);
87 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
88 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
89 static int lpfc_sli4_abort_nvme_io(struct lpfc_hba *phba,
90 				   struct lpfc_sli_ring *pring,
91 				   struct lpfc_iocbq *cmdiocb);
92 
93 static IOCB_t *
94 lpfc_get_iocb_from_iocbq(struct lpfc_iocbq *iocbq)
95 {
96 	return &iocbq->iocb;
97 }
98 
99 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
100 /**
101  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
102  * @srcp: Source memory pointer.
103  * @destp: Destination memory pointer.
104  * @cnt: Number of words required to be copied.
105  *       Must be a multiple of sizeof(uint64_t)
106  *
107  * This function is used for copying data between driver memory
108  * and the SLI WQ. This function also changes the endianness
109  * of each word if native endianness is different from SLI
110  * endianness. This function can be called with or without
111  * lock.
112  **/
113 void
114 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
115 {
116 	uint64_t *src = srcp;
117 	uint64_t *dest = destp;
118 	int i;
119 
120 	for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
121 		*dest++ = *src++;
122 }
123 #else
124 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
125 #endif
126 
127 /**
128  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
129  * @q: The Work Queue to operate on.
130  * @wqe: The work Queue Entry to put on the Work queue.
131  *
132  * This routine will copy the contents of @wqe to the next available entry on
133  * the @q. This function will then ring the Work Queue Doorbell to signal the
134  * HBA to start processing the Work Queue Entry. This function returns 0 if
135  * successful. If no entries are available on @q then this function will return
136  * -ENOMEM.
137  * The caller is expected to hold the hbalock when calling this routine.
138  **/
139 static int
140 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
141 {
142 	union lpfc_wqe *temp_wqe;
143 	struct lpfc_register doorbell;
144 	uint32_t host_index;
145 	uint32_t idx;
146 	uint32_t i = 0;
147 	uint8_t *tmp;
148 	u32 if_type;
149 
150 	/* sanity check on queue memory */
151 	if (unlikely(!q))
152 		return -ENOMEM;
153 	temp_wqe = q->qe[q->host_index].wqe;
154 
155 	/* If the host has not yet processed the next entry then we are done */
156 	idx = ((q->host_index + 1) % q->entry_count);
157 	if (idx == q->hba_index) {
158 		q->WQ_overflow++;
159 		return -EBUSY;
160 	}
161 	q->WQ_posted++;
162 	/* set consumption flag every once in a while */
163 	if (!((q->host_index + 1) % q->entry_repost))
164 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
165 	else
166 		bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
167 	if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
168 		bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
169 	lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
170 	if (q->dpp_enable && q->phba->cfg_enable_dpp) {
171 		/* write to DPP aperture taking advatage of Combined Writes */
172 		tmp = (uint8_t *)temp_wqe;
173 #ifdef __raw_writeq
174 		for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
175 			__raw_writeq(*((uint64_t *)(tmp + i)),
176 					q->dpp_regaddr + i);
177 #else
178 		for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
179 			__raw_writel(*((uint32_t *)(tmp + i)),
180 					q->dpp_regaddr + i);
181 #endif
182 	}
183 	/* ensure WQE bcopy and DPP flushed before doorbell write */
184 	wmb();
185 
186 	/* Update the host index before invoking device */
187 	host_index = q->host_index;
188 
189 	q->host_index = idx;
190 
191 	/* Ring Doorbell */
192 	doorbell.word0 = 0;
193 	if (q->db_format == LPFC_DB_LIST_FORMAT) {
194 		if (q->dpp_enable && q->phba->cfg_enable_dpp) {
195 			bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
196 			bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
197 			bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
198 			    q->dpp_id);
199 			bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
200 			    q->queue_id);
201 		} else {
202 			bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
203 			bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
204 
205 			/* Leave bits <23:16> clear for if_type 6 dpp */
206 			if_type = bf_get(lpfc_sli_intf_if_type,
207 					 &q->phba->sli4_hba.sli_intf);
208 			if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
209 				bf_set(lpfc_wq_db_list_fm_index, &doorbell,
210 				       host_index);
211 		}
212 	} else if (q->db_format == LPFC_DB_RING_FORMAT) {
213 		bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
214 		bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
215 	} else {
216 		return -EINVAL;
217 	}
218 	writel(doorbell.word0, q->db_regaddr);
219 
220 	return 0;
221 }
222 
223 /**
224  * lpfc_sli4_wq_release - Updates internal hba index for WQ
225  * @q: The Work Queue to operate on.
226  * @index: The index to advance the hba index to.
227  *
228  * This routine will update the HBA index of a queue to reflect consumption of
229  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
230  * an entry the host calls this function to update the queue's internal
231  * pointers. This routine returns the number of entries that were consumed by
232  * the HBA.
233  **/
234 static uint32_t
235 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
236 {
237 	uint32_t released = 0;
238 
239 	/* sanity check on queue memory */
240 	if (unlikely(!q))
241 		return 0;
242 
243 	if (q->hba_index == index)
244 		return 0;
245 	do {
246 		q->hba_index = ((q->hba_index + 1) % q->entry_count);
247 		released++;
248 	} while (q->hba_index != index);
249 	return released;
250 }
251 
252 /**
253  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
254  * @q: The Mailbox Queue to operate on.
255  * @wqe: The Mailbox Queue Entry to put on the Work queue.
256  *
257  * This routine will copy the contents of @mqe to the next available entry on
258  * the @q. This function will then ring the Work Queue Doorbell to signal the
259  * HBA to start processing the Work Queue Entry. This function returns 0 if
260  * successful. If no entries are available on @q then this function will return
261  * -ENOMEM.
262  * The caller is expected to hold the hbalock when calling this routine.
263  **/
264 static uint32_t
265 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
266 {
267 	struct lpfc_mqe *temp_mqe;
268 	struct lpfc_register doorbell;
269 
270 	/* sanity check on queue memory */
271 	if (unlikely(!q))
272 		return -ENOMEM;
273 	temp_mqe = q->qe[q->host_index].mqe;
274 
275 	/* If the host has not yet processed the next entry then we are done */
276 	if (((q->host_index + 1) % q->entry_count) == q->hba_index)
277 		return -ENOMEM;
278 	lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
279 	/* Save off the mailbox pointer for completion */
280 	q->phba->mbox = (MAILBOX_t *)temp_mqe;
281 
282 	/* Update the host index before invoking device */
283 	q->host_index = ((q->host_index + 1) % q->entry_count);
284 
285 	/* Ring Doorbell */
286 	doorbell.word0 = 0;
287 	bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
288 	bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
289 	writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
290 	return 0;
291 }
292 
293 /**
294  * lpfc_sli4_mq_release - Updates internal hba index for MQ
295  * @q: The Mailbox Queue to operate on.
296  *
297  * This routine will update the HBA index of a queue to reflect consumption of
298  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
299  * an entry the host calls this function to update the queue's internal
300  * pointers. This routine returns the number of entries that were consumed by
301  * the HBA.
302  **/
303 static uint32_t
304 lpfc_sli4_mq_release(struct lpfc_queue *q)
305 {
306 	/* sanity check on queue memory */
307 	if (unlikely(!q))
308 		return 0;
309 
310 	/* Clear the mailbox pointer for completion */
311 	q->phba->mbox = NULL;
312 	q->hba_index = ((q->hba_index + 1) % q->entry_count);
313 	return 1;
314 }
315 
316 /**
317  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
318  * @q: The Event Queue to get the first valid EQE from
319  *
320  * This routine will get the first valid Event Queue Entry from @q, update
321  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
322  * the Queue (no more work to do), or the Queue is full of EQEs that have been
323  * processed, but not popped back to the HBA then this routine will return NULL.
324  **/
325 static struct lpfc_eqe *
326 lpfc_sli4_eq_get(struct lpfc_queue *q)
327 {
328 	struct lpfc_hba *phba;
329 	struct lpfc_eqe *eqe;
330 	uint32_t idx;
331 
332 	/* sanity check on queue memory */
333 	if (unlikely(!q))
334 		return NULL;
335 	phba = q->phba;
336 	eqe = q->qe[q->hba_index].eqe;
337 
338 	/* If the next EQE is not valid then we are done */
339 	if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
340 		return NULL;
341 	/* If the host has not yet processed the next entry then we are done */
342 	idx = ((q->hba_index + 1) % q->entry_count);
343 	if (idx == q->host_index)
344 		return NULL;
345 
346 	q->hba_index = idx;
347 	/* if the index wrapped around, toggle the valid bit */
348 	if (phba->sli4_hba.pc_sli4_params.eqav && !q->hba_index)
349 		q->qe_valid = (q->qe_valid) ? 0 : 1;
350 
351 
352 	/*
353 	 * insert barrier for instruction interlock : data from the hardware
354 	 * must have the valid bit checked before it can be copied and acted
355 	 * upon. Speculative instructions were allowing a bcopy at the start
356 	 * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
357 	 * after our return, to copy data before the valid bit check above
358 	 * was done. As such, some of the copied data was stale. The barrier
359 	 * ensures the check is before any data is copied.
360 	 */
361 	mb();
362 	return eqe;
363 }
364 
365 /**
366  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
367  * @q: The Event Queue to disable interrupts
368  *
369  **/
370 inline void
371 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
372 {
373 	struct lpfc_register doorbell;
374 
375 	doorbell.word0 = 0;
376 	bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
377 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
378 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
379 		(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
380 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
381 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
382 }
383 
384 /**
385  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
386  * @q: The Event Queue to disable interrupts
387  *
388  **/
389 inline void
390 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
391 {
392 	struct lpfc_register doorbell;
393 
394 	doorbell.word0 = 0;
395 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
396 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
397 }
398 
399 /**
400  * lpfc_sli4_eq_release - Indicates the host has finished processing an EQ
401  * @q: The Event Queue that the host has completed processing for.
402  * @arm: Indicates whether the host wants to arms this CQ.
403  *
404  * This routine will mark all Event Queue Entries on @q, from the last
405  * known completed entry to the last entry that was processed, as completed
406  * by clearing the valid bit for each completion queue entry. Then it will
407  * notify the HBA, by ringing the doorbell, that the EQEs have been processed.
408  * The internal host index in the @q will be updated by this routine to indicate
409  * that the host has finished processing the entries. The @arm parameter
410  * indicates that the queue should be rearmed when ringing the doorbell.
411  *
412  * This function will return the number of EQEs that were popped.
413  **/
414 uint32_t
415 lpfc_sli4_eq_release(struct lpfc_queue *q, bool arm)
416 {
417 	uint32_t released = 0;
418 	struct lpfc_hba *phba;
419 	struct lpfc_eqe *temp_eqe;
420 	struct lpfc_register doorbell;
421 
422 	/* sanity check on queue memory */
423 	if (unlikely(!q))
424 		return 0;
425 	phba = q->phba;
426 
427 	/* while there are valid entries */
428 	while (q->hba_index != q->host_index) {
429 		if (!phba->sli4_hba.pc_sli4_params.eqav) {
430 			temp_eqe = q->qe[q->host_index].eqe;
431 			bf_set_le32(lpfc_eqe_valid, temp_eqe, 0);
432 		}
433 		released++;
434 		q->host_index = ((q->host_index + 1) % q->entry_count);
435 	}
436 	if (unlikely(released == 0 && !arm))
437 		return 0;
438 
439 	/* ring doorbell for number popped */
440 	doorbell.word0 = 0;
441 	if (arm) {
442 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
443 		bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
444 	}
445 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, released);
446 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
447 	bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
448 			(q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
449 	bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
450 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
451 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
452 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
453 		readl(q->phba->sli4_hba.EQDBregaddr);
454 	return released;
455 }
456 
457 /**
458  * lpfc_sli4_if6_eq_release - Indicates the host has finished processing an EQ
459  * @q: The Event Queue that the host has completed processing for.
460  * @arm: Indicates whether the host wants to arms this CQ.
461  *
462  * This routine will mark all Event Queue Entries on @q, from the last
463  * known completed entry to the last entry that was processed, as completed
464  * by clearing the valid bit for each completion queue entry. Then it will
465  * notify the HBA, by ringing the doorbell, that the EQEs have been processed.
466  * The internal host index in the @q will be updated by this routine to indicate
467  * that the host has finished processing the entries. The @arm parameter
468  * indicates that the queue should be rearmed when ringing the doorbell.
469  *
470  * This function will return the number of EQEs that were popped.
471  **/
472 uint32_t
473 lpfc_sli4_if6_eq_release(struct lpfc_queue *q, bool arm)
474 {
475 	uint32_t released = 0;
476 	struct lpfc_hba *phba;
477 	struct lpfc_eqe *temp_eqe;
478 	struct lpfc_register doorbell;
479 
480 	/* sanity check on queue memory */
481 	if (unlikely(!q))
482 		return 0;
483 	phba = q->phba;
484 
485 	/* while there are valid entries */
486 	while (q->hba_index != q->host_index) {
487 		if (!phba->sli4_hba.pc_sli4_params.eqav) {
488 			temp_eqe = q->qe[q->host_index].eqe;
489 			bf_set_le32(lpfc_eqe_valid, temp_eqe, 0);
490 		}
491 		released++;
492 		q->host_index = ((q->host_index + 1) % q->entry_count);
493 	}
494 	if (unlikely(released == 0 && !arm))
495 		return 0;
496 
497 	/* ring doorbell for number popped */
498 	doorbell.word0 = 0;
499 	if (arm)
500 		bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
501 	bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, released);
502 	bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
503 	writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
504 	/* PCI read to flush PCI pipeline on re-arming for INTx mode */
505 	if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
506 		readl(q->phba->sli4_hba.EQDBregaddr);
507 	return released;
508 }
509 
510 /**
511  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
512  * @q: The Completion Queue to get the first valid CQE from
513  *
514  * This routine will get the first valid Completion Queue Entry from @q, update
515  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
516  * the Queue (no more work to do), or the Queue is full of CQEs that have been
517  * processed, but not popped back to the HBA then this routine will return NULL.
518  **/
519 static struct lpfc_cqe *
520 lpfc_sli4_cq_get(struct lpfc_queue *q)
521 {
522 	struct lpfc_hba *phba;
523 	struct lpfc_cqe *cqe;
524 	uint32_t idx;
525 
526 	/* sanity check on queue memory */
527 	if (unlikely(!q))
528 		return NULL;
529 	phba = q->phba;
530 	cqe = q->qe[q->hba_index].cqe;
531 
532 	/* If the next CQE is not valid then we are done */
533 	if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
534 		return NULL;
535 	/* If the host has not yet processed the next entry then we are done */
536 	idx = ((q->hba_index + 1) % q->entry_count);
537 	if (idx == q->host_index)
538 		return NULL;
539 
540 	q->hba_index = idx;
541 	/* if the index wrapped around, toggle the valid bit */
542 	if (phba->sli4_hba.pc_sli4_params.cqav && !q->hba_index)
543 		q->qe_valid = (q->qe_valid) ? 0 : 1;
544 
545 	/*
546 	 * insert barrier for instruction interlock : data from the hardware
547 	 * must have the valid bit checked before it can be copied and acted
548 	 * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
549 	 * instructions allowing action on content before valid bit checked,
550 	 * add barrier here as well. May not be needed as "content" is a
551 	 * single 32-bit entity here (vs multi word structure for cq's).
552 	 */
553 	mb();
554 	return cqe;
555 }
556 
557 /**
558  * lpfc_sli4_cq_release - Indicates the host has finished processing a CQ
559  * @q: The Completion Queue that the host has completed processing for.
560  * @arm: Indicates whether the host wants to arms this CQ.
561  *
562  * This routine will mark all Completion queue entries on @q, from the last
563  * known completed entry to the last entry that was processed, as completed
564  * by clearing the valid bit for each completion queue entry. Then it will
565  * notify the HBA, by ringing the doorbell, that the CQEs have been processed.
566  * The internal host index in the @q will be updated by this routine to indicate
567  * that the host has finished processing the entries. The @arm parameter
568  * indicates that the queue should be rearmed when ringing the doorbell.
569  *
570  * This function will return the number of CQEs that were released.
571  **/
572 uint32_t
573 lpfc_sli4_cq_release(struct lpfc_queue *q, bool arm)
574 {
575 	uint32_t released = 0;
576 	struct lpfc_hba *phba;
577 	struct lpfc_cqe *temp_qe;
578 	struct lpfc_register doorbell;
579 
580 	/* sanity check on queue memory */
581 	if (unlikely(!q))
582 		return 0;
583 	phba = q->phba;
584 
585 	/* while there are valid entries */
586 	while (q->hba_index != q->host_index) {
587 		if (!phba->sli4_hba.pc_sli4_params.cqav) {
588 			temp_qe = q->qe[q->host_index].cqe;
589 			bf_set_le32(lpfc_cqe_valid, temp_qe, 0);
590 		}
591 		released++;
592 		q->host_index = ((q->host_index + 1) % q->entry_count);
593 	}
594 	if (unlikely(released == 0 && !arm))
595 		return 0;
596 
597 	/* ring doorbell for number popped */
598 	doorbell.word0 = 0;
599 	if (arm)
600 		bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
601 	bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, released);
602 	bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
603 	bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
604 			(q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
605 	bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
606 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
607 	return released;
608 }
609 
610 /**
611  * lpfc_sli4_if6_cq_release - Indicates the host has finished processing a CQ
612  * @q: The Completion Queue that the host has completed processing for.
613  * @arm: Indicates whether the host wants to arms this CQ.
614  *
615  * This routine will mark all Completion queue entries on @q, from the last
616  * known completed entry to the last entry that was processed, as completed
617  * by clearing the valid bit for each completion queue entry. Then it will
618  * notify the HBA, by ringing the doorbell, that the CQEs have been processed.
619  * The internal host index in the @q will be updated by this routine to indicate
620  * that the host has finished processing the entries. The @arm parameter
621  * indicates that the queue should be rearmed when ringing the doorbell.
622  *
623  * This function will return the number of CQEs that were released.
624  **/
625 uint32_t
626 lpfc_sli4_if6_cq_release(struct lpfc_queue *q, bool arm)
627 {
628 	uint32_t released = 0;
629 	struct lpfc_hba *phba;
630 	struct lpfc_cqe *temp_qe;
631 	struct lpfc_register doorbell;
632 
633 	/* sanity check on queue memory */
634 	if (unlikely(!q))
635 		return 0;
636 	phba = q->phba;
637 
638 	/* while there are valid entries */
639 	while (q->hba_index != q->host_index) {
640 		if (!phba->sli4_hba.pc_sli4_params.cqav) {
641 			temp_qe = q->qe[q->host_index].cqe;
642 			bf_set_le32(lpfc_cqe_valid, temp_qe, 0);
643 		}
644 		released++;
645 		q->host_index = ((q->host_index + 1) % q->entry_count);
646 	}
647 	if (unlikely(released == 0 && !arm))
648 		return 0;
649 
650 	/* ring doorbell for number popped */
651 	doorbell.word0 = 0;
652 	if (arm)
653 		bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
654 	bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, released);
655 	bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
656 	writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
657 	return released;
658 }
659 
660 /**
661  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
662  * @q: The Header Receive Queue to operate on.
663  * @wqe: The Receive Queue Entry to put on the Receive queue.
664  *
665  * This routine will copy the contents of @wqe to the next available entry on
666  * the @q. This function will then ring the Receive Queue Doorbell to signal the
667  * HBA to start processing the Receive Queue Entry. This function returns the
668  * index that the rqe was copied to if successful. If no entries are available
669  * on @q then this function will return -ENOMEM.
670  * The caller is expected to hold the hbalock when calling this routine.
671  **/
672 int
673 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
674 		 struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
675 {
676 	struct lpfc_rqe *temp_hrqe;
677 	struct lpfc_rqe *temp_drqe;
678 	struct lpfc_register doorbell;
679 	int hq_put_index;
680 	int dq_put_index;
681 
682 	/* sanity check on queue memory */
683 	if (unlikely(!hq) || unlikely(!dq))
684 		return -ENOMEM;
685 	hq_put_index = hq->host_index;
686 	dq_put_index = dq->host_index;
687 	temp_hrqe = hq->qe[hq_put_index].rqe;
688 	temp_drqe = dq->qe[dq_put_index].rqe;
689 
690 	if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
691 		return -EINVAL;
692 	if (hq_put_index != dq_put_index)
693 		return -EINVAL;
694 	/* If the host has not yet processed the next entry then we are done */
695 	if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
696 		return -EBUSY;
697 	lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
698 	lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
699 
700 	/* Update the host index to point to the next slot */
701 	hq->host_index = ((hq_put_index + 1) % hq->entry_count);
702 	dq->host_index = ((dq_put_index + 1) % dq->entry_count);
703 	hq->RQ_buf_posted++;
704 
705 	/* Ring The Header Receive Queue Doorbell */
706 	if (!(hq->host_index % hq->entry_repost)) {
707 		doorbell.word0 = 0;
708 		if (hq->db_format == LPFC_DB_RING_FORMAT) {
709 			bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
710 			       hq->entry_repost);
711 			bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
712 		} else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
713 			bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
714 			       hq->entry_repost);
715 			bf_set(lpfc_rq_db_list_fm_index, &doorbell,
716 			       hq->host_index);
717 			bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
718 		} else {
719 			return -EINVAL;
720 		}
721 		writel(doorbell.word0, hq->db_regaddr);
722 	}
723 	return hq_put_index;
724 }
725 
726 /**
727  * lpfc_sli4_rq_release - Updates internal hba index for RQ
728  * @q: The Header Receive Queue to operate on.
729  *
730  * This routine will update the HBA index of a queue to reflect consumption of
731  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
732  * consumed an entry the host calls this function to update the queue's
733  * internal pointers. This routine returns the number of entries that were
734  * consumed by the HBA.
735  **/
736 static uint32_t
737 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
738 {
739 	/* sanity check on queue memory */
740 	if (unlikely(!hq) || unlikely(!dq))
741 		return 0;
742 
743 	if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
744 		return 0;
745 	hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
746 	dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
747 	return 1;
748 }
749 
750 /**
751  * lpfc_cmd_iocb - Get next command iocb entry in the ring
752  * @phba: Pointer to HBA context object.
753  * @pring: Pointer to driver SLI ring object.
754  *
755  * This function returns pointer to next command iocb entry
756  * in the command ring. The caller must hold hbalock to prevent
757  * other threads consume the next command iocb.
758  * SLI-2/SLI-3 provide different sized iocbs.
759  **/
760 static inline IOCB_t *
761 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
762 {
763 	return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
764 			   pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
765 }
766 
767 /**
768  * lpfc_resp_iocb - Get next response iocb entry in the ring
769  * @phba: Pointer to HBA context object.
770  * @pring: Pointer to driver SLI ring object.
771  *
772  * This function returns pointer to next response iocb entry
773  * in the response ring. The caller must hold hbalock to make sure
774  * that no other thread consume the next response iocb.
775  * SLI-2/SLI-3 provide different sized iocbs.
776  **/
777 static inline IOCB_t *
778 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
779 {
780 	return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
781 			   pring->sli.sli3.rspidx * phba->iocb_rsp_size);
782 }
783 
784 /**
785  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
786  * @phba: Pointer to HBA context object.
787  *
788  * This function is called with hbalock held. This function
789  * allocates a new driver iocb object from the iocb pool. If the
790  * allocation is successful, it returns pointer to the newly
791  * allocated iocb object else it returns NULL.
792  **/
793 struct lpfc_iocbq *
794 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
795 {
796 	struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
797 	struct lpfc_iocbq * iocbq = NULL;
798 
799 	lockdep_assert_held(&phba->hbalock);
800 
801 	list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
802 	if (iocbq)
803 		phba->iocb_cnt++;
804 	if (phba->iocb_cnt > phba->iocb_max)
805 		phba->iocb_max = phba->iocb_cnt;
806 	return iocbq;
807 }
808 
809 /**
810  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
811  * @phba: Pointer to HBA context object.
812  * @xritag: XRI value.
813  *
814  * This function clears the sglq pointer from the array of acive
815  * sglq's. The xritag that is passed in is used to index into the
816  * array. Before the xritag can be used it needs to be adjusted
817  * by subtracting the xribase.
818  *
819  * Returns sglq ponter = success, NULL = Failure.
820  **/
821 struct lpfc_sglq *
822 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
823 {
824 	struct lpfc_sglq *sglq;
825 
826 	sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
827 	phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
828 	return sglq;
829 }
830 
831 /**
832  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
833  * @phba: Pointer to HBA context object.
834  * @xritag: XRI value.
835  *
836  * This function returns the sglq pointer from the array of acive
837  * sglq's. The xritag that is passed in is used to index into the
838  * array. Before the xritag can be used it needs to be adjusted
839  * by subtracting the xribase.
840  *
841  * Returns sglq ponter = success, NULL = Failure.
842  **/
843 struct lpfc_sglq *
844 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
845 {
846 	struct lpfc_sglq *sglq;
847 
848 	sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
849 	return sglq;
850 }
851 
852 /**
853  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
854  * @phba: Pointer to HBA context object.
855  * @xritag: xri used in this exchange.
856  * @rrq: The RRQ to be cleared.
857  *
858  **/
859 void
860 lpfc_clr_rrq_active(struct lpfc_hba *phba,
861 		    uint16_t xritag,
862 		    struct lpfc_node_rrq *rrq)
863 {
864 	struct lpfc_nodelist *ndlp = NULL;
865 
866 	if ((rrq->vport) && NLP_CHK_NODE_ACT(rrq->ndlp))
867 		ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
868 
869 	/* The target DID could have been swapped (cable swap)
870 	 * we should use the ndlp from the findnode if it is
871 	 * available.
872 	 */
873 	if ((!ndlp) && rrq->ndlp)
874 		ndlp = rrq->ndlp;
875 
876 	if (!ndlp)
877 		goto out;
878 
879 	if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
880 		rrq->send_rrq = 0;
881 		rrq->xritag = 0;
882 		rrq->rrq_stop_time = 0;
883 	}
884 out:
885 	mempool_free(rrq, phba->rrq_pool);
886 }
887 
888 /**
889  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
890  * @phba: Pointer to HBA context object.
891  *
892  * This function is called with hbalock held. This function
893  * Checks if stop_time (ratov from setting rrq active) has
894  * been reached, if it has and the send_rrq flag is set then
895  * it will call lpfc_send_rrq. If the send_rrq flag is not set
896  * then it will just call the routine to clear the rrq and
897  * free the rrq resource.
898  * The timer is set to the next rrq that is going to expire before
899  * leaving the routine.
900  *
901  **/
902 void
903 lpfc_handle_rrq_active(struct lpfc_hba *phba)
904 {
905 	struct lpfc_node_rrq *rrq;
906 	struct lpfc_node_rrq *nextrrq;
907 	unsigned long next_time;
908 	unsigned long iflags;
909 	LIST_HEAD(send_rrq);
910 
911 	spin_lock_irqsave(&phba->hbalock, iflags);
912 	phba->hba_flag &= ~HBA_RRQ_ACTIVE;
913 	next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
914 	list_for_each_entry_safe(rrq, nextrrq,
915 				 &phba->active_rrq_list, list) {
916 		if (time_after(jiffies, rrq->rrq_stop_time))
917 			list_move(&rrq->list, &send_rrq);
918 		else if (time_before(rrq->rrq_stop_time, next_time))
919 			next_time = rrq->rrq_stop_time;
920 	}
921 	spin_unlock_irqrestore(&phba->hbalock, iflags);
922 	if ((!list_empty(&phba->active_rrq_list)) &&
923 	    (!(phba->pport->load_flag & FC_UNLOADING)))
924 		mod_timer(&phba->rrq_tmr, next_time);
925 	list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
926 		list_del(&rrq->list);
927 		if (!rrq->send_rrq)
928 			/* this call will free the rrq */
929 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
930 		else if (lpfc_send_rrq(phba, rrq)) {
931 			/* if we send the rrq then the completion handler
932 			*  will clear the bit in the xribitmap.
933 			*/
934 			lpfc_clr_rrq_active(phba, rrq->xritag,
935 					    rrq);
936 		}
937 	}
938 }
939 
940 /**
941  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
942  * @vport: Pointer to vport context object.
943  * @xri: The xri used in the exchange.
944  * @did: The targets DID for this exchange.
945  *
946  * returns NULL = rrq not found in the phba->active_rrq_list.
947  *         rrq = rrq for this xri and target.
948  **/
949 struct lpfc_node_rrq *
950 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
951 {
952 	struct lpfc_hba *phba = vport->phba;
953 	struct lpfc_node_rrq *rrq;
954 	struct lpfc_node_rrq *nextrrq;
955 	unsigned long iflags;
956 
957 	if (phba->sli_rev != LPFC_SLI_REV4)
958 		return NULL;
959 	spin_lock_irqsave(&phba->hbalock, iflags);
960 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
961 		if (rrq->vport == vport && rrq->xritag == xri &&
962 				rrq->nlp_DID == did){
963 			list_del(&rrq->list);
964 			spin_unlock_irqrestore(&phba->hbalock, iflags);
965 			return rrq;
966 		}
967 	}
968 	spin_unlock_irqrestore(&phba->hbalock, iflags);
969 	return NULL;
970 }
971 
972 /**
973  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
974  * @vport: Pointer to vport context object.
975  * @ndlp: Pointer to the lpfc_node_list structure.
976  * If ndlp is NULL Remove all active RRQs for this vport from the
977  * phba->active_rrq_list and clear the rrq.
978  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
979  **/
980 void
981 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
982 
983 {
984 	struct lpfc_hba *phba = vport->phba;
985 	struct lpfc_node_rrq *rrq;
986 	struct lpfc_node_rrq *nextrrq;
987 	unsigned long iflags;
988 	LIST_HEAD(rrq_list);
989 
990 	if (phba->sli_rev != LPFC_SLI_REV4)
991 		return;
992 	if (!ndlp) {
993 		lpfc_sli4_vport_delete_els_xri_aborted(vport);
994 		lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
995 	}
996 	spin_lock_irqsave(&phba->hbalock, iflags);
997 	list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list)
998 		if ((rrq->vport == vport) && (!ndlp  || rrq->ndlp == ndlp))
999 			list_move(&rrq->list, &rrq_list);
1000 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1001 
1002 	list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1003 		list_del(&rrq->list);
1004 		lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1005 	}
1006 }
1007 
1008 /**
1009  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1010  * @phba: Pointer to HBA context object.
1011  * @ndlp: Targets nodelist pointer for this exchange.
1012  * @xritag the xri in the bitmap to test.
1013  *
1014  * This function is called with hbalock held. This function
1015  * returns 0 = rrq not active for this xri
1016  *         1 = rrq is valid for this xri.
1017  **/
1018 int
1019 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1020 			uint16_t  xritag)
1021 {
1022 	lockdep_assert_held(&phba->hbalock);
1023 	if (!ndlp)
1024 		return 0;
1025 	if (!ndlp->active_rrqs_xri_bitmap)
1026 		return 0;
1027 	if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1028 			return 1;
1029 	else
1030 		return 0;
1031 }
1032 
1033 /**
1034  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1035  * @phba: Pointer to HBA context object.
1036  * @ndlp: nodelist pointer for this target.
1037  * @xritag: xri used in this exchange.
1038  * @rxid: Remote Exchange ID.
1039  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1040  *
1041  * This function takes the hbalock.
1042  * The active bit is always set in the active rrq xri_bitmap even
1043  * if there is no slot avaiable for the other rrq information.
1044  *
1045  * returns 0 rrq actived for this xri
1046  *         < 0 No memory or invalid ndlp.
1047  **/
1048 int
1049 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1050 		    uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1051 {
1052 	unsigned long iflags;
1053 	struct lpfc_node_rrq *rrq;
1054 	int empty;
1055 
1056 	if (!ndlp)
1057 		return -EINVAL;
1058 
1059 	if (!phba->cfg_enable_rrq)
1060 		return -EINVAL;
1061 
1062 	spin_lock_irqsave(&phba->hbalock, iflags);
1063 	if (phba->pport->load_flag & FC_UNLOADING) {
1064 		phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1065 		goto out;
1066 	}
1067 
1068 	/*
1069 	 * set the active bit even if there is no mem available.
1070 	 */
1071 	if (NLP_CHK_FREE_REQ(ndlp))
1072 		goto out;
1073 
1074 	if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
1075 		goto out;
1076 
1077 	if (!ndlp->active_rrqs_xri_bitmap)
1078 		goto out;
1079 
1080 	if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1081 		goto out;
1082 
1083 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1084 	rrq = mempool_alloc(phba->rrq_pool, GFP_KERNEL);
1085 	if (!rrq) {
1086 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1087 				"3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1088 				" DID:0x%x Send:%d\n",
1089 				xritag, rxid, ndlp->nlp_DID, send_rrq);
1090 		return -EINVAL;
1091 	}
1092 	if (phba->cfg_enable_rrq == 1)
1093 		rrq->send_rrq = send_rrq;
1094 	else
1095 		rrq->send_rrq = 0;
1096 	rrq->xritag = xritag;
1097 	rrq->rrq_stop_time = jiffies +
1098 				msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1099 	rrq->ndlp = ndlp;
1100 	rrq->nlp_DID = ndlp->nlp_DID;
1101 	rrq->vport = ndlp->vport;
1102 	rrq->rxid = rxid;
1103 	spin_lock_irqsave(&phba->hbalock, iflags);
1104 	empty = list_empty(&phba->active_rrq_list);
1105 	list_add_tail(&rrq->list, &phba->active_rrq_list);
1106 	phba->hba_flag |= HBA_RRQ_ACTIVE;
1107 	if (empty)
1108 		lpfc_worker_wake_up(phba);
1109 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1110 	return 0;
1111 out:
1112 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1113 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1114 			"2921 Can't set rrq active xri:0x%x rxid:0x%x"
1115 			" DID:0x%x Send:%d\n",
1116 			xritag, rxid, ndlp->nlp_DID, send_rrq);
1117 	return -EINVAL;
1118 }
1119 
1120 /**
1121  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
1122  * @phba: Pointer to HBA context object.
1123  * @piocb: Pointer to the iocbq.
1124  *
1125  * This function is called with the ring lock held. This function
1126  * gets a new driver sglq object from the sglq list. If the
1127  * list is not empty then it is successful, it returns pointer to the newly
1128  * allocated sglq object else it returns NULL.
1129  **/
1130 static struct lpfc_sglq *
1131 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1132 {
1133 	struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
1134 	struct lpfc_sglq *sglq = NULL;
1135 	struct lpfc_sglq *start_sglq = NULL;
1136 	struct lpfc_scsi_buf *lpfc_cmd;
1137 	struct lpfc_nodelist *ndlp;
1138 	int found = 0;
1139 
1140 	lockdep_assert_held(&phba->hbalock);
1141 
1142 	if (piocbq->iocb_flag &  LPFC_IO_FCP) {
1143 		lpfc_cmd = (struct lpfc_scsi_buf *) piocbq->context1;
1144 		ndlp = lpfc_cmd->rdata->pnode;
1145 	} else  if ((piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) &&
1146 			!(piocbq->iocb_flag & LPFC_IO_LIBDFC)) {
1147 		ndlp = piocbq->context_un.ndlp;
1148 	} else  if (piocbq->iocb_flag & LPFC_IO_LIBDFC) {
1149 		if (piocbq->iocb_flag & LPFC_IO_LOOPBACK)
1150 			ndlp = NULL;
1151 		else
1152 			ndlp = piocbq->context_un.ndlp;
1153 	} else {
1154 		ndlp = piocbq->context1;
1155 	}
1156 
1157 	spin_lock(&phba->sli4_hba.sgl_list_lock);
1158 	list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
1159 	start_sglq = sglq;
1160 	while (!found) {
1161 		if (!sglq)
1162 			break;
1163 		if (ndlp && ndlp->active_rrqs_xri_bitmap &&
1164 		    test_bit(sglq->sli4_lxritag,
1165 		    ndlp->active_rrqs_xri_bitmap)) {
1166 			/* This xri has an rrq outstanding for this DID.
1167 			 * put it back in the list and get another xri.
1168 			 */
1169 			list_add_tail(&sglq->list, lpfc_els_sgl_list);
1170 			sglq = NULL;
1171 			list_remove_head(lpfc_els_sgl_list, sglq,
1172 						struct lpfc_sglq, list);
1173 			if (sglq == start_sglq) {
1174 				list_add_tail(&sglq->list, lpfc_els_sgl_list);
1175 				sglq = NULL;
1176 				break;
1177 			} else
1178 				continue;
1179 		}
1180 		sglq->ndlp = ndlp;
1181 		found = 1;
1182 		phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1183 		sglq->state = SGL_ALLOCATED;
1184 	}
1185 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
1186 	return sglq;
1187 }
1188 
1189 /**
1190  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
1191  * @phba: Pointer to HBA context object.
1192  * @piocb: Pointer to the iocbq.
1193  *
1194  * This function is called with the sgl_list lock held. This function
1195  * gets a new driver sglq object from the sglq list. If the
1196  * list is not empty then it is successful, it returns pointer to the newly
1197  * allocated sglq object else it returns NULL.
1198  **/
1199 struct lpfc_sglq *
1200 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1201 {
1202 	struct list_head *lpfc_nvmet_sgl_list;
1203 	struct lpfc_sglq *sglq = NULL;
1204 
1205 	lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
1206 
1207 	lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1208 
1209 	list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1210 	if (!sglq)
1211 		return NULL;
1212 	phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1213 	sglq->state = SGL_ALLOCATED;
1214 	return sglq;
1215 }
1216 
1217 /**
1218  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1219  * @phba: Pointer to HBA context object.
1220  *
1221  * This function is called with no lock held. This function
1222  * allocates a new driver iocb object from the iocb pool. If the
1223  * allocation is successful, it returns pointer to the newly
1224  * allocated iocb object else it returns NULL.
1225  **/
1226 struct lpfc_iocbq *
1227 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1228 {
1229 	struct lpfc_iocbq * iocbq = NULL;
1230 	unsigned long iflags;
1231 
1232 	spin_lock_irqsave(&phba->hbalock, iflags);
1233 	iocbq = __lpfc_sli_get_iocbq(phba);
1234 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1235 	return iocbq;
1236 }
1237 
1238 /**
1239  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1240  * @phba: Pointer to HBA context object.
1241  * @iocbq: Pointer to driver iocb object.
1242  *
1243  * This function is called with hbalock held to release driver
1244  * iocb object to the iocb pool. The iotag in the iocb object
1245  * does not change for each use of the iocb object. This function
1246  * clears all other fields of the iocb object when it is freed.
1247  * The sqlq structure that holds the xritag and phys and virtual
1248  * mappings for the scatter gather list is retrieved from the
1249  * active array of sglq. The get of the sglq pointer also clears
1250  * the entry in the array. If the status of the IO indiactes that
1251  * this IO was aborted then the sglq entry it put on the
1252  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1253  * IO has good status or fails for any other reason then the sglq
1254  * entry is added to the free list (lpfc_els_sgl_list).
1255  **/
1256 static void
1257 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1258 {
1259 	struct lpfc_sglq *sglq;
1260 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1261 	unsigned long iflag = 0;
1262 	struct lpfc_sli_ring *pring;
1263 
1264 	lockdep_assert_held(&phba->hbalock);
1265 
1266 	if (iocbq->sli4_xritag == NO_XRI)
1267 		sglq = NULL;
1268 	else
1269 		sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1270 
1271 
1272 	if (sglq)  {
1273 		if (iocbq->iocb_flag & LPFC_IO_NVMET) {
1274 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1275 					  iflag);
1276 			sglq->state = SGL_FREED;
1277 			sglq->ndlp = NULL;
1278 			list_add_tail(&sglq->list,
1279 				      &phba->sli4_hba.lpfc_nvmet_sgl_list);
1280 			spin_unlock_irqrestore(
1281 				&phba->sli4_hba.sgl_list_lock, iflag);
1282 			goto out;
1283 		}
1284 
1285 		pring = phba->sli4_hba.els_wq->pring;
1286 		if ((iocbq->iocb_flag & LPFC_EXCHANGE_BUSY) &&
1287 			(sglq->state != SGL_XRI_ABORTED)) {
1288 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1289 					  iflag);
1290 			list_add(&sglq->list,
1291 				 &phba->sli4_hba.lpfc_abts_els_sgl_list);
1292 			spin_unlock_irqrestore(
1293 				&phba->sli4_hba.sgl_list_lock, iflag);
1294 		} else {
1295 			spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1296 					  iflag);
1297 			sglq->state = SGL_FREED;
1298 			sglq->ndlp = NULL;
1299 			list_add_tail(&sglq->list,
1300 				      &phba->sli4_hba.lpfc_els_sgl_list);
1301 			spin_unlock_irqrestore(
1302 				&phba->sli4_hba.sgl_list_lock, iflag);
1303 
1304 			/* Check if TXQ queue needs to be serviced */
1305 			if (!list_empty(&pring->txq))
1306 				lpfc_worker_wake_up(phba);
1307 		}
1308 	}
1309 
1310 out:
1311 	/*
1312 	 * Clean all volatile data fields, preserve iotag and node struct.
1313 	 */
1314 	memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1315 	iocbq->sli4_lxritag = NO_XRI;
1316 	iocbq->sli4_xritag = NO_XRI;
1317 	iocbq->iocb_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET |
1318 			      LPFC_IO_NVME_LS);
1319 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1320 }
1321 
1322 
1323 /**
1324  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1325  * @phba: Pointer to HBA context object.
1326  * @iocbq: Pointer to driver iocb object.
1327  *
1328  * This function is called with hbalock held to release driver
1329  * iocb object to the iocb pool. The iotag in the iocb object
1330  * does not change for each use of the iocb object. This function
1331  * clears all other fields of the iocb object when it is freed.
1332  **/
1333 static void
1334 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1335 {
1336 	size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1337 
1338 	lockdep_assert_held(&phba->hbalock);
1339 
1340 	/*
1341 	 * Clean all volatile data fields, preserve iotag and node struct.
1342 	 */
1343 	memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1344 	iocbq->sli4_xritag = NO_XRI;
1345 	list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1346 }
1347 
1348 /**
1349  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1350  * @phba: Pointer to HBA context object.
1351  * @iocbq: Pointer to driver iocb object.
1352  *
1353  * This function is called with hbalock held to release driver
1354  * iocb object to the iocb pool. The iotag in the iocb object
1355  * does not change for each use of the iocb object. This function
1356  * clears all other fields of the iocb object when it is freed.
1357  **/
1358 static void
1359 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1360 {
1361 	lockdep_assert_held(&phba->hbalock);
1362 
1363 	phba->__lpfc_sli_release_iocbq(phba, iocbq);
1364 	phba->iocb_cnt--;
1365 }
1366 
1367 /**
1368  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1369  * @phba: Pointer to HBA context object.
1370  * @iocbq: Pointer to driver iocb object.
1371  *
1372  * This function is called with no lock held to release the iocb to
1373  * iocb pool.
1374  **/
1375 void
1376 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1377 {
1378 	unsigned long iflags;
1379 
1380 	/*
1381 	 * Clean all volatile data fields, preserve iotag and node struct.
1382 	 */
1383 	spin_lock_irqsave(&phba->hbalock, iflags);
1384 	__lpfc_sli_release_iocbq(phba, iocbq);
1385 	spin_unlock_irqrestore(&phba->hbalock, iflags);
1386 }
1387 
1388 /**
1389  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1390  * @phba: Pointer to HBA context object.
1391  * @iocblist: List of IOCBs.
1392  * @ulpstatus: ULP status in IOCB command field.
1393  * @ulpWord4: ULP word-4 in IOCB command field.
1394  *
1395  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1396  * on the list by invoking the complete callback function associated with the
1397  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1398  * fields.
1399  **/
1400 void
1401 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1402 		      uint32_t ulpstatus, uint32_t ulpWord4)
1403 {
1404 	struct lpfc_iocbq *piocb;
1405 
1406 	while (!list_empty(iocblist)) {
1407 		list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1408 		if (!piocb->iocb_cmpl)
1409 			lpfc_sli_release_iocbq(phba, piocb);
1410 		else {
1411 			piocb->iocb.ulpStatus = ulpstatus;
1412 			piocb->iocb.un.ulpWord[4] = ulpWord4;
1413 			(piocb->iocb_cmpl) (phba, piocb, piocb);
1414 		}
1415 	}
1416 	return;
1417 }
1418 
1419 /**
1420  * lpfc_sli_iocb_cmd_type - Get the iocb type
1421  * @iocb_cmnd: iocb command code.
1422  *
1423  * This function is called by ring event handler function to get the iocb type.
1424  * This function translates the iocb command to an iocb command type used to
1425  * decide the final disposition of each completed IOCB.
1426  * The function returns
1427  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1428  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1429  * LPFC_ABORT_IOCB   if it is an abort iocb
1430  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1431  *
1432  * The caller is not required to hold any lock.
1433  **/
1434 static lpfc_iocb_type
1435 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1436 {
1437 	lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1438 
1439 	if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1440 		return 0;
1441 
1442 	switch (iocb_cmnd) {
1443 	case CMD_XMIT_SEQUENCE_CR:
1444 	case CMD_XMIT_SEQUENCE_CX:
1445 	case CMD_XMIT_BCAST_CN:
1446 	case CMD_XMIT_BCAST_CX:
1447 	case CMD_ELS_REQUEST_CR:
1448 	case CMD_ELS_REQUEST_CX:
1449 	case CMD_CREATE_XRI_CR:
1450 	case CMD_CREATE_XRI_CX:
1451 	case CMD_GET_RPI_CN:
1452 	case CMD_XMIT_ELS_RSP_CX:
1453 	case CMD_GET_RPI_CR:
1454 	case CMD_FCP_IWRITE_CR:
1455 	case CMD_FCP_IWRITE_CX:
1456 	case CMD_FCP_IREAD_CR:
1457 	case CMD_FCP_IREAD_CX:
1458 	case CMD_FCP_ICMND_CR:
1459 	case CMD_FCP_ICMND_CX:
1460 	case CMD_FCP_TSEND_CX:
1461 	case CMD_FCP_TRSP_CX:
1462 	case CMD_FCP_TRECEIVE_CX:
1463 	case CMD_FCP_AUTO_TRSP_CX:
1464 	case CMD_ADAPTER_MSG:
1465 	case CMD_ADAPTER_DUMP:
1466 	case CMD_XMIT_SEQUENCE64_CR:
1467 	case CMD_XMIT_SEQUENCE64_CX:
1468 	case CMD_XMIT_BCAST64_CN:
1469 	case CMD_XMIT_BCAST64_CX:
1470 	case CMD_ELS_REQUEST64_CR:
1471 	case CMD_ELS_REQUEST64_CX:
1472 	case CMD_FCP_IWRITE64_CR:
1473 	case CMD_FCP_IWRITE64_CX:
1474 	case CMD_FCP_IREAD64_CR:
1475 	case CMD_FCP_IREAD64_CX:
1476 	case CMD_FCP_ICMND64_CR:
1477 	case CMD_FCP_ICMND64_CX:
1478 	case CMD_FCP_TSEND64_CX:
1479 	case CMD_FCP_TRSP64_CX:
1480 	case CMD_FCP_TRECEIVE64_CX:
1481 	case CMD_GEN_REQUEST64_CR:
1482 	case CMD_GEN_REQUEST64_CX:
1483 	case CMD_XMIT_ELS_RSP64_CX:
1484 	case DSSCMD_IWRITE64_CR:
1485 	case DSSCMD_IWRITE64_CX:
1486 	case DSSCMD_IREAD64_CR:
1487 	case DSSCMD_IREAD64_CX:
1488 		type = LPFC_SOL_IOCB;
1489 		break;
1490 	case CMD_ABORT_XRI_CN:
1491 	case CMD_ABORT_XRI_CX:
1492 	case CMD_CLOSE_XRI_CN:
1493 	case CMD_CLOSE_XRI_CX:
1494 	case CMD_XRI_ABORTED_CX:
1495 	case CMD_ABORT_MXRI64_CN:
1496 	case CMD_XMIT_BLS_RSP64_CX:
1497 		type = LPFC_ABORT_IOCB;
1498 		break;
1499 	case CMD_RCV_SEQUENCE_CX:
1500 	case CMD_RCV_ELS_REQ_CX:
1501 	case CMD_RCV_SEQUENCE64_CX:
1502 	case CMD_RCV_ELS_REQ64_CX:
1503 	case CMD_ASYNC_STATUS:
1504 	case CMD_IOCB_RCV_SEQ64_CX:
1505 	case CMD_IOCB_RCV_ELS64_CX:
1506 	case CMD_IOCB_RCV_CONT64_CX:
1507 	case CMD_IOCB_RET_XRI64_CX:
1508 		type = LPFC_UNSOL_IOCB;
1509 		break;
1510 	case CMD_IOCB_XMIT_MSEQ64_CR:
1511 	case CMD_IOCB_XMIT_MSEQ64_CX:
1512 	case CMD_IOCB_RCV_SEQ_LIST64_CX:
1513 	case CMD_IOCB_RCV_ELS_LIST64_CX:
1514 	case CMD_IOCB_CLOSE_EXTENDED_CN:
1515 	case CMD_IOCB_ABORT_EXTENDED_CN:
1516 	case CMD_IOCB_RET_HBQE64_CN:
1517 	case CMD_IOCB_FCP_IBIDIR64_CR:
1518 	case CMD_IOCB_FCP_IBIDIR64_CX:
1519 	case CMD_IOCB_FCP_ITASKMGT64_CX:
1520 	case CMD_IOCB_LOGENTRY_CN:
1521 	case CMD_IOCB_LOGENTRY_ASYNC_CN:
1522 		printk("%s - Unhandled SLI-3 Command x%x\n",
1523 				__func__, iocb_cmnd);
1524 		type = LPFC_UNKNOWN_IOCB;
1525 		break;
1526 	default:
1527 		type = LPFC_UNKNOWN_IOCB;
1528 		break;
1529 	}
1530 
1531 	return type;
1532 }
1533 
1534 /**
1535  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1536  * @phba: Pointer to HBA context object.
1537  *
1538  * This function is called from SLI initialization code
1539  * to configure every ring of the HBA's SLI interface. The
1540  * caller is not required to hold any lock. This function issues
1541  * a config_ring mailbox command for each ring.
1542  * This function returns zero if successful else returns a negative
1543  * error code.
1544  **/
1545 static int
1546 lpfc_sli_ring_map(struct lpfc_hba *phba)
1547 {
1548 	struct lpfc_sli *psli = &phba->sli;
1549 	LPFC_MBOXQ_t *pmb;
1550 	MAILBOX_t *pmbox;
1551 	int i, rc, ret = 0;
1552 
1553 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1554 	if (!pmb)
1555 		return -ENOMEM;
1556 	pmbox = &pmb->u.mb;
1557 	phba->link_state = LPFC_INIT_MBX_CMDS;
1558 	for (i = 0; i < psli->num_rings; i++) {
1559 		lpfc_config_ring(phba, i, pmb);
1560 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1561 		if (rc != MBX_SUCCESS) {
1562 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1563 					"0446 Adapter failed to init (%d), "
1564 					"mbxCmd x%x CFG_RING, mbxStatus x%x, "
1565 					"ring %d\n",
1566 					rc, pmbox->mbxCommand,
1567 					pmbox->mbxStatus, i);
1568 			phba->link_state = LPFC_HBA_ERROR;
1569 			ret = -ENXIO;
1570 			break;
1571 		}
1572 	}
1573 	mempool_free(pmb, phba->mbox_mem_pool);
1574 	return ret;
1575 }
1576 
1577 /**
1578  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1579  * @phba: Pointer to HBA context object.
1580  * @pring: Pointer to driver SLI ring object.
1581  * @piocb: Pointer to the driver iocb object.
1582  *
1583  * This function is called with hbalock held. The function adds the
1584  * new iocb to txcmplq of the given ring. This function always returns
1585  * 0. If this function is called for ELS ring, this function checks if
1586  * there is a vport associated with the ELS command. This function also
1587  * starts els_tmofunc timer if this is an ELS command.
1588  **/
1589 static int
1590 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1591 			struct lpfc_iocbq *piocb)
1592 {
1593 	lockdep_assert_held(&phba->hbalock);
1594 
1595 	BUG_ON(!piocb);
1596 
1597 	list_add_tail(&piocb->list, &pring->txcmplq);
1598 	piocb->iocb_flag |= LPFC_IO_ON_TXCMPLQ;
1599 
1600 	if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1601 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
1602 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
1603 		BUG_ON(!piocb->vport);
1604 		if (!(piocb->vport->load_flag & FC_UNLOADING))
1605 			mod_timer(&piocb->vport->els_tmofunc,
1606 				  jiffies +
1607 				  msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1608 	}
1609 
1610 	return 0;
1611 }
1612 
1613 /**
1614  * lpfc_sli_ringtx_get - Get first element of the txq
1615  * @phba: Pointer to HBA context object.
1616  * @pring: Pointer to driver SLI ring object.
1617  *
1618  * This function is called with hbalock held to get next
1619  * iocb in txq of the given ring. If there is any iocb in
1620  * the txq, the function returns first iocb in the list after
1621  * removing the iocb from the list, else it returns NULL.
1622  **/
1623 struct lpfc_iocbq *
1624 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1625 {
1626 	struct lpfc_iocbq *cmd_iocb;
1627 
1628 	lockdep_assert_held(&phba->hbalock);
1629 
1630 	list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1631 	return cmd_iocb;
1632 }
1633 
1634 /**
1635  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
1636  * @phba: Pointer to HBA context object.
1637  * @pring: Pointer to driver SLI ring object.
1638  *
1639  * This function is called with hbalock held and the caller must post the
1640  * iocb without releasing the lock. If the caller releases the lock,
1641  * iocb slot returned by the function is not guaranteed to be available.
1642  * The function returns pointer to the next available iocb slot if there
1643  * is available slot in the ring, else it returns NULL.
1644  * If the get index of the ring is ahead of the put index, the function
1645  * will post an error attention event to the worker thread to take the
1646  * HBA to offline state.
1647  **/
1648 static IOCB_t *
1649 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1650 {
1651 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
1652 	uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
1653 
1654 	lockdep_assert_held(&phba->hbalock);
1655 
1656 	if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
1657 	   (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
1658 		pring->sli.sli3.next_cmdidx = 0;
1659 
1660 	if (unlikely(pring->sli.sli3.local_getidx ==
1661 		pring->sli.sli3.next_cmdidx)) {
1662 
1663 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
1664 
1665 		if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
1666 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1667 					"0315 Ring %d issue: portCmdGet %d "
1668 					"is bigger than cmd ring %d\n",
1669 					pring->ringno,
1670 					pring->sli.sli3.local_getidx,
1671 					max_cmd_idx);
1672 
1673 			phba->link_state = LPFC_HBA_ERROR;
1674 			/*
1675 			 * All error attention handlers are posted to
1676 			 * worker thread
1677 			 */
1678 			phba->work_ha |= HA_ERATT;
1679 			phba->work_hs = HS_FFER3;
1680 
1681 			lpfc_worker_wake_up(phba);
1682 
1683 			return NULL;
1684 		}
1685 
1686 		if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
1687 			return NULL;
1688 	}
1689 
1690 	return lpfc_cmd_iocb(phba, pring);
1691 }
1692 
1693 /**
1694  * lpfc_sli_next_iotag - Get an iotag for the iocb
1695  * @phba: Pointer to HBA context object.
1696  * @iocbq: Pointer to driver iocb object.
1697  *
1698  * This function gets an iotag for the iocb. If there is no unused iotag and
1699  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
1700  * array and assigns a new iotag.
1701  * The function returns the allocated iotag if successful, else returns zero.
1702  * Zero is not a valid iotag.
1703  * The caller is not required to hold any lock.
1704  **/
1705 uint16_t
1706 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1707 {
1708 	struct lpfc_iocbq **new_arr;
1709 	struct lpfc_iocbq **old_arr;
1710 	size_t new_len;
1711 	struct lpfc_sli *psli = &phba->sli;
1712 	uint16_t iotag;
1713 
1714 	spin_lock_irq(&phba->hbalock);
1715 	iotag = psli->last_iotag;
1716 	if(++iotag < psli->iocbq_lookup_len) {
1717 		psli->last_iotag = iotag;
1718 		psli->iocbq_lookup[iotag] = iocbq;
1719 		spin_unlock_irq(&phba->hbalock);
1720 		iocbq->iotag = iotag;
1721 		return iotag;
1722 	} else if (psli->iocbq_lookup_len < (0xffff
1723 					   - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
1724 		new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
1725 		spin_unlock_irq(&phba->hbalock);
1726 		new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
1727 				  GFP_KERNEL);
1728 		if (new_arr) {
1729 			spin_lock_irq(&phba->hbalock);
1730 			old_arr = psli->iocbq_lookup;
1731 			if (new_len <= psli->iocbq_lookup_len) {
1732 				/* highly unprobable case */
1733 				kfree(new_arr);
1734 				iotag = psli->last_iotag;
1735 				if(++iotag < psli->iocbq_lookup_len) {
1736 					psli->last_iotag = iotag;
1737 					psli->iocbq_lookup[iotag] = iocbq;
1738 					spin_unlock_irq(&phba->hbalock);
1739 					iocbq->iotag = iotag;
1740 					return iotag;
1741 				}
1742 				spin_unlock_irq(&phba->hbalock);
1743 				return 0;
1744 			}
1745 			if (psli->iocbq_lookup)
1746 				memcpy(new_arr, old_arr,
1747 				       ((psli->last_iotag  + 1) *
1748 					sizeof (struct lpfc_iocbq *)));
1749 			psli->iocbq_lookup = new_arr;
1750 			psli->iocbq_lookup_len = new_len;
1751 			psli->last_iotag = iotag;
1752 			psli->iocbq_lookup[iotag] = iocbq;
1753 			spin_unlock_irq(&phba->hbalock);
1754 			iocbq->iotag = iotag;
1755 			kfree(old_arr);
1756 			return iotag;
1757 		}
1758 	} else
1759 		spin_unlock_irq(&phba->hbalock);
1760 
1761 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
1762 			"0318 Failed to allocate IOTAG.last IOTAG is %d\n",
1763 			psli->last_iotag);
1764 
1765 	return 0;
1766 }
1767 
1768 /**
1769  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
1770  * @phba: Pointer to HBA context object.
1771  * @pring: Pointer to driver SLI ring object.
1772  * @iocb: Pointer to iocb slot in the ring.
1773  * @nextiocb: Pointer to driver iocb object which need to be
1774  *            posted to firmware.
1775  *
1776  * This function is called with hbalock held to post a new iocb to
1777  * the firmware. This function copies the new iocb to ring iocb slot and
1778  * updates the ring pointers. It adds the new iocb to txcmplq if there is
1779  * a completion call back for this iocb else the function will free the
1780  * iocb object.
1781  **/
1782 static void
1783 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1784 		IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
1785 {
1786 	lockdep_assert_held(&phba->hbalock);
1787 	/*
1788 	 * Set up an iotag
1789 	 */
1790 	nextiocb->iocb.ulpIoTag = (nextiocb->iocb_cmpl) ? nextiocb->iotag : 0;
1791 
1792 
1793 	if (pring->ringno == LPFC_ELS_RING) {
1794 		lpfc_debugfs_slow_ring_trc(phba,
1795 			"IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
1796 			*(((uint32_t *) &nextiocb->iocb) + 4),
1797 			*(((uint32_t *) &nextiocb->iocb) + 6),
1798 			*(((uint32_t *) &nextiocb->iocb) + 7));
1799 	}
1800 
1801 	/*
1802 	 * Issue iocb command to adapter
1803 	 */
1804 	lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
1805 	wmb();
1806 	pring->stats.iocb_cmd++;
1807 
1808 	/*
1809 	 * If there is no completion routine to call, we can release the
1810 	 * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
1811 	 * that have no rsp ring completion, iocb_cmpl MUST be NULL.
1812 	 */
1813 	if (nextiocb->iocb_cmpl)
1814 		lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
1815 	else
1816 		__lpfc_sli_release_iocbq(phba, nextiocb);
1817 
1818 	/*
1819 	 * Let the HBA know what IOCB slot will be the next one the
1820 	 * driver will put a command into.
1821 	 */
1822 	pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
1823 	writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
1824 }
1825 
1826 /**
1827  * lpfc_sli_update_full_ring - Update the chip attention register
1828  * @phba: Pointer to HBA context object.
1829  * @pring: Pointer to driver SLI ring object.
1830  *
1831  * The caller is not required to hold any lock for calling this function.
1832  * This function updates the chip attention bits for the ring to inform firmware
1833  * that there are pending work to be done for this ring and requests an
1834  * interrupt when there is space available in the ring. This function is
1835  * called when the driver is unable to post more iocbs to the ring due
1836  * to unavailability of space in the ring.
1837  **/
1838 static void
1839 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1840 {
1841 	int ringno = pring->ringno;
1842 
1843 	pring->flag |= LPFC_CALL_RING_AVAILABLE;
1844 
1845 	wmb();
1846 
1847 	/*
1848 	 * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
1849 	 * The HBA will tell us when an IOCB entry is available.
1850 	 */
1851 	writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
1852 	readl(phba->CAregaddr); /* flush */
1853 
1854 	pring->stats.iocb_cmd_full++;
1855 }
1856 
1857 /**
1858  * lpfc_sli_update_ring - Update chip attention register
1859  * @phba: Pointer to HBA context object.
1860  * @pring: Pointer to driver SLI ring object.
1861  *
1862  * This function updates the chip attention register bit for the
1863  * given ring to inform HBA that there is more work to be done
1864  * in this ring. The caller is not required to hold any lock.
1865  **/
1866 static void
1867 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1868 {
1869 	int ringno = pring->ringno;
1870 
1871 	/*
1872 	 * Tell the HBA that there is work to do in this ring.
1873 	 */
1874 	if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
1875 		wmb();
1876 		writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
1877 		readl(phba->CAregaddr); /* flush */
1878 	}
1879 }
1880 
1881 /**
1882  * lpfc_sli_resume_iocb - Process iocbs in the txq
1883  * @phba: Pointer to HBA context object.
1884  * @pring: Pointer to driver SLI ring object.
1885  *
1886  * This function is called with hbalock held to post pending iocbs
1887  * in the txq to the firmware. This function is called when driver
1888  * detects space available in the ring.
1889  **/
1890 static void
1891 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1892 {
1893 	IOCB_t *iocb;
1894 	struct lpfc_iocbq *nextiocb;
1895 
1896 	lockdep_assert_held(&phba->hbalock);
1897 
1898 	/*
1899 	 * Check to see if:
1900 	 *  (a) there is anything on the txq to send
1901 	 *  (b) link is up
1902 	 *  (c) link attention events can be processed (fcp ring only)
1903 	 *  (d) IOCB processing is not blocked by the outstanding mbox command.
1904 	 */
1905 
1906 	if (lpfc_is_link_up(phba) &&
1907 	    (!list_empty(&pring->txq)) &&
1908 	    (pring->ringno != LPFC_FCP_RING ||
1909 	     phba->sli.sli_flag & LPFC_PROCESS_LA)) {
1910 
1911 		while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
1912 		       (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
1913 			lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
1914 
1915 		if (iocb)
1916 			lpfc_sli_update_ring(phba, pring);
1917 		else
1918 			lpfc_sli_update_full_ring(phba, pring);
1919 	}
1920 
1921 	return;
1922 }
1923 
1924 /**
1925  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
1926  * @phba: Pointer to HBA context object.
1927  * @hbqno: HBQ number.
1928  *
1929  * This function is called with hbalock held to get the next
1930  * available slot for the given HBQ. If there is free slot
1931  * available for the HBQ it will return pointer to the next available
1932  * HBQ entry else it will return NULL.
1933  **/
1934 static struct lpfc_hbq_entry *
1935 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
1936 {
1937 	struct hbq_s *hbqp = &phba->hbqs[hbqno];
1938 
1939 	lockdep_assert_held(&phba->hbalock);
1940 
1941 	if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
1942 	    ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
1943 		hbqp->next_hbqPutIdx = 0;
1944 
1945 	if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
1946 		uint32_t raw_index = phba->hbq_get[hbqno];
1947 		uint32_t getidx = le32_to_cpu(raw_index);
1948 
1949 		hbqp->local_hbqGetIdx = getidx;
1950 
1951 		if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
1952 			lpfc_printf_log(phba, KERN_ERR,
1953 					LOG_SLI | LOG_VPORT,
1954 					"1802 HBQ %d: local_hbqGetIdx "
1955 					"%u is > than hbqp->entry_count %u\n",
1956 					hbqno, hbqp->local_hbqGetIdx,
1957 					hbqp->entry_count);
1958 
1959 			phba->link_state = LPFC_HBA_ERROR;
1960 			return NULL;
1961 		}
1962 
1963 		if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
1964 			return NULL;
1965 	}
1966 
1967 	return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
1968 			hbqp->hbqPutIdx;
1969 }
1970 
1971 /**
1972  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
1973  * @phba: Pointer to HBA context object.
1974  *
1975  * This function is called with no lock held to free all the
1976  * hbq buffers while uninitializing the SLI interface. It also
1977  * frees the HBQ buffers returned by the firmware but not yet
1978  * processed by the upper layers.
1979  **/
1980 void
1981 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
1982 {
1983 	struct lpfc_dmabuf *dmabuf, *next_dmabuf;
1984 	struct hbq_dmabuf *hbq_buf;
1985 	unsigned long flags;
1986 	int i, hbq_count;
1987 
1988 	hbq_count = lpfc_sli_hbq_count();
1989 	/* Return all memory used by all HBQs */
1990 	spin_lock_irqsave(&phba->hbalock, flags);
1991 	for (i = 0; i < hbq_count; ++i) {
1992 		list_for_each_entry_safe(dmabuf, next_dmabuf,
1993 				&phba->hbqs[i].hbq_buffer_list, list) {
1994 			hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
1995 			list_del(&hbq_buf->dbuf.list);
1996 			(phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
1997 		}
1998 		phba->hbqs[i].buffer_count = 0;
1999 	}
2000 
2001 	/* Mark the HBQs not in use */
2002 	phba->hbq_in_use = 0;
2003 	spin_unlock_irqrestore(&phba->hbalock, flags);
2004 }
2005 
2006 /**
2007  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2008  * @phba: Pointer to HBA context object.
2009  * @hbqno: HBQ number.
2010  * @hbq_buf: Pointer to HBQ buffer.
2011  *
2012  * This function is called with the hbalock held to post a
2013  * hbq buffer to the firmware. If the function finds an empty
2014  * slot in the HBQ, it will post the buffer. The function will return
2015  * pointer to the hbq entry if it successfully post the buffer
2016  * else it will return NULL.
2017  **/
2018 static int
2019 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2020 			 struct hbq_dmabuf *hbq_buf)
2021 {
2022 	lockdep_assert_held(&phba->hbalock);
2023 	return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2024 }
2025 
2026 /**
2027  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2028  * @phba: Pointer to HBA context object.
2029  * @hbqno: HBQ number.
2030  * @hbq_buf: Pointer to HBQ buffer.
2031  *
2032  * This function is called with the hbalock held to post a hbq buffer to the
2033  * firmware. If the function finds an empty slot in the HBQ, it will post the
2034  * buffer and place it on the hbq_buffer_list. The function will return zero if
2035  * it successfully post the buffer else it will return an error.
2036  **/
2037 static int
2038 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2039 			    struct hbq_dmabuf *hbq_buf)
2040 {
2041 	struct lpfc_hbq_entry *hbqe;
2042 	dma_addr_t physaddr = hbq_buf->dbuf.phys;
2043 
2044 	lockdep_assert_held(&phba->hbalock);
2045 	/* Get next HBQ entry slot to use */
2046 	hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2047 	if (hbqe) {
2048 		struct hbq_s *hbqp = &phba->hbqs[hbqno];
2049 
2050 		hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2051 		hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2052 		hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2053 		hbqe->bde.tus.f.bdeFlags = 0;
2054 		hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2055 		hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2056 				/* Sync SLIM */
2057 		hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2058 		writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2059 				/* flush */
2060 		readl(phba->hbq_put + hbqno);
2061 		list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2062 		return 0;
2063 	} else
2064 		return -ENOMEM;
2065 }
2066 
2067 /**
2068  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2069  * @phba: Pointer to HBA context object.
2070  * @hbqno: HBQ number.
2071  * @hbq_buf: Pointer to HBQ buffer.
2072  *
2073  * This function is called with the hbalock held to post an RQE to the SLI4
2074  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2075  * the hbq_buffer_list and return zero, otherwise it will return an error.
2076  **/
2077 static int
2078 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2079 			    struct hbq_dmabuf *hbq_buf)
2080 {
2081 	int rc;
2082 	struct lpfc_rqe hrqe;
2083 	struct lpfc_rqe drqe;
2084 	struct lpfc_queue *hrq;
2085 	struct lpfc_queue *drq;
2086 
2087 	if (hbqno != LPFC_ELS_HBQ)
2088 		return 1;
2089 	hrq = phba->sli4_hba.hdr_rq;
2090 	drq = phba->sli4_hba.dat_rq;
2091 
2092 	lockdep_assert_held(&phba->hbalock);
2093 	hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2094 	hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2095 	drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2096 	drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2097 	rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2098 	if (rc < 0)
2099 		return rc;
2100 	hbq_buf->tag = (rc | (hbqno << 16));
2101 	list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2102 	return 0;
2103 }
2104 
2105 /* HBQ for ELS and CT traffic. */
2106 static struct lpfc_hbq_init lpfc_els_hbq = {
2107 	.rn = 1,
2108 	.entry_count = 256,
2109 	.mask_count = 0,
2110 	.profile = 0,
2111 	.ring_mask = (1 << LPFC_ELS_RING),
2112 	.buffer_count = 0,
2113 	.init_count = 40,
2114 	.add_count = 40,
2115 };
2116 
2117 /* Array of HBQs */
2118 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2119 	&lpfc_els_hbq,
2120 };
2121 
2122 /**
2123  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2124  * @phba: Pointer to HBA context object.
2125  * @hbqno: HBQ number.
2126  * @count: Number of HBQ buffers to be posted.
2127  *
2128  * This function is called with no lock held to post more hbq buffers to the
2129  * given HBQ. The function returns the number of HBQ buffers successfully
2130  * posted.
2131  **/
2132 static int
2133 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2134 {
2135 	uint32_t i, posted = 0;
2136 	unsigned long flags;
2137 	struct hbq_dmabuf *hbq_buffer;
2138 	LIST_HEAD(hbq_buf_list);
2139 	if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2140 		return 0;
2141 
2142 	if ((phba->hbqs[hbqno].buffer_count + count) >
2143 	    lpfc_hbq_defs[hbqno]->entry_count)
2144 		count = lpfc_hbq_defs[hbqno]->entry_count -
2145 					phba->hbqs[hbqno].buffer_count;
2146 	if (!count)
2147 		return 0;
2148 	/* Allocate HBQ entries */
2149 	for (i = 0; i < count; i++) {
2150 		hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2151 		if (!hbq_buffer)
2152 			break;
2153 		list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2154 	}
2155 	/* Check whether HBQ is still in use */
2156 	spin_lock_irqsave(&phba->hbalock, flags);
2157 	if (!phba->hbq_in_use)
2158 		goto err;
2159 	while (!list_empty(&hbq_buf_list)) {
2160 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2161 				 dbuf.list);
2162 		hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2163 				      (hbqno << 16));
2164 		if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2165 			phba->hbqs[hbqno].buffer_count++;
2166 			posted++;
2167 		} else
2168 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2169 	}
2170 	spin_unlock_irqrestore(&phba->hbalock, flags);
2171 	return posted;
2172 err:
2173 	spin_unlock_irqrestore(&phba->hbalock, flags);
2174 	while (!list_empty(&hbq_buf_list)) {
2175 		list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2176 				 dbuf.list);
2177 		(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2178 	}
2179 	return 0;
2180 }
2181 
2182 /**
2183  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2184  * @phba: Pointer to HBA context object.
2185  * @qno: HBQ number.
2186  *
2187  * This function posts more buffers to the HBQ. This function
2188  * is called with no lock held. The function returns the number of HBQ entries
2189  * successfully allocated.
2190  **/
2191 int
2192 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2193 {
2194 	if (phba->sli_rev == LPFC_SLI_REV4)
2195 		return 0;
2196 	else
2197 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2198 					 lpfc_hbq_defs[qno]->add_count);
2199 }
2200 
2201 /**
2202  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2203  * @phba: Pointer to HBA context object.
2204  * @qno:  HBQ queue number.
2205  *
2206  * This function is called from SLI initialization code path with
2207  * no lock held to post initial HBQ buffers to firmware. The
2208  * function returns the number of HBQ entries successfully allocated.
2209  **/
2210 static int
2211 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2212 {
2213 	if (phba->sli_rev == LPFC_SLI_REV4)
2214 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2215 					lpfc_hbq_defs[qno]->entry_count);
2216 	else
2217 		return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2218 					 lpfc_hbq_defs[qno]->init_count);
2219 }
2220 
2221 /**
2222  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2223  * @phba: Pointer to HBA context object.
2224  * @hbqno: HBQ number.
2225  *
2226  * This function removes the first hbq buffer on an hbq list and returns a
2227  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2228  **/
2229 static struct hbq_dmabuf *
2230 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2231 {
2232 	struct lpfc_dmabuf *d_buf;
2233 
2234 	list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2235 	if (!d_buf)
2236 		return NULL;
2237 	return container_of(d_buf, struct hbq_dmabuf, dbuf);
2238 }
2239 
2240 /**
2241  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2242  * @phba: Pointer to HBA context object.
2243  * @hbqno: HBQ number.
2244  *
2245  * This function removes the first RQ buffer on an RQ buffer list and returns a
2246  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2247  **/
2248 static struct rqb_dmabuf *
2249 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2250 {
2251 	struct lpfc_dmabuf *h_buf;
2252 	struct lpfc_rqb *rqbp;
2253 
2254 	rqbp = hrq->rqbp;
2255 	list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2256 			 struct lpfc_dmabuf, list);
2257 	if (!h_buf)
2258 		return NULL;
2259 	rqbp->buffer_count--;
2260 	return container_of(h_buf, struct rqb_dmabuf, hbuf);
2261 }
2262 
2263 /**
2264  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2265  * @phba: Pointer to HBA context object.
2266  * @tag: Tag of the hbq buffer.
2267  *
2268  * This function searches for the hbq buffer associated with the given tag in
2269  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2270  * otherwise it returns NULL.
2271  **/
2272 static struct hbq_dmabuf *
2273 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2274 {
2275 	struct lpfc_dmabuf *d_buf;
2276 	struct hbq_dmabuf *hbq_buf;
2277 	uint32_t hbqno;
2278 
2279 	hbqno = tag >> 16;
2280 	if (hbqno >= LPFC_MAX_HBQS)
2281 		return NULL;
2282 
2283 	spin_lock_irq(&phba->hbalock);
2284 	list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2285 		hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2286 		if (hbq_buf->tag == tag) {
2287 			spin_unlock_irq(&phba->hbalock);
2288 			return hbq_buf;
2289 		}
2290 	}
2291 	spin_unlock_irq(&phba->hbalock);
2292 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_VPORT,
2293 			"1803 Bad hbq tag. Data: x%x x%x\n",
2294 			tag, phba->hbqs[tag >> 16].buffer_count);
2295 	return NULL;
2296 }
2297 
2298 /**
2299  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2300  * @phba: Pointer to HBA context object.
2301  * @hbq_buffer: Pointer to HBQ buffer.
2302  *
2303  * This function is called with hbalock. This function gives back
2304  * the hbq buffer to firmware. If the HBQ does not have space to
2305  * post the buffer, it will free the buffer.
2306  **/
2307 void
2308 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2309 {
2310 	uint32_t hbqno;
2311 
2312 	if (hbq_buffer) {
2313 		hbqno = hbq_buffer->tag >> 16;
2314 		if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2315 			(phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2316 	}
2317 }
2318 
2319 /**
2320  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2321  * @mbxCommand: mailbox command code.
2322  *
2323  * This function is called by the mailbox event handler function to verify
2324  * that the completed mailbox command is a legitimate mailbox command. If the
2325  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2326  * and the mailbox event handler will take the HBA offline.
2327  **/
2328 static int
2329 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2330 {
2331 	uint8_t ret;
2332 
2333 	switch (mbxCommand) {
2334 	case MBX_LOAD_SM:
2335 	case MBX_READ_NV:
2336 	case MBX_WRITE_NV:
2337 	case MBX_WRITE_VPARMS:
2338 	case MBX_RUN_BIU_DIAG:
2339 	case MBX_INIT_LINK:
2340 	case MBX_DOWN_LINK:
2341 	case MBX_CONFIG_LINK:
2342 	case MBX_CONFIG_RING:
2343 	case MBX_RESET_RING:
2344 	case MBX_READ_CONFIG:
2345 	case MBX_READ_RCONFIG:
2346 	case MBX_READ_SPARM:
2347 	case MBX_READ_STATUS:
2348 	case MBX_READ_RPI:
2349 	case MBX_READ_XRI:
2350 	case MBX_READ_REV:
2351 	case MBX_READ_LNK_STAT:
2352 	case MBX_REG_LOGIN:
2353 	case MBX_UNREG_LOGIN:
2354 	case MBX_CLEAR_LA:
2355 	case MBX_DUMP_MEMORY:
2356 	case MBX_DUMP_CONTEXT:
2357 	case MBX_RUN_DIAGS:
2358 	case MBX_RESTART:
2359 	case MBX_UPDATE_CFG:
2360 	case MBX_DOWN_LOAD:
2361 	case MBX_DEL_LD_ENTRY:
2362 	case MBX_RUN_PROGRAM:
2363 	case MBX_SET_MASK:
2364 	case MBX_SET_VARIABLE:
2365 	case MBX_UNREG_D_ID:
2366 	case MBX_KILL_BOARD:
2367 	case MBX_CONFIG_FARP:
2368 	case MBX_BEACON:
2369 	case MBX_LOAD_AREA:
2370 	case MBX_RUN_BIU_DIAG64:
2371 	case MBX_CONFIG_PORT:
2372 	case MBX_READ_SPARM64:
2373 	case MBX_READ_RPI64:
2374 	case MBX_REG_LOGIN64:
2375 	case MBX_READ_TOPOLOGY:
2376 	case MBX_WRITE_WWN:
2377 	case MBX_SET_DEBUG:
2378 	case MBX_LOAD_EXP_ROM:
2379 	case MBX_ASYNCEVT_ENABLE:
2380 	case MBX_REG_VPI:
2381 	case MBX_UNREG_VPI:
2382 	case MBX_HEARTBEAT:
2383 	case MBX_PORT_CAPABILITIES:
2384 	case MBX_PORT_IOV_CONTROL:
2385 	case MBX_SLI4_CONFIG:
2386 	case MBX_SLI4_REQ_FTRS:
2387 	case MBX_REG_FCFI:
2388 	case MBX_UNREG_FCFI:
2389 	case MBX_REG_VFI:
2390 	case MBX_UNREG_VFI:
2391 	case MBX_INIT_VPI:
2392 	case MBX_INIT_VFI:
2393 	case MBX_RESUME_RPI:
2394 	case MBX_READ_EVENT_LOG_STATUS:
2395 	case MBX_READ_EVENT_LOG:
2396 	case MBX_SECURITY_MGMT:
2397 	case MBX_AUTH_PORT:
2398 	case MBX_ACCESS_VDATA:
2399 		ret = mbxCommand;
2400 		break;
2401 	default:
2402 		ret = MBX_SHUTDOWN;
2403 		break;
2404 	}
2405 	return ret;
2406 }
2407 
2408 /**
2409  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2410  * @phba: Pointer to HBA context object.
2411  * @pmboxq: Pointer to mailbox command.
2412  *
2413  * This is completion handler function for mailbox commands issued from
2414  * lpfc_sli_issue_mbox_wait function. This function is called by the
2415  * mailbox event handler function with no lock held. This function
2416  * will wake up thread waiting on the wait queue pointed by context1
2417  * of the mailbox.
2418  **/
2419 void
2420 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2421 {
2422 	unsigned long drvr_flag;
2423 	struct completion *pmbox_done;
2424 
2425 	/*
2426 	 * If pmbox_done is empty, the driver thread gave up waiting and
2427 	 * continued running.
2428 	 */
2429 	pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2430 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
2431 	pmbox_done = (struct completion *)pmboxq->context3;
2432 	if (pmbox_done)
2433 		complete(pmbox_done);
2434 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2435 	return;
2436 }
2437 
2438 
2439 /**
2440  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2441  * @phba: Pointer to HBA context object.
2442  * @pmb: Pointer to mailbox object.
2443  *
2444  * This function is the default mailbox completion handler. It
2445  * frees the memory resources associated with the completed mailbox
2446  * command. If the completed command is a REG_LOGIN mailbox command,
2447  * this function will issue a UREG_LOGIN to re-claim the RPI.
2448  **/
2449 void
2450 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2451 {
2452 	struct lpfc_vport  *vport = pmb->vport;
2453 	struct lpfc_dmabuf *mp;
2454 	struct lpfc_nodelist *ndlp;
2455 	struct Scsi_Host *shost;
2456 	uint16_t rpi, vpi;
2457 	int rc;
2458 
2459 	mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
2460 
2461 	if (mp) {
2462 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
2463 		kfree(mp);
2464 	}
2465 
2466 	/*
2467 	 * If a REG_LOGIN succeeded  after node is destroyed or node
2468 	 * is in re-discovery driver need to cleanup the RPI.
2469 	 */
2470 	if (!(phba->pport->load_flag & FC_UNLOADING) &&
2471 	    pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2472 	    !pmb->u.mb.mbxStatus) {
2473 		rpi = pmb->u.mb.un.varWords[0];
2474 		vpi = pmb->u.mb.un.varRegLogin.vpi;
2475 		lpfc_unreg_login(phba, vpi, rpi, pmb);
2476 		pmb->vport = vport;
2477 		pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2478 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2479 		if (rc != MBX_NOT_FINISHED)
2480 			return;
2481 	}
2482 
2483 	if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2484 		!(phba->pport->load_flag & FC_UNLOADING) &&
2485 		!pmb->u.mb.mbxStatus) {
2486 		shost = lpfc_shost_from_vport(vport);
2487 		spin_lock_irq(shost->host_lock);
2488 		vport->vpi_state |= LPFC_VPI_REGISTERED;
2489 		vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2490 		spin_unlock_irq(shost->host_lock);
2491 	}
2492 
2493 	if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2494 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2495 		lpfc_nlp_put(ndlp);
2496 		pmb->ctx_buf = NULL;
2497 		pmb->ctx_ndlp = NULL;
2498 	}
2499 
2500 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2501 		ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2502 
2503 		/* Check to see if there are any deferred events to process */
2504 		if (ndlp) {
2505 			lpfc_printf_vlog(
2506 				vport,
2507 				KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2508 				"1438 UNREG cmpl deferred mbox x%x "
2509 				"on NPort x%x Data: x%x x%x %p\n",
2510 				ndlp->nlp_rpi, ndlp->nlp_DID,
2511 				ndlp->nlp_flag, ndlp->nlp_defer_did, ndlp);
2512 
2513 			if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2514 			    (ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING)) {
2515 				ndlp->nlp_flag &= ~NLP_UNREG_INP;
2516 				ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2517 				lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2518 			} else {
2519 				ndlp->nlp_flag &= ~NLP_UNREG_INP;
2520 			}
2521 		}
2522 		pmb->ctx_ndlp = NULL;
2523 	}
2524 
2525 	/* Check security permission status on INIT_LINK mailbox command */
2526 	if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2527 	    (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2528 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
2529 				"2860 SLI authentication is required "
2530 				"for INIT_LINK but has not done yet\n");
2531 
2532 	if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2533 		lpfc_sli4_mbox_cmd_free(phba, pmb);
2534 	else
2535 		mempool_free(pmb, phba->mbox_mem_pool);
2536 }
2537  /**
2538  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2539  * @phba: Pointer to HBA context object.
2540  * @pmb: Pointer to mailbox object.
2541  *
2542  * This function is the unreg rpi mailbox completion handler. It
2543  * frees the memory resources associated with the completed mailbox
2544  * command. An additional refrenece is put on the ndlp to prevent
2545  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2546  * the unreg mailbox command completes, this routine puts the
2547  * reference back.
2548  *
2549  **/
2550 void
2551 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2552 {
2553 	struct lpfc_vport  *vport = pmb->vport;
2554 	struct lpfc_nodelist *ndlp;
2555 
2556 	ndlp = pmb->ctx_ndlp;
2557 	if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2558 		if (phba->sli_rev == LPFC_SLI_REV4 &&
2559 		    (bf_get(lpfc_sli_intf_if_type,
2560 		     &phba->sli4_hba.sli_intf) >=
2561 		     LPFC_SLI_INTF_IF_TYPE_2)) {
2562 			if (ndlp) {
2563 				lpfc_printf_vlog(
2564 					vport, KERN_INFO, LOG_MBOX | LOG_SLI,
2565 					 "0010 UNREG_LOGIN vpi:%x "
2566 					 "rpi:%x DID:%x defer x%x flg x%x "
2567 					 "map:%x %p\n",
2568 					 vport->vpi, ndlp->nlp_rpi,
2569 					 ndlp->nlp_DID, ndlp->nlp_defer_did,
2570 					 ndlp->nlp_flag,
2571 					 ndlp->nlp_usg_map, ndlp);
2572 				ndlp->nlp_flag &= ~NLP_LOGO_ACC;
2573 				lpfc_nlp_put(ndlp);
2574 
2575 				/* Check to see if there are any deferred
2576 				 * events to process
2577 				 */
2578 				if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2579 				    (ndlp->nlp_defer_did !=
2580 				    NLP_EVT_NOTHING_PENDING)) {
2581 					lpfc_printf_vlog(
2582 						vport, KERN_INFO, LOG_DISCOVERY,
2583 						"4111 UNREG cmpl deferred "
2584 						"clr x%x on "
2585 						"NPort x%x Data: x%x %p\n",
2586 						ndlp->nlp_rpi, ndlp->nlp_DID,
2587 						ndlp->nlp_defer_did, ndlp);
2588 					ndlp->nlp_flag &= ~NLP_UNREG_INP;
2589 					ndlp->nlp_defer_did =
2590 						NLP_EVT_NOTHING_PENDING;
2591 					lpfc_issue_els_plogi(
2592 						vport, ndlp->nlp_DID, 0);
2593 				} else {
2594 					ndlp->nlp_flag &= ~NLP_UNREG_INP;
2595 				}
2596 			}
2597 		}
2598 	}
2599 
2600 	mempool_free(pmb, phba->mbox_mem_pool);
2601 }
2602 
2603 /**
2604  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
2605  * @phba: Pointer to HBA context object.
2606  *
2607  * This function is called with no lock held. This function processes all
2608  * the completed mailbox commands and gives it to upper layers. The interrupt
2609  * service routine processes mailbox completion interrupt and adds completed
2610  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
2611  * Worker thread call lpfc_sli_handle_mb_event, which will return the
2612  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
2613  * function returns the mailbox commands to the upper layer by calling the
2614  * completion handler function of each mailbox.
2615  **/
2616 int
2617 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
2618 {
2619 	MAILBOX_t *pmbox;
2620 	LPFC_MBOXQ_t *pmb;
2621 	int rc;
2622 	LIST_HEAD(cmplq);
2623 
2624 	phba->sli.slistat.mbox_event++;
2625 
2626 	/* Get all completed mailboxe buffers into the cmplq */
2627 	spin_lock_irq(&phba->hbalock);
2628 	list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
2629 	spin_unlock_irq(&phba->hbalock);
2630 
2631 	/* Get a Mailbox buffer to setup mailbox commands for callback */
2632 	do {
2633 		list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
2634 		if (pmb == NULL)
2635 			break;
2636 
2637 		pmbox = &pmb->u.mb;
2638 
2639 		if (pmbox->mbxCommand != MBX_HEARTBEAT) {
2640 			if (pmb->vport) {
2641 				lpfc_debugfs_disc_trc(pmb->vport,
2642 					LPFC_DISC_TRC_MBOX_VPORT,
2643 					"MBOX cmpl vport: cmd:x%x mb:x%x x%x",
2644 					(uint32_t)pmbox->mbxCommand,
2645 					pmbox->un.varWords[0],
2646 					pmbox->un.varWords[1]);
2647 			}
2648 			else {
2649 				lpfc_debugfs_disc_trc(phba->pport,
2650 					LPFC_DISC_TRC_MBOX,
2651 					"MBOX cmpl:       cmd:x%x mb:x%x x%x",
2652 					(uint32_t)pmbox->mbxCommand,
2653 					pmbox->un.varWords[0],
2654 					pmbox->un.varWords[1]);
2655 			}
2656 		}
2657 
2658 		/*
2659 		 * It is a fatal error if unknown mbox command completion.
2660 		 */
2661 		if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
2662 		    MBX_SHUTDOWN) {
2663 			/* Unknown mailbox command compl */
2664 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
2665 					"(%d):0323 Unknown Mailbox command "
2666 					"x%x (x%x/x%x) Cmpl\n",
2667 					pmb->vport ? pmb->vport->vpi : 0,
2668 					pmbox->mbxCommand,
2669 					lpfc_sli_config_mbox_subsys_get(phba,
2670 									pmb),
2671 					lpfc_sli_config_mbox_opcode_get(phba,
2672 									pmb));
2673 			phba->link_state = LPFC_HBA_ERROR;
2674 			phba->work_hs = HS_FFER3;
2675 			lpfc_handle_eratt(phba);
2676 			continue;
2677 		}
2678 
2679 		if (pmbox->mbxStatus) {
2680 			phba->sli.slistat.mbox_stat_err++;
2681 			if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
2682 				/* Mbox cmd cmpl error - RETRYing */
2683 				lpfc_printf_log(phba, KERN_INFO,
2684 					LOG_MBOX | LOG_SLI,
2685 					"(%d):0305 Mbox cmd cmpl "
2686 					"error - RETRYing Data: x%x "
2687 					"(x%x/x%x) x%x x%x x%x\n",
2688 					pmb->vport ? pmb->vport->vpi : 0,
2689 					pmbox->mbxCommand,
2690 					lpfc_sli_config_mbox_subsys_get(phba,
2691 									pmb),
2692 					lpfc_sli_config_mbox_opcode_get(phba,
2693 									pmb),
2694 					pmbox->mbxStatus,
2695 					pmbox->un.varWords[0],
2696 					pmb->vport->port_state);
2697 				pmbox->mbxStatus = 0;
2698 				pmbox->mbxOwner = OWN_HOST;
2699 				rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2700 				if (rc != MBX_NOT_FINISHED)
2701 					continue;
2702 			}
2703 		}
2704 
2705 		/* Mailbox cmd <cmd> Cmpl <cmpl> */
2706 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
2707 				"(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl x%p "
2708 				"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
2709 				"x%x x%x x%x\n",
2710 				pmb->vport ? pmb->vport->vpi : 0,
2711 				pmbox->mbxCommand,
2712 				lpfc_sli_config_mbox_subsys_get(phba, pmb),
2713 				lpfc_sli_config_mbox_opcode_get(phba, pmb),
2714 				pmb->mbox_cmpl,
2715 				*((uint32_t *) pmbox),
2716 				pmbox->un.varWords[0],
2717 				pmbox->un.varWords[1],
2718 				pmbox->un.varWords[2],
2719 				pmbox->un.varWords[3],
2720 				pmbox->un.varWords[4],
2721 				pmbox->un.varWords[5],
2722 				pmbox->un.varWords[6],
2723 				pmbox->un.varWords[7],
2724 				pmbox->un.varWords[8],
2725 				pmbox->un.varWords[9],
2726 				pmbox->un.varWords[10]);
2727 
2728 		if (pmb->mbox_cmpl)
2729 			pmb->mbox_cmpl(phba,pmb);
2730 	} while (1);
2731 	return 0;
2732 }
2733 
2734 /**
2735  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
2736  * @phba: Pointer to HBA context object.
2737  * @pring: Pointer to driver SLI ring object.
2738  * @tag: buffer tag.
2739  *
2740  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
2741  * is set in the tag the buffer is posted for a particular exchange,
2742  * the function will return the buffer without replacing the buffer.
2743  * If the buffer is for unsolicited ELS or CT traffic, this function
2744  * returns the buffer and also posts another buffer to the firmware.
2745  **/
2746 static struct lpfc_dmabuf *
2747 lpfc_sli_get_buff(struct lpfc_hba *phba,
2748 		  struct lpfc_sli_ring *pring,
2749 		  uint32_t tag)
2750 {
2751 	struct hbq_dmabuf *hbq_entry;
2752 
2753 	if (tag & QUE_BUFTAG_BIT)
2754 		return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
2755 	hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
2756 	if (!hbq_entry)
2757 		return NULL;
2758 	return &hbq_entry->dbuf;
2759 }
2760 
2761 /**
2762  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
2763  * @phba: Pointer to HBA context object.
2764  * @pring: Pointer to driver SLI ring object.
2765  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
2766  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
2767  * @fch_type: the type for the first frame of the sequence.
2768  *
2769  * This function is called with no lock held. This function uses the r_ctl and
2770  * type of the received sequence to find the correct callback function to call
2771  * to process the sequence.
2772  **/
2773 static int
2774 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2775 			 struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
2776 			 uint32_t fch_type)
2777 {
2778 	int i;
2779 
2780 	switch (fch_type) {
2781 	case FC_TYPE_NVME:
2782 		lpfc_nvmet_unsol_ls_event(phba, pring, saveq);
2783 		return 1;
2784 	default:
2785 		break;
2786 	}
2787 
2788 	/* unSolicited Responses */
2789 	if (pring->prt[0].profile) {
2790 		if (pring->prt[0].lpfc_sli_rcv_unsol_event)
2791 			(pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
2792 									saveq);
2793 		return 1;
2794 	}
2795 	/* We must search, based on rctl / type
2796 	   for the right routine */
2797 	for (i = 0; i < pring->num_mask; i++) {
2798 		if ((pring->prt[i].rctl == fch_r_ctl) &&
2799 		    (pring->prt[i].type == fch_type)) {
2800 			if (pring->prt[i].lpfc_sli_rcv_unsol_event)
2801 				(pring->prt[i].lpfc_sli_rcv_unsol_event)
2802 						(phba, pring, saveq);
2803 			return 1;
2804 		}
2805 	}
2806 	return 0;
2807 }
2808 
2809 /**
2810  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
2811  * @phba: Pointer to HBA context object.
2812  * @pring: Pointer to driver SLI ring object.
2813  * @saveq: Pointer to the unsolicited iocb.
2814  *
2815  * This function is called with no lock held by the ring event handler
2816  * when there is an unsolicited iocb posted to the response ring by the
2817  * firmware. This function gets the buffer associated with the iocbs
2818  * and calls the event handler for the ring. This function handles both
2819  * qring buffers and hbq buffers.
2820  * When the function returns 1 the caller can free the iocb object otherwise
2821  * upper layer functions will free the iocb objects.
2822  **/
2823 static int
2824 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2825 			    struct lpfc_iocbq *saveq)
2826 {
2827 	IOCB_t           * irsp;
2828 	WORD5            * w5p;
2829 	uint32_t           Rctl, Type;
2830 	struct lpfc_iocbq *iocbq;
2831 	struct lpfc_dmabuf *dmzbuf;
2832 
2833 	irsp = &(saveq->iocb);
2834 
2835 	if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
2836 		if (pring->lpfc_sli_rcv_async_status)
2837 			pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
2838 		else
2839 			lpfc_printf_log(phba,
2840 					KERN_WARNING,
2841 					LOG_SLI,
2842 					"0316 Ring %d handler: unexpected "
2843 					"ASYNC_STATUS iocb received evt_code "
2844 					"0x%x\n",
2845 					pring->ringno,
2846 					irsp->un.asyncstat.evt_code);
2847 		return 1;
2848 	}
2849 
2850 	if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
2851 		(phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
2852 		if (irsp->ulpBdeCount > 0) {
2853 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2854 					irsp->un.ulpWord[3]);
2855 			lpfc_in_buf_free(phba, dmzbuf);
2856 		}
2857 
2858 		if (irsp->ulpBdeCount > 1) {
2859 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2860 					irsp->unsli3.sli3Words[3]);
2861 			lpfc_in_buf_free(phba, dmzbuf);
2862 		}
2863 
2864 		if (irsp->ulpBdeCount > 2) {
2865 			dmzbuf = lpfc_sli_get_buff(phba, pring,
2866 				irsp->unsli3.sli3Words[7]);
2867 			lpfc_in_buf_free(phba, dmzbuf);
2868 		}
2869 
2870 		return 1;
2871 	}
2872 
2873 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
2874 		if (irsp->ulpBdeCount != 0) {
2875 			saveq->context2 = lpfc_sli_get_buff(phba, pring,
2876 						irsp->un.ulpWord[3]);
2877 			if (!saveq->context2)
2878 				lpfc_printf_log(phba,
2879 					KERN_ERR,
2880 					LOG_SLI,
2881 					"0341 Ring %d Cannot find buffer for "
2882 					"an unsolicited iocb. tag 0x%x\n",
2883 					pring->ringno,
2884 					irsp->un.ulpWord[3]);
2885 		}
2886 		if (irsp->ulpBdeCount == 2) {
2887 			saveq->context3 = lpfc_sli_get_buff(phba, pring,
2888 						irsp->unsli3.sli3Words[7]);
2889 			if (!saveq->context3)
2890 				lpfc_printf_log(phba,
2891 					KERN_ERR,
2892 					LOG_SLI,
2893 					"0342 Ring %d Cannot find buffer for an"
2894 					" unsolicited iocb. tag 0x%x\n",
2895 					pring->ringno,
2896 					irsp->unsli3.sli3Words[7]);
2897 		}
2898 		list_for_each_entry(iocbq, &saveq->list, list) {
2899 			irsp = &(iocbq->iocb);
2900 			if (irsp->ulpBdeCount != 0) {
2901 				iocbq->context2 = lpfc_sli_get_buff(phba, pring,
2902 							irsp->un.ulpWord[3]);
2903 				if (!iocbq->context2)
2904 					lpfc_printf_log(phba,
2905 						KERN_ERR,
2906 						LOG_SLI,
2907 						"0343 Ring %d Cannot find "
2908 						"buffer for an unsolicited iocb"
2909 						". tag 0x%x\n", pring->ringno,
2910 						irsp->un.ulpWord[3]);
2911 			}
2912 			if (irsp->ulpBdeCount == 2) {
2913 				iocbq->context3 = lpfc_sli_get_buff(phba, pring,
2914 						irsp->unsli3.sli3Words[7]);
2915 				if (!iocbq->context3)
2916 					lpfc_printf_log(phba,
2917 						KERN_ERR,
2918 						LOG_SLI,
2919 						"0344 Ring %d Cannot find "
2920 						"buffer for an unsolicited "
2921 						"iocb. tag 0x%x\n",
2922 						pring->ringno,
2923 						irsp->unsli3.sli3Words[7]);
2924 			}
2925 		}
2926 	}
2927 	if (irsp->ulpBdeCount != 0 &&
2928 	    (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
2929 	     irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
2930 		int found = 0;
2931 
2932 		/* search continue save q for same XRI */
2933 		list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
2934 			if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
2935 				saveq->iocb.unsli3.rcvsli3.ox_id) {
2936 				list_add_tail(&saveq->list, &iocbq->list);
2937 				found = 1;
2938 				break;
2939 			}
2940 		}
2941 		if (!found)
2942 			list_add_tail(&saveq->clist,
2943 				      &pring->iocb_continue_saveq);
2944 		if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
2945 			list_del_init(&iocbq->clist);
2946 			saveq = iocbq;
2947 			irsp = &(saveq->iocb);
2948 		} else
2949 			return 0;
2950 	}
2951 	if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
2952 	    (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
2953 	    (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
2954 		Rctl = FC_RCTL_ELS_REQ;
2955 		Type = FC_TYPE_ELS;
2956 	} else {
2957 		w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
2958 		Rctl = w5p->hcsw.Rctl;
2959 		Type = w5p->hcsw.Type;
2960 
2961 		/* Firmware Workaround */
2962 		if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
2963 			(irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
2964 			 irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
2965 			Rctl = FC_RCTL_ELS_REQ;
2966 			Type = FC_TYPE_ELS;
2967 			w5p->hcsw.Rctl = Rctl;
2968 			w5p->hcsw.Type = Type;
2969 		}
2970 	}
2971 
2972 	if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
2973 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2974 				"0313 Ring %d handler: unexpected Rctl x%x "
2975 				"Type x%x received\n",
2976 				pring->ringno, Rctl, Type);
2977 
2978 	return 1;
2979 }
2980 
2981 /**
2982  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
2983  * @phba: Pointer to HBA context object.
2984  * @pring: Pointer to driver SLI ring object.
2985  * @prspiocb: Pointer to response iocb object.
2986  *
2987  * This function looks up the iocb_lookup table to get the command iocb
2988  * corresponding to the given response iocb using the iotag of the
2989  * response iocb. This function is called with the hbalock held
2990  * for sli3 devices or the ring_lock for sli4 devices.
2991  * This function returns the command iocb object if it finds the command
2992  * iocb else returns NULL.
2993  **/
2994 static struct lpfc_iocbq *
2995 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
2996 		      struct lpfc_sli_ring *pring,
2997 		      struct lpfc_iocbq *prspiocb)
2998 {
2999 	struct lpfc_iocbq *cmd_iocb = NULL;
3000 	uint16_t iotag;
3001 	lockdep_assert_held(&phba->hbalock);
3002 
3003 	iotag = prspiocb->iocb.ulpIoTag;
3004 
3005 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3006 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3007 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3008 			/* remove from txcmpl queue list */
3009 			list_del_init(&cmd_iocb->list);
3010 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3011 			return cmd_iocb;
3012 		}
3013 	}
3014 
3015 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3016 			"0317 iotag x%x is out of "
3017 			"range: max iotag x%x wd0 x%x\n",
3018 			iotag, phba->sli.last_iotag,
3019 			*(((uint32_t *) &prspiocb->iocb) + 7));
3020 	return NULL;
3021 }
3022 
3023 /**
3024  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3025  * @phba: Pointer to HBA context object.
3026  * @pring: Pointer to driver SLI ring object.
3027  * @iotag: IOCB tag.
3028  *
3029  * This function looks up the iocb_lookup table to get the command iocb
3030  * corresponding to the given iotag. This function is called with the
3031  * hbalock held.
3032  * This function returns the command iocb object if it finds the command
3033  * iocb else returns NULL.
3034  **/
3035 static struct lpfc_iocbq *
3036 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3037 			     struct lpfc_sli_ring *pring, uint16_t iotag)
3038 {
3039 	struct lpfc_iocbq *cmd_iocb = NULL;
3040 
3041 	lockdep_assert_held(&phba->hbalock);
3042 	if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3043 		cmd_iocb = phba->sli.iocbq_lookup[iotag];
3044 		if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3045 			/* remove from txcmpl queue list */
3046 			list_del_init(&cmd_iocb->list);
3047 			cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3048 			return cmd_iocb;
3049 		}
3050 	}
3051 
3052 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3053 			"0372 iotag x%x lookup error: max iotag (x%x) "
3054 			"iocb_flag x%x\n",
3055 			iotag, phba->sli.last_iotag,
3056 			cmd_iocb ? cmd_iocb->iocb_flag : 0xffff);
3057 	return NULL;
3058 }
3059 
3060 /**
3061  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3062  * @phba: Pointer to HBA context object.
3063  * @pring: Pointer to driver SLI ring object.
3064  * @saveq: Pointer to the response iocb to be processed.
3065  *
3066  * This function is called by the ring event handler for non-fcp
3067  * rings when there is a new response iocb in the response ring.
3068  * The caller is not required to hold any locks. This function
3069  * gets the command iocb associated with the response iocb and
3070  * calls the completion handler for the command iocb. If there
3071  * is no completion handler, the function will free the resources
3072  * associated with command iocb. If the response iocb is for
3073  * an already aborted command iocb, the status of the completion
3074  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3075  * This function always returns 1.
3076  **/
3077 static int
3078 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3079 			  struct lpfc_iocbq *saveq)
3080 {
3081 	struct lpfc_iocbq *cmdiocbp;
3082 	int rc = 1;
3083 	unsigned long iflag;
3084 
3085 	/* Based on the iotag field, get the cmd IOCB from the txcmplq */
3086 	if (phba->sli_rev == LPFC_SLI_REV4)
3087 		spin_lock_irqsave(&pring->ring_lock, iflag);
3088 	else
3089 		spin_lock_irqsave(&phba->hbalock, iflag);
3090 	cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3091 	if (phba->sli_rev == LPFC_SLI_REV4)
3092 		spin_unlock_irqrestore(&pring->ring_lock, iflag);
3093 	else
3094 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3095 
3096 	if (cmdiocbp) {
3097 		if (cmdiocbp->iocb_cmpl) {
3098 			/*
3099 			 * If an ELS command failed send an event to mgmt
3100 			 * application.
3101 			 */
3102 			if (saveq->iocb.ulpStatus &&
3103 			     (pring->ringno == LPFC_ELS_RING) &&
3104 			     (cmdiocbp->iocb.ulpCommand ==
3105 				CMD_ELS_REQUEST64_CR))
3106 				lpfc_send_els_failure_event(phba,
3107 					cmdiocbp, saveq);
3108 
3109 			/*
3110 			 * Post all ELS completions to the worker thread.
3111 			 * All other are passed to the completion callback.
3112 			 */
3113 			if (pring->ringno == LPFC_ELS_RING) {
3114 				if ((phba->sli_rev < LPFC_SLI_REV4) &&
3115 				    (cmdiocbp->iocb_flag &
3116 							LPFC_DRIVER_ABORTED)) {
3117 					spin_lock_irqsave(&phba->hbalock,
3118 							  iflag);
3119 					cmdiocbp->iocb_flag &=
3120 						~LPFC_DRIVER_ABORTED;
3121 					spin_unlock_irqrestore(&phba->hbalock,
3122 							       iflag);
3123 					saveq->iocb.ulpStatus =
3124 						IOSTAT_LOCAL_REJECT;
3125 					saveq->iocb.un.ulpWord[4] =
3126 						IOERR_SLI_ABORTED;
3127 
3128 					/* Firmware could still be in progress
3129 					 * of DMAing payload, so don't free data
3130 					 * buffer till after a hbeat.
3131 					 */
3132 					spin_lock_irqsave(&phba->hbalock,
3133 							  iflag);
3134 					saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
3135 					spin_unlock_irqrestore(&phba->hbalock,
3136 							       iflag);
3137 				}
3138 				if (phba->sli_rev == LPFC_SLI_REV4) {
3139 					if (saveq->iocb_flag &
3140 					    LPFC_EXCHANGE_BUSY) {
3141 						/* Set cmdiocb flag for the
3142 						 * exchange busy so sgl (xri)
3143 						 * will not be released until
3144 						 * the abort xri is received
3145 						 * from hba.
3146 						 */
3147 						spin_lock_irqsave(
3148 							&phba->hbalock, iflag);
3149 						cmdiocbp->iocb_flag |=
3150 							LPFC_EXCHANGE_BUSY;
3151 						spin_unlock_irqrestore(
3152 							&phba->hbalock, iflag);
3153 					}
3154 					if (cmdiocbp->iocb_flag &
3155 					    LPFC_DRIVER_ABORTED) {
3156 						/*
3157 						 * Clear LPFC_DRIVER_ABORTED
3158 						 * bit in case it was driver
3159 						 * initiated abort.
3160 						 */
3161 						spin_lock_irqsave(
3162 							&phba->hbalock, iflag);
3163 						cmdiocbp->iocb_flag &=
3164 							~LPFC_DRIVER_ABORTED;
3165 						spin_unlock_irqrestore(
3166 							&phba->hbalock, iflag);
3167 						cmdiocbp->iocb.ulpStatus =
3168 							IOSTAT_LOCAL_REJECT;
3169 						cmdiocbp->iocb.un.ulpWord[4] =
3170 							IOERR_ABORT_REQUESTED;
3171 						/*
3172 						 * For SLI4, irsiocb contains
3173 						 * NO_XRI in sli_xritag, it
3174 						 * shall not affect releasing
3175 						 * sgl (xri) process.
3176 						 */
3177 						saveq->iocb.ulpStatus =
3178 							IOSTAT_LOCAL_REJECT;
3179 						saveq->iocb.un.ulpWord[4] =
3180 							IOERR_SLI_ABORTED;
3181 						spin_lock_irqsave(
3182 							&phba->hbalock, iflag);
3183 						saveq->iocb_flag |=
3184 							LPFC_DELAY_MEM_FREE;
3185 						spin_unlock_irqrestore(
3186 							&phba->hbalock, iflag);
3187 					}
3188 				}
3189 			}
3190 			(cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
3191 		} else
3192 			lpfc_sli_release_iocbq(phba, cmdiocbp);
3193 	} else {
3194 		/*
3195 		 * Unknown initiating command based on the response iotag.
3196 		 * This could be the case on the ELS ring because of
3197 		 * lpfc_els_abort().
3198 		 */
3199 		if (pring->ringno != LPFC_ELS_RING) {
3200 			/*
3201 			 * Ring <ringno> handler: unexpected completion IoTag
3202 			 * <IoTag>
3203 			 */
3204 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3205 					 "0322 Ring %d handler: "
3206 					 "unexpected completion IoTag x%x "
3207 					 "Data: x%x x%x x%x x%x\n",
3208 					 pring->ringno,
3209 					 saveq->iocb.ulpIoTag,
3210 					 saveq->iocb.ulpStatus,
3211 					 saveq->iocb.un.ulpWord[4],
3212 					 saveq->iocb.ulpCommand,
3213 					 saveq->iocb.ulpContext);
3214 		}
3215 	}
3216 
3217 	return rc;
3218 }
3219 
3220 /**
3221  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3222  * @phba: Pointer to HBA context object.
3223  * @pring: Pointer to driver SLI ring object.
3224  *
3225  * This function is called from the iocb ring event handlers when
3226  * put pointer is ahead of the get pointer for a ring. This function signal
3227  * an error attention condition to the worker thread and the worker
3228  * thread will transition the HBA to offline state.
3229  **/
3230 static void
3231 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3232 {
3233 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3234 	/*
3235 	 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3236 	 * rsp ring <portRspMax>
3237 	 */
3238 	lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3239 			"0312 Ring %d handler: portRspPut %d "
3240 			"is bigger than rsp ring %d\n",
3241 			pring->ringno, le32_to_cpu(pgp->rspPutInx),
3242 			pring->sli.sli3.numRiocb);
3243 
3244 	phba->link_state = LPFC_HBA_ERROR;
3245 
3246 	/*
3247 	 * All error attention handlers are posted to
3248 	 * worker thread
3249 	 */
3250 	phba->work_ha |= HA_ERATT;
3251 	phba->work_hs = HS_FFER3;
3252 
3253 	lpfc_worker_wake_up(phba);
3254 
3255 	return;
3256 }
3257 
3258 /**
3259  * lpfc_poll_eratt - Error attention polling timer timeout handler
3260  * @ptr: Pointer to address of HBA context object.
3261  *
3262  * This function is invoked by the Error Attention polling timer when the
3263  * timer times out. It will check the SLI Error Attention register for
3264  * possible attention events. If so, it will post an Error Attention event
3265  * and wake up worker thread to process it. Otherwise, it will set up the
3266  * Error Attention polling timer for the next poll.
3267  **/
3268 void lpfc_poll_eratt(struct timer_list *t)
3269 {
3270 	struct lpfc_hba *phba;
3271 	uint32_t eratt = 0;
3272 	uint64_t sli_intr, cnt;
3273 
3274 	phba = from_timer(phba, t, eratt_poll);
3275 
3276 	/* Here we will also keep track of interrupts per sec of the hba */
3277 	sli_intr = phba->sli.slistat.sli_intr;
3278 
3279 	if (phba->sli.slistat.sli_prev_intr > sli_intr)
3280 		cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3281 			sli_intr);
3282 	else
3283 		cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3284 
3285 	/* 64-bit integer division not supported on 32-bit x86 - use do_div */
3286 	do_div(cnt, phba->eratt_poll_interval);
3287 	phba->sli.slistat.sli_ips = cnt;
3288 
3289 	phba->sli.slistat.sli_prev_intr = sli_intr;
3290 
3291 	/* Check chip HA register for error event */
3292 	eratt = lpfc_sli_check_eratt(phba);
3293 
3294 	if (eratt)
3295 		/* Tell the worker thread there is work to do */
3296 		lpfc_worker_wake_up(phba);
3297 	else
3298 		/* Restart the timer for next eratt poll */
3299 		mod_timer(&phba->eratt_poll,
3300 			  jiffies +
3301 			  msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3302 	return;
3303 }
3304 
3305 
3306 /**
3307  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3308  * @phba: Pointer to HBA context object.
3309  * @pring: Pointer to driver SLI ring object.
3310  * @mask: Host attention register mask for this ring.
3311  *
3312  * This function is called from the interrupt context when there is a ring
3313  * event for the fcp ring. The caller does not hold any lock.
3314  * The function processes each response iocb in the response ring until it
3315  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3316  * LE bit set. The function will call the completion handler of the command iocb
3317  * if the response iocb indicates a completion for a command iocb or it is
3318  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3319  * function if this is an unsolicited iocb.
3320  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3321  * to check it explicitly.
3322  */
3323 int
3324 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3325 				struct lpfc_sli_ring *pring, uint32_t mask)
3326 {
3327 	struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3328 	IOCB_t *irsp = NULL;
3329 	IOCB_t *entry = NULL;
3330 	struct lpfc_iocbq *cmdiocbq = NULL;
3331 	struct lpfc_iocbq rspiocbq;
3332 	uint32_t status;
3333 	uint32_t portRspPut, portRspMax;
3334 	int rc = 1;
3335 	lpfc_iocb_type type;
3336 	unsigned long iflag;
3337 	uint32_t rsp_cmpl = 0;
3338 
3339 	spin_lock_irqsave(&phba->hbalock, iflag);
3340 	pring->stats.iocb_event++;
3341 
3342 	/*
3343 	 * The next available response entry should never exceed the maximum
3344 	 * entries.  If it does, treat it as an adapter hardware error.
3345 	 */
3346 	portRspMax = pring->sli.sli3.numRiocb;
3347 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3348 	if (unlikely(portRspPut >= portRspMax)) {
3349 		lpfc_sli_rsp_pointers_error(phba, pring);
3350 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3351 		return 1;
3352 	}
3353 	if (phba->fcp_ring_in_use) {
3354 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3355 		return 1;
3356 	} else
3357 		phba->fcp_ring_in_use = 1;
3358 
3359 	rmb();
3360 	while (pring->sli.sli3.rspidx != portRspPut) {
3361 		/*
3362 		 * Fetch an entry off the ring and copy it into a local data
3363 		 * structure.  The copy involves a byte-swap since the
3364 		 * network byte order and pci byte orders are different.
3365 		 */
3366 		entry = lpfc_resp_iocb(phba, pring);
3367 		phba->last_completion_time = jiffies;
3368 
3369 		if (++pring->sli.sli3.rspidx >= portRspMax)
3370 			pring->sli.sli3.rspidx = 0;
3371 
3372 		lpfc_sli_pcimem_bcopy((uint32_t *) entry,
3373 				      (uint32_t *) &rspiocbq.iocb,
3374 				      phba->iocb_rsp_size);
3375 		INIT_LIST_HEAD(&(rspiocbq.list));
3376 		irsp = &rspiocbq.iocb;
3377 
3378 		type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
3379 		pring->stats.iocb_rsp++;
3380 		rsp_cmpl++;
3381 
3382 		if (unlikely(irsp->ulpStatus)) {
3383 			/*
3384 			 * If resource errors reported from HBA, reduce
3385 			 * queuedepths of the SCSI device.
3386 			 */
3387 			if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3388 			    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3389 			     IOERR_NO_RESOURCES)) {
3390 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3391 				phba->lpfc_rampdown_queue_depth(phba);
3392 				spin_lock_irqsave(&phba->hbalock, iflag);
3393 			}
3394 
3395 			/* Rsp ring <ringno> error: IOCB */
3396 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3397 					"0336 Rsp Ring %d error: IOCB Data: "
3398 					"x%x x%x x%x x%x x%x x%x x%x x%x\n",
3399 					pring->ringno,
3400 					irsp->un.ulpWord[0],
3401 					irsp->un.ulpWord[1],
3402 					irsp->un.ulpWord[2],
3403 					irsp->un.ulpWord[3],
3404 					irsp->un.ulpWord[4],
3405 					irsp->un.ulpWord[5],
3406 					*(uint32_t *)&irsp->un1,
3407 					*((uint32_t *)&irsp->un1 + 1));
3408 		}
3409 
3410 		switch (type) {
3411 		case LPFC_ABORT_IOCB:
3412 		case LPFC_SOL_IOCB:
3413 			/*
3414 			 * Idle exchange closed via ABTS from port.  No iocb
3415 			 * resources need to be recovered.
3416 			 */
3417 			if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
3418 				lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3419 						"0333 IOCB cmd 0x%x"
3420 						" processed. Skipping"
3421 						" completion\n",
3422 						irsp->ulpCommand);
3423 				break;
3424 			}
3425 
3426 			cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
3427 							 &rspiocbq);
3428 			if (unlikely(!cmdiocbq))
3429 				break;
3430 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
3431 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
3432 			if (cmdiocbq->iocb_cmpl) {
3433 				spin_unlock_irqrestore(&phba->hbalock, iflag);
3434 				(cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
3435 						      &rspiocbq);
3436 				spin_lock_irqsave(&phba->hbalock, iflag);
3437 			}
3438 			break;
3439 		case LPFC_UNSOL_IOCB:
3440 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3441 			lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
3442 			spin_lock_irqsave(&phba->hbalock, iflag);
3443 			break;
3444 		default:
3445 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3446 				char adaptermsg[LPFC_MAX_ADPTMSG];
3447 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3448 				memcpy(&adaptermsg[0], (uint8_t *) irsp,
3449 				       MAX_MSG_DATA);
3450 				dev_warn(&((phba->pcidev)->dev),
3451 					 "lpfc%d: %s\n",
3452 					 phba->brd_no, adaptermsg);
3453 			} else {
3454 				/* Unknown IOCB command */
3455 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3456 						"0334 Unknown IOCB command "
3457 						"Data: x%x, x%x x%x x%x x%x\n",
3458 						type, irsp->ulpCommand,
3459 						irsp->ulpStatus,
3460 						irsp->ulpIoTag,
3461 						irsp->ulpContext);
3462 			}
3463 			break;
3464 		}
3465 
3466 		/*
3467 		 * The response IOCB has been processed.  Update the ring
3468 		 * pointer in SLIM.  If the port response put pointer has not
3469 		 * been updated, sync the pgp->rspPutInx and fetch the new port
3470 		 * response put pointer.
3471 		 */
3472 		writel(pring->sli.sli3.rspidx,
3473 			&phba->host_gp[pring->ringno].rspGetInx);
3474 
3475 		if (pring->sli.sli3.rspidx == portRspPut)
3476 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3477 	}
3478 
3479 	if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
3480 		pring->stats.iocb_rsp_full++;
3481 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3482 		writel(status, phba->CAregaddr);
3483 		readl(phba->CAregaddr);
3484 	}
3485 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3486 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3487 		pring->stats.iocb_cmd_empty++;
3488 
3489 		/* Force update of the local copy of cmdGetInx */
3490 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3491 		lpfc_sli_resume_iocb(phba, pring);
3492 
3493 		if ((pring->lpfc_sli_cmd_available))
3494 			(pring->lpfc_sli_cmd_available) (phba, pring);
3495 
3496 	}
3497 
3498 	phba->fcp_ring_in_use = 0;
3499 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3500 	return rc;
3501 }
3502 
3503 /**
3504  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
3505  * @phba: Pointer to HBA context object.
3506  * @pring: Pointer to driver SLI ring object.
3507  * @rspiocbp: Pointer to driver response IOCB object.
3508  *
3509  * This function is called from the worker thread when there is a slow-path
3510  * response IOCB to process. This function chains all the response iocbs until
3511  * seeing the iocb with the LE bit set. The function will call
3512  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
3513  * completion of a command iocb. The function will call the
3514  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
3515  * The function frees the resources or calls the completion handler if this
3516  * iocb is an abort completion. The function returns NULL when the response
3517  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
3518  * this function shall chain the iocb on to the iocb_continueq and return the
3519  * response iocb passed in.
3520  **/
3521 static struct lpfc_iocbq *
3522 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3523 			struct lpfc_iocbq *rspiocbp)
3524 {
3525 	struct lpfc_iocbq *saveq;
3526 	struct lpfc_iocbq *cmdiocbp;
3527 	struct lpfc_iocbq *next_iocb;
3528 	IOCB_t *irsp = NULL;
3529 	uint32_t free_saveq;
3530 	uint8_t iocb_cmd_type;
3531 	lpfc_iocb_type type;
3532 	unsigned long iflag;
3533 	int rc;
3534 
3535 	spin_lock_irqsave(&phba->hbalock, iflag);
3536 	/* First add the response iocb to the countinueq list */
3537 	list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
3538 	pring->iocb_continueq_cnt++;
3539 
3540 	/* Now, determine whether the list is completed for processing */
3541 	irsp = &rspiocbp->iocb;
3542 	if (irsp->ulpLe) {
3543 		/*
3544 		 * By default, the driver expects to free all resources
3545 		 * associated with this iocb completion.
3546 		 */
3547 		free_saveq = 1;
3548 		saveq = list_get_first(&pring->iocb_continueq,
3549 				       struct lpfc_iocbq, list);
3550 		irsp = &(saveq->iocb);
3551 		list_del_init(&pring->iocb_continueq);
3552 		pring->iocb_continueq_cnt = 0;
3553 
3554 		pring->stats.iocb_rsp++;
3555 
3556 		/*
3557 		 * If resource errors reported from HBA, reduce
3558 		 * queuedepths of the SCSI device.
3559 		 */
3560 		if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3561 		    ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3562 		     IOERR_NO_RESOURCES)) {
3563 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3564 			phba->lpfc_rampdown_queue_depth(phba);
3565 			spin_lock_irqsave(&phba->hbalock, iflag);
3566 		}
3567 
3568 		if (irsp->ulpStatus) {
3569 			/* Rsp ring <ringno> error: IOCB */
3570 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3571 					"0328 Rsp Ring %d error: "
3572 					"IOCB Data: "
3573 					"x%x x%x x%x x%x "
3574 					"x%x x%x x%x x%x "
3575 					"x%x x%x x%x x%x "
3576 					"x%x x%x x%x x%x\n",
3577 					pring->ringno,
3578 					irsp->un.ulpWord[0],
3579 					irsp->un.ulpWord[1],
3580 					irsp->un.ulpWord[2],
3581 					irsp->un.ulpWord[3],
3582 					irsp->un.ulpWord[4],
3583 					irsp->un.ulpWord[5],
3584 					*(((uint32_t *) irsp) + 6),
3585 					*(((uint32_t *) irsp) + 7),
3586 					*(((uint32_t *) irsp) + 8),
3587 					*(((uint32_t *) irsp) + 9),
3588 					*(((uint32_t *) irsp) + 10),
3589 					*(((uint32_t *) irsp) + 11),
3590 					*(((uint32_t *) irsp) + 12),
3591 					*(((uint32_t *) irsp) + 13),
3592 					*(((uint32_t *) irsp) + 14),
3593 					*(((uint32_t *) irsp) + 15));
3594 		}
3595 
3596 		/*
3597 		 * Fetch the IOCB command type and call the correct completion
3598 		 * routine. Solicited and Unsolicited IOCBs on the ELS ring
3599 		 * get freed back to the lpfc_iocb_list by the discovery
3600 		 * kernel thread.
3601 		 */
3602 		iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
3603 		type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
3604 		switch (type) {
3605 		case LPFC_SOL_IOCB:
3606 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3607 			rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
3608 			spin_lock_irqsave(&phba->hbalock, iflag);
3609 			break;
3610 
3611 		case LPFC_UNSOL_IOCB:
3612 			spin_unlock_irqrestore(&phba->hbalock, iflag);
3613 			rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
3614 			spin_lock_irqsave(&phba->hbalock, iflag);
3615 			if (!rc)
3616 				free_saveq = 0;
3617 			break;
3618 
3619 		case LPFC_ABORT_IOCB:
3620 			cmdiocbp = NULL;
3621 			if (irsp->ulpCommand != CMD_XRI_ABORTED_CX)
3622 				cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
3623 								 saveq);
3624 			if (cmdiocbp) {
3625 				/* Call the specified completion routine */
3626 				if (cmdiocbp->iocb_cmpl) {
3627 					spin_unlock_irqrestore(&phba->hbalock,
3628 							       iflag);
3629 					(cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
3630 							      saveq);
3631 					spin_lock_irqsave(&phba->hbalock,
3632 							  iflag);
3633 				} else
3634 					__lpfc_sli_release_iocbq(phba,
3635 								 cmdiocbp);
3636 			}
3637 			break;
3638 
3639 		case LPFC_UNKNOWN_IOCB:
3640 			if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3641 				char adaptermsg[LPFC_MAX_ADPTMSG];
3642 				memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3643 				memcpy(&adaptermsg[0], (uint8_t *)irsp,
3644 				       MAX_MSG_DATA);
3645 				dev_warn(&((phba->pcidev)->dev),
3646 					 "lpfc%d: %s\n",
3647 					 phba->brd_no, adaptermsg);
3648 			} else {
3649 				/* Unknown IOCB command */
3650 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3651 						"0335 Unknown IOCB "
3652 						"command Data: x%x "
3653 						"x%x x%x x%x\n",
3654 						irsp->ulpCommand,
3655 						irsp->ulpStatus,
3656 						irsp->ulpIoTag,
3657 						irsp->ulpContext);
3658 			}
3659 			break;
3660 		}
3661 
3662 		if (free_saveq) {
3663 			list_for_each_entry_safe(rspiocbp, next_iocb,
3664 						 &saveq->list, list) {
3665 				list_del_init(&rspiocbp->list);
3666 				__lpfc_sli_release_iocbq(phba, rspiocbp);
3667 			}
3668 			__lpfc_sli_release_iocbq(phba, saveq);
3669 		}
3670 		rspiocbp = NULL;
3671 	}
3672 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3673 	return rspiocbp;
3674 }
3675 
3676 /**
3677  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
3678  * @phba: Pointer to HBA context object.
3679  * @pring: Pointer to driver SLI ring object.
3680  * @mask: Host attention register mask for this ring.
3681  *
3682  * This routine wraps the actual slow_ring event process routine from the
3683  * API jump table function pointer from the lpfc_hba struct.
3684  **/
3685 void
3686 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
3687 				struct lpfc_sli_ring *pring, uint32_t mask)
3688 {
3689 	phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
3690 }
3691 
3692 /**
3693  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
3694  * @phba: Pointer to HBA context object.
3695  * @pring: Pointer to driver SLI ring object.
3696  * @mask: Host attention register mask for this ring.
3697  *
3698  * This function is called from the worker thread when there is a ring event
3699  * for non-fcp rings. The caller does not hold any lock. The function will
3700  * remove each response iocb in the response ring and calls the handle
3701  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3702  **/
3703 static void
3704 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
3705 				   struct lpfc_sli_ring *pring, uint32_t mask)
3706 {
3707 	struct lpfc_pgp *pgp;
3708 	IOCB_t *entry;
3709 	IOCB_t *irsp = NULL;
3710 	struct lpfc_iocbq *rspiocbp = NULL;
3711 	uint32_t portRspPut, portRspMax;
3712 	unsigned long iflag;
3713 	uint32_t status;
3714 
3715 	pgp = &phba->port_gp[pring->ringno];
3716 	spin_lock_irqsave(&phba->hbalock, iflag);
3717 	pring->stats.iocb_event++;
3718 
3719 	/*
3720 	 * The next available response entry should never exceed the maximum
3721 	 * entries.  If it does, treat it as an adapter hardware error.
3722 	 */
3723 	portRspMax = pring->sli.sli3.numRiocb;
3724 	portRspPut = le32_to_cpu(pgp->rspPutInx);
3725 	if (portRspPut >= portRspMax) {
3726 		/*
3727 		 * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3728 		 * rsp ring <portRspMax>
3729 		 */
3730 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3731 				"0303 Ring %d handler: portRspPut %d "
3732 				"is bigger than rsp ring %d\n",
3733 				pring->ringno, portRspPut, portRspMax);
3734 
3735 		phba->link_state = LPFC_HBA_ERROR;
3736 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3737 
3738 		phba->work_hs = HS_FFER3;
3739 		lpfc_handle_eratt(phba);
3740 
3741 		return;
3742 	}
3743 
3744 	rmb();
3745 	while (pring->sli.sli3.rspidx != portRspPut) {
3746 		/*
3747 		 * Build a completion list and call the appropriate handler.
3748 		 * The process is to get the next available response iocb, get
3749 		 * a free iocb from the list, copy the response data into the
3750 		 * free iocb, insert to the continuation list, and update the
3751 		 * next response index to slim.  This process makes response
3752 		 * iocb's in the ring available to DMA as fast as possible but
3753 		 * pays a penalty for a copy operation.  Since the iocb is
3754 		 * only 32 bytes, this penalty is considered small relative to
3755 		 * the PCI reads for register values and a slim write.  When
3756 		 * the ulpLe field is set, the entire Command has been
3757 		 * received.
3758 		 */
3759 		entry = lpfc_resp_iocb(phba, pring);
3760 
3761 		phba->last_completion_time = jiffies;
3762 		rspiocbp = __lpfc_sli_get_iocbq(phba);
3763 		if (rspiocbp == NULL) {
3764 			printk(KERN_ERR "%s: out of buffers! Failing "
3765 			       "completion.\n", __func__);
3766 			break;
3767 		}
3768 
3769 		lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
3770 				      phba->iocb_rsp_size);
3771 		irsp = &rspiocbp->iocb;
3772 
3773 		if (++pring->sli.sli3.rspidx >= portRspMax)
3774 			pring->sli.sli3.rspidx = 0;
3775 
3776 		if (pring->ringno == LPFC_ELS_RING) {
3777 			lpfc_debugfs_slow_ring_trc(phba,
3778 			"IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
3779 				*(((uint32_t *) irsp) + 4),
3780 				*(((uint32_t *) irsp) + 6),
3781 				*(((uint32_t *) irsp) + 7));
3782 		}
3783 
3784 		writel(pring->sli.sli3.rspidx,
3785 			&phba->host_gp[pring->ringno].rspGetInx);
3786 
3787 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3788 		/* Handle the response IOCB */
3789 		rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
3790 		spin_lock_irqsave(&phba->hbalock, iflag);
3791 
3792 		/*
3793 		 * If the port response put pointer has not been updated, sync
3794 		 * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
3795 		 * response put pointer.
3796 		 */
3797 		if (pring->sli.sli3.rspidx == portRspPut) {
3798 			portRspPut = le32_to_cpu(pgp->rspPutInx);
3799 		}
3800 	} /* while (pring->sli.sli3.rspidx != portRspPut) */
3801 
3802 	if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
3803 		/* At least one response entry has been freed */
3804 		pring->stats.iocb_rsp_full++;
3805 		/* SET RxRE_RSP in Chip Att register */
3806 		status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3807 		writel(status, phba->CAregaddr);
3808 		readl(phba->CAregaddr); /* flush */
3809 	}
3810 	if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3811 		pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3812 		pring->stats.iocb_cmd_empty++;
3813 
3814 		/* Force update of the local copy of cmdGetInx */
3815 		pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3816 		lpfc_sli_resume_iocb(phba, pring);
3817 
3818 		if ((pring->lpfc_sli_cmd_available))
3819 			(pring->lpfc_sli_cmd_available) (phba, pring);
3820 
3821 	}
3822 
3823 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3824 	return;
3825 }
3826 
3827 /**
3828  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
3829  * @phba: Pointer to HBA context object.
3830  * @pring: Pointer to driver SLI ring object.
3831  * @mask: Host attention register mask for this ring.
3832  *
3833  * This function is called from the worker thread when there is a pending
3834  * ELS response iocb on the driver internal slow-path response iocb worker
3835  * queue. The caller does not hold any lock. The function will remove each
3836  * response iocb from the response worker queue and calls the handle
3837  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3838  **/
3839 static void
3840 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
3841 				   struct lpfc_sli_ring *pring, uint32_t mask)
3842 {
3843 	struct lpfc_iocbq *irspiocbq;
3844 	struct hbq_dmabuf *dmabuf;
3845 	struct lpfc_cq_event *cq_event;
3846 	unsigned long iflag;
3847 	int count = 0;
3848 
3849 	spin_lock_irqsave(&phba->hbalock, iflag);
3850 	phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
3851 	spin_unlock_irqrestore(&phba->hbalock, iflag);
3852 	while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
3853 		/* Get the response iocb from the head of work queue */
3854 		spin_lock_irqsave(&phba->hbalock, iflag);
3855 		list_remove_head(&phba->sli4_hba.sp_queue_event,
3856 				 cq_event, struct lpfc_cq_event, list);
3857 		spin_unlock_irqrestore(&phba->hbalock, iflag);
3858 
3859 		switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
3860 		case CQE_CODE_COMPL_WQE:
3861 			irspiocbq = container_of(cq_event, struct lpfc_iocbq,
3862 						 cq_event);
3863 			/* Translate ELS WCQE to response IOCBQ */
3864 			irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
3865 								   irspiocbq);
3866 			if (irspiocbq)
3867 				lpfc_sli_sp_handle_rspiocb(phba, pring,
3868 							   irspiocbq);
3869 			count++;
3870 			break;
3871 		case CQE_CODE_RECEIVE:
3872 		case CQE_CODE_RECEIVE_V1:
3873 			dmabuf = container_of(cq_event, struct hbq_dmabuf,
3874 					      cq_event);
3875 			lpfc_sli4_handle_received_buffer(phba, dmabuf);
3876 			count++;
3877 			break;
3878 		default:
3879 			break;
3880 		}
3881 
3882 		/* Limit the number of events to 64 to avoid soft lockups */
3883 		if (count == 64)
3884 			break;
3885 	}
3886 }
3887 
3888 /**
3889  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
3890  * @phba: Pointer to HBA context object.
3891  * @pring: Pointer to driver SLI ring object.
3892  *
3893  * This function aborts all iocbs in the given ring and frees all the iocb
3894  * objects in txq. This function issues an abort iocb for all the iocb commands
3895  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3896  * the return of this function. The caller is not required to hold any locks.
3897  **/
3898 void
3899 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3900 {
3901 	LIST_HEAD(completions);
3902 	struct lpfc_iocbq *iocb, *next_iocb;
3903 
3904 	if (pring->ringno == LPFC_ELS_RING) {
3905 		lpfc_fabric_abort_hba(phba);
3906 	}
3907 
3908 	/* Error everything on txq and txcmplq
3909 	 * First do the txq.
3910 	 */
3911 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3912 		spin_lock_irq(&pring->ring_lock);
3913 		list_splice_init(&pring->txq, &completions);
3914 		pring->txq_cnt = 0;
3915 		spin_unlock_irq(&pring->ring_lock);
3916 
3917 		spin_lock_irq(&phba->hbalock);
3918 		/* Next issue ABTS for everything on the txcmplq */
3919 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3920 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3921 		spin_unlock_irq(&phba->hbalock);
3922 	} else {
3923 		spin_lock_irq(&phba->hbalock);
3924 		list_splice_init(&pring->txq, &completions);
3925 		pring->txq_cnt = 0;
3926 
3927 		/* Next issue ABTS for everything on the txcmplq */
3928 		list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3929 			lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3930 		spin_unlock_irq(&phba->hbalock);
3931 	}
3932 
3933 	/* Cancel all the IOCBs from the completions list */
3934 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
3935 			      IOERR_SLI_ABORTED);
3936 }
3937 
3938 /**
3939  * lpfc_sli_abort_wqe_ring - Abort all iocbs in the ring
3940  * @phba: Pointer to HBA context object.
3941  * @pring: Pointer to driver SLI ring object.
3942  *
3943  * This function aborts all iocbs in the given ring and frees all the iocb
3944  * objects in txq. This function issues an abort iocb for all the iocb commands
3945  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3946  * the return of this function. The caller is not required to hold any locks.
3947  **/
3948 void
3949 lpfc_sli_abort_wqe_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3950 {
3951 	LIST_HEAD(completions);
3952 	struct lpfc_iocbq *iocb, *next_iocb;
3953 
3954 	if (pring->ringno == LPFC_ELS_RING)
3955 		lpfc_fabric_abort_hba(phba);
3956 
3957 	spin_lock_irq(&phba->hbalock);
3958 	/* Next issue ABTS for everything on the txcmplq */
3959 	list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3960 		lpfc_sli4_abort_nvme_io(phba, pring, iocb);
3961 	spin_unlock_irq(&phba->hbalock);
3962 }
3963 
3964 
3965 /**
3966  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
3967  * @phba: Pointer to HBA context object.
3968  * @pring: Pointer to driver SLI ring object.
3969  *
3970  * This function aborts all iocbs in FCP rings and frees all the iocb
3971  * objects in txq. This function issues an abort iocb for all the iocb commands
3972  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3973  * the return of this function. The caller is not required to hold any locks.
3974  **/
3975 void
3976 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
3977 {
3978 	struct lpfc_sli *psli = &phba->sli;
3979 	struct lpfc_sli_ring  *pring;
3980 	uint32_t i;
3981 
3982 	/* Look on all the FCP Rings for the iotag */
3983 	if (phba->sli_rev >= LPFC_SLI_REV4) {
3984 		for (i = 0; i < phba->cfg_fcp_io_channel; i++) {
3985 			pring = phba->sli4_hba.fcp_wq[i]->pring;
3986 			lpfc_sli_abort_iocb_ring(phba, pring);
3987 		}
3988 	} else {
3989 		pring = &psli->sli3_ring[LPFC_FCP_RING];
3990 		lpfc_sli_abort_iocb_ring(phba, pring);
3991 	}
3992 }
3993 
3994 /**
3995  * lpfc_sli_abort_nvme_rings - Abort all wqes in all NVME rings
3996  * @phba: Pointer to HBA context object.
3997  *
3998  * This function aborts all wqes in NVME rings. This function issues an
3999  * abort wqe for all the outstanding IO commands in txcmplq. The iocbs in
4000  * the txcmplq is not guaranteed to complete before the return of this
4001  * function. The caller is not required to hold any locks.
4002  **/
4003 void
4004 lpfc_sli_abort_nvme_rings(struct lpfc_hba *phba)
4005 {
4006 	struct lpfc_sli_ring  *pring;
4007 	uint32_t i;
4008 
4009 	if (phba->sli_rev < LPFC_SLI_REV4)
4010 		return;
4011 
4012 	/* Abort all IO on each NVME ring. */
4013 	for (i = 0; i < phba->cfg_nvme_io_channel; i++) {
4014 		pring = phba->sli4_hba.nvme_wq[i]->pring;
4015 		lpfc_sli_abort_wqe_ring(phba, pring);
4016 	}
4017 }
4018 
4019 
4020 /**
4021  * lpfc_sli_flush_fcp_rings - flush all iocbs in the fcp ring
4022  * @phba: Pointer to HBA context object.
4023  *
4024  * This function flushes all iocbs in the fcp ring and frees all the iocb
4025  * objects in txq and txcmplq. This function will not issue abort iocbs
4026  * for all the iocb commands in txcmplq, they will just be returned with
4027  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4028  * slot has been permanently disabled.
4029  **/
4030 void
4031 lpfc_sli_flush_fcp_rings(struct lpfc_hba *phba)
4032 {
4033 	LIST_HEAD(txq);
4034 	LIST_HEAD(txcmplq);
4035 	struct lpfc_sli *psli = &phba->sli;
4036 	struct lpfc_sli_ring  *pring;
4037 	uint32_t i;
4038 	struct lpfc_iocbq *piocb, *next_iocb;
4039 
4040 	spin_lock_irq(&phba->hbalock);
4041 	/* Indicate the I/O queues are flushed */
4042 	phba->hba_flag |= HBA_FCP_IOQ_FLUSH;
4043 	spin_unlock_irq(&phba->hbalock);
4044 
4045 	/* Look on all the FCP Rings for the iotag */
4046 	if (phba->sli_rev >= LPFC_SLI_REV4) {
4047 		for (i = 0; i < phba->cfg_fcp_io_channel; i++) {
4048 			pring = phba->sli4_hba.fcp_wq[i]->pring;
4049 
4050 			spin_lock_irq(&pring->ring_lock);
4051 			/* Retrieve everything on txq */
4052 			list_splice_init(&pring->txq, &txq);
4053 			list_for_each_entry_safe(piocb, next_iocb,
4054 						 &pring->txcmplq, list)
4055 				piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4056 			/* Retrieve everything on the txcmplq */
4057 			list_splice_init(&pring->txcmplq, &txcmplq);
4058 			pring->txq_cnt = 0;
4059 			pring->txcmplq_cnt = 0;
4060 			spin_unlock_irq(&pring->ring_lock);
4061 
4062 			/* Flush the txq */
4063 			lpfc_sli_cancel_iocbs(phba, &txq,
4064 					      IOSTAT_LOCAL_REJECT,
4065 					      IOERR_SLI_DOWN);
4066 			/* Flush the txcmpq */
4067 			lpfc_sli_cancel_iocbs(phba, &txcmplq,
4068 					      IOSTAT_LOCAL_REJECT,
4069 					      IOERR_SLI_DOWN);
4070 		}
4071 	} else {
4072 		pring = &psli->sli3_ring[LPFC_FCP_RING];
4073 
4074 		spin_lock_irq(&phba->hbalock);
4075 		/* Retrieve everything on txq */
4076 		list_splice_init(&pring->txq, &txq);
4077 		list_for_each_entry_safe(piocb, next_iocb,
4078 					 &pring->txcmplq, list)
4079 			piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4080 		/* Retrieve everything on the txcmplq */
4081 		list_splice_init(&pring->txcmplq, &txcmplq);
4082 		pring->txq_cnt = 0;
4083 		pring->txcmplq_cnt = 0;
4084 		spin_unlock_irq(&phba->hbalock);
4085 
4086 		/* Flush the txq */
4087 		lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4088 				      IOERR_SLI_DOWN);
4089 		/* Flush the txcmpq */
4090 		lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4091 				      IOERR_SLI_DOWN);
4092 	}
4093 }
4094 
4095 /**
4096  * lpfc_sli_flush_nvme_rings - flush all wqes in the nvme rings
4097  * @phba: Pointer to HBA context object.
4098  *
4099  * This function flushes all wqes in the nvme rings and frees all resources
4100  * in the txcmplq. This function does not issue abort wqes for the IO
4101  * commands in txcmplq, they will just be returned with
4102  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4103  * slot has been permanently disabled.
4104  **/
4105 void
4106 lpfc_sli_flush_nvme_rings(struct lpfc_hba *phba)
4107 {
4108 	LIST_HEAD(txcmplq);
4109 	struct lpfc_sli_ring  *pring;
4110 	uint32_t i;
4111 	struct lpfc_iocbq *piocb, *next_iocb;
4112 
4113 	if (phba->sli_rev < LPFC_SLI_REV4)
4114 		return;
4115 
4116 	/* Hint to other driver operations that a flush is in progress. */
4117 	spin_lock_irq(&phba->hbalock);
4118 	phba->hba_flag |= HBA_NVME_IOQ_FLUSH;
4119 	spin_unlock_irq(&phba->hbalock);
4120 
4121 	/* Cycle through all NVME rings and complete each IO with
4122 	 * a local driver reason code.  This is a flush so no
4123 	 * abort exchange to FW.
4124 	 */
4125 	for (i = 0; i < phba->cfg_nvme_io_channel; i++) {
4126 		pring = phba->sli4_hba.nvme_wq[i]->pring;
4127 
4128 		spin_lock_irq(&pring->ring_lock);
4129 		list_for_each_entry_safe(piocb, next_iocb,
4130 					 &pring->txcmplq, list)
4131 			piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4132 		/* Retrieve everything on the txcmplq */
4133 		list_splice_init(&pring->txcmplq, &txcmplq);
4134 		pring->txcmplq_cnt = 0;
4135 		spin_unlock_irq(&pring->ring_lock);
4136 
4137 		/* Flush the txcmpq &&&PAE */
4138 		lpfc_sli_cancel_iocbs(phba, &txcmplq,
4139 				      IOSTAT_LOCAL_REJECT,
4140 				      IOERR_SLI_DOWN);
4141 	}
4142 }
4143 
4144 /**
4145  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4146  * @phba: Pointer to HBA context object.
4147  * @mask: Bit mask to be checked.
4148  *
4149  * This function reads the host status register and compares
4150  * with the provided bit mask to check if HBA completed
4151  * the restart. This function will wait in a loop for the
4152  * HBA to complete restart. If the HBA does not restart within
4153  * 15 iterations, the function will reset the HBA again. The
4154  * function returns 1 when HBA fail to restart otherwise returns
4155  * zero.
4156  **/
4157 static int
4158 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4159 {
4160 	uint32_t status;
4161 	int i = 0;
4162 	int retval = 0;
4163 
4164 	/* Read the HBA Host Status Register */
4165 	if (lpfc_readl(phba->HSregaddr, &status))
4166 		return 1;
4167 
4168 	/*
4169 	 * Check status register every 100ms for 5 retries, then every
4170 	 * 500ms for 5, then every 2.5 sec for 5, then reset board and
4171 	 * every 2.5 sec for 4.
4172 	 * Break our of the loop if errors occurred during init.
4173 	 */
4174 	while (((status & mask) != mask) &&
4175 	       !(status & HS_FFERM) &&
4176 	       i++ < 20) {
4177 
4178 		if (i <= 5)
4179 			msleep(10);
4180 		else if (i <= 10)
4181 			msleep(500);
4182 		else
4183 			msleep(2500);
4184 
4185 		if (i == 15) {
4186 				/* Do post */
4187 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4188 			lpfc_sli_brdrestart(phba);
4189 		}
4190 		/* Read the HBA Host Status Register */
4191 		if (lpfc_readl(phba->HSregaddr, &status)) {
4192 			retval = 1;
4193 			break;
4194 		}
4195 	}
4196 
4197 	/* Check to see if any errors occurred during init */
4198 	if ((status & HS_FFERM) || (i >= 20)) {
4199 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4200 				"2751 Adapter failed to restart, "
4201 				"status reg x%x, FW Data: A8 x%x AC x%x\n",
4202 				status,
4203 				readl(phba->MBslimaddr + 0xa8),
4204 				readl(phba->MBslimaddr + 0xac));
4205 		phba->link_state = LPFC_HBA_ERROR;
4206 		retval = 1;
4207 	}
4208 
4209 	return retval;
4210 }
4211 
4212 /**
4213  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4214  * @phba: Pointer to HBA context object.
4215  * @mask: Bit mask to be checked.
4216  *
4217  * This function checks the host status register to check if HBA is
4218  * ready. This function will wait in a loop for the HBA to be ready
4219  * If the HBA is not ready , the function will will reset the HBA PCI
4220  * function again. The function returns 1 when HBA fail to be ready
4221  * otherwise returns zero.
4222  **/
4223 static int
4224 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4225 {
4226 	uint32_t status;
4227 	int retval = 0;
4228 
4229 	/* Read the HBA Host Status Register */
4230 	status = lpfc_sli4_post_status_check(phba);
4231 
4232 	if (status) {
4233 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4234 		lpfc_sli_brdrestart(phba);
4235 		status = lpfc_sli4_post_status_check(phba);
4236 	}
4237 
4238 	/* Check to see if any errors occurred during init */
4239 	if (status) {
4240 		phba->link_state = LPFC_HBA_ERROR;
4241 		retval = 1;
4242 	} else
4243 		phba->sli4_hba.intr_enable = 0;
4244 
4245 	return retval;
4246 }
4247 
4248 /**
4249  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4250  * @phba: Pointer to HBA context object.
4251  * @mask: Bit mask to be checked.
4252  *
4253  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4254  * from the API jump table function pointer from the lpfc_hba struct.
4255  **/
4256 int
4257 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4258 {
4259 	return phba->lpfc_sli_brdready(phba, mask);
4260 }
4261 
4262 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4263 
4264 /**
4265  * lpfc_reset_barrier - Make HBA ready for HBA reset
4266  * @phba: Pointer to HBA context object.
4267  *
4268  * This function is called before resetting an HBA. This function is called
4269  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4270  **/
4271 void lpfc_reset_barrier(struct lpfc_hba *phba)
4272 {
4273 	uint32_t __iomem *resp_buf;
4274 	uint32_t __iomem *mbox_buf;
4275 	volatile uint32_t mbox;
4276 	uint32_t hc_copy, ha_copy, resp_data;
4277 	int  i;
4278 	uint8_t hdrtype;
4279 
4280 	lockdep_assert_held(&phba->hbalock);
4281 
4282 	pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4283 	if (hdrtype != 0x80 ||
4284 	    (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4285 	     FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4286 		return;
4287 
4288 	/*
4289 	 * Tell the other part of the chip to suspend temporarily all
4290 	 * its DMA activity.
4291 	 */
4292 	resp_buf = phba->MBslimaddr;
4293 
4294 	/* Disable the error attention */
4295 	if (lpfc_readl(phba->HCregaddr, &hc_copy))
4296 		return;
4297 	writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4298 	readl(phba->HCregaddr); /* flush */
4299 	phba->link_flag |= LS_IGNORE_ERATT;
4300 
4301 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4302 		return;
4303 	if (ha_copy & HA_ERATT) {
4304 		/* Clear Chip error bit */
4305 		writel(HA_ERATT, phba->HAregaddr);
4306 		phba->pport->stopped = 1;
4307 	}
4308 
4309 	mbox = 0;
4310 	((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
4311 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
4312 
4313 	writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4314 	mbox_buf = phba->MBslimaddr;
4315 	writel(mbox, mbox_buf);
4316 
4317 	for (i = 0; i < 50; i++) {
4318 		if (lpfc_readl((resp_buf + 1), &resp_data))
4319 			return;
4320 		if (resp_data != ~(BARRIER_TEST_PATTERN))
4321 			mdelay(1);
4322 		else
4323 			break;
4324 	}
4325 	resp_data = 0;
4326 	if (lpfc_readl((resp_buf + 1), &resp_data))
4327 		return;
4328 	if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4329 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4330 		    phba->pport->stopped)
4331 			goto restore_hc;
4332 		else
4333 			goto clear_errat;
4334 	}
4335 
4336 	((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
4337 	resp_data = 0;
4338 	for (i = 0; i < 500; i++) {
4339 		if (lpfc_readl(resp_buf, &resp_data))
4340 			return;
4341 		if (resp_data != mbox)
4342 			mdelay(1);
4343 		else
4344 			break;
4345 	}
4346 
4347 clear_errat:
4348 
4349 	while (++i < 500) {
4350 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4351 			return;
4352 		if (!(ha_copy & HA_ERATT))
4353 			mdelay(1);
4354 		else
4355 			break;
4356 	}
4357 
4358 	if (readl(phba->HAregaddr) & HA_ERATT) {
4359 		writel(HA_ERATT, phba->HAregaddr);
4360 		phba->pport->stopped = 1;
4361 	}
4362 
4363 restore_hc:
4364 	phba->link_flag &= ~LS_IGNORE_ERATT;
4365 	writel(hc_copy, phba->HCregaddr);
4366 	readl(phba->HCregaddr); /* flush */
4367 }
4368 
4369 /**
4370  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4371  * @phba: Pointer to HBA context object.
4372  *
4373  * This function issues a kill_board mailbox command and waits for
4374  * the error attention interrupt. This function is called for stopping
4375  * the firmware processing. The caller is not required to hold any
4376  * locks. This function calls lpfc_hba_down_post function to free
4377  * any pending commands after the kill. The function will return 1 when it
4378  * fails to kill the board else will return 0.
4379  **/
4380 int
4381 lpfc_sli_brdkill(struct lpfc_hba *phba)
4382 {
4383 	struct lpfc_sli *psli;
4384 	LPFC_MBOXQ_t *pmb;
4385 	uint32_t status;
4386 	uint32_t ha_copy;
4387 	int retval;
4388 	int i = 0;
4389 
4390 	psli = &phba->sli;
4391 
4392 	/* Kill HBA */
4393 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4394 			"0329 Kill HBA Data: x%x x%x\n",
4395 			phba->pport->port_state, psli->sli_flag);
4396 
4397 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4398 	if (!pmb)
4399 		return 1;
4400 
4401 	/* Disable the error attention */
4402 	spin_lock_irq(&phba->hbalock);
4403 	if (lpfc_readl(phba->HCregaddr, &status)) {
4404 		spin_unlock_irq(&phba->hbalock);
4405 		mempool_free(pmb, phba->mbox_mem_pool);
4406 		return 1;
4407 	}
4408 	status &= ~HC_ERINT_ENA;
4409 	writel(status, phba->HCregaddr);
4410 	readl(phba->HCregaddr); /* flush */
4411 	phba->link_flag |= LS_IGNORE_ERATT;
4412 	spin_unlock_irq(&phba->hbalock);
4413 
4414 	lpfc_kill_board(phba, pmb);
4415 	pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4416 	retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
4417 
4418 	if (retval != MBX_SUCCESS) {
4419 		if (retval != MBX_BUSY)
4420 			mempool_free(pmb, phba->mbox_mem_pool);
4421 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4422 				"2752 KILL_BOARD command failed retval %d\n",
4423 				retval);
4424 		spin_lock_irq(&phba->hbalock);
4425 		phba->link_flag &= ~LS_IGNORE_ERATT;
4426 		spin_unlock_irq(&phba->hbalock);
4427 		return 1;
4428 	}
4429 
4430 	spin_lock_irq(&phba->hbalock);
4431 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
4432 	spin_unlock_irq(&phba->hbalock);
4433 
4434 	mempool_free(pmb, phba->mbox_mem_pool);
4435 
4436 	/* There is no completion for a KILL_BOARD mbox cmd. Check for an error
4437 	 * attention every 100ms for 3 seconds. If we don't get ERATT after
4438 	 * 3 seconds we still set HBA_ERROR state because the status of the
4439 	 * board is now undefined.
4440 	 */
4441 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
4442 		return 1;
4443 	while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
4444 		mdelay(100);
4445 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
4446 			return 1;
4447 	}
4448 
4449 	del_timer_sync(&psli->mbox_tmo);
4450 	if (ha_copy & HA_ERATT) {
4451 		writel(HA_ERATT, phba->HAregaddr);
4452 		phba->pport->stopped = 1;
4453 	}
4454 	spin_lock_irq(&phba->hbalock);
4455 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4456 	psli->mbox_active = NULL;
4457 	phba->link_flag &= ~LS_IGNORE_ERATT;
4458 	spin_unlock_irq(&phba->hbalock);
4459 
4460 	lpfc_hba_down_post(phba);
4461 	phba->link_state = LPFC_HBA_ERROR;
4462 
4463 	return ha_copy & HA_ERATT ? 0 : 1;
4464 }
4465 
4466 /**
4467  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
4468  * @phba: Pointer to HBA context object.
4469  *
4470  * This function resets the HBA by writing HC_INITFF to the control
4471  * register. After the HBA resets, this function resets all the iocb ring
4472  * indices. This function disables PCI layer parity checking during
4473  * the reset.
4474  * This function returns 0 always.
4475  * The caller is not required to hold any locks.
4476  **/
4477 int
4478 lpfc_sli_brdreset(struct lpfc_hba *phba)
4479 {
4480 	struct lpfc_sli *psli;
4481 	struct lpfc_sli_ring *pring;
4482 	uint16_t cfg_value;
4483 	int i;
4484 
4485 	psli = &phba->sli;
4486 
4487 	/* Reset HBA */
4488 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4489 			"0325 Reset HBA Data: x%x x%x\n",
4490 			(phba->pport) ? phba->pport->port_state : 0,
4491 			psli->sli_flag);
4492 
4493 	/* perform board reset */
4494 	phba->fc_eventTag = 0;
4495 	phba->link_events = 0;
4496 	if (phba->pport) {
4497 		phba->pport->fc_myDID = 0;
4498 		phba->pport->fc_prevDID = 0;
4499 	}
4500 
4501 	/* Turn off parity checking and serr during the physical reset */
4502 	pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value);
4503 	pci_write_config_word(phba->pcidev, PCI_COMMAND,
4504 			      (cfg_value &
4505 			       ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4506 
4507 	psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
4508 
4509 	/* Now toggle INITFF bit in the Host Control Register */
4510 	writel(HC_INITFF, phba->HCregaddr);
4511 	mdelay(1);
4512 	readl(phba->HCregaddr); /* flush */
4513 	writel(0, phba->HCregaddr);
4514 	readl(phba->HCregaddr); /* flush */
4515 
4516 	/* Restore PCI cmd register */
4517 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4518 
4519 	/* Initialize relevant SLI info */
4520 	for (i = 0; i < psli->num_rings; i++) {
4521 		pring = &psli->sli3_ring[i];
4522 		pring->flag = 0;
4523 		pring->sli.sli3.rspidx = 0;
4524 		pring->sli.sli3.next_cmdidx  = 0;
4525 		pring->sli.sli3.local_getidx = 0;
4526 		pring->sli.sli3.cmdidx = 0;
4527 		pring->missbufcnt = 0;
4528 	}
4529 
4530 	phba->link_state = LPFC_WARM_START;
4531 	return 0;
4532 }
4533 
4534 /**
4535  * lpfc_sli4_brdreset - Reset a sli-4 HBA
4536  * @phba: Pointer to HBA context object.
4537  *
4538  * This function resets a SLI4 HBA. This function disables PCI layer parity
4539  * checking during resets the device. The caller is not required to hold
4540  * any locks.
4541  *
4542  * This function returns 0 always.
4543  **/
4544 int
4545 lpfc_sli4_brdreset(struct lpfc_hba *phba)
4546 {
4547 	struct lpfc_sli *psli = &phba->sli;
4548 	uint16_t cfg_value;
4549 	int rc = 0;
4550 
4551 	/* Reset HBA */
4552 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4553 			"0295 Reset HBA Data: x%x x%x x%x\n",
4554 			phba->pport->port_state, psli->sli_flag,
4555 			phba->hba_flag);
4556 
4557 	/* perform board reset */
4558 	phba->fc_eventTag = 0;
4559 	phba->link_events = 0;
4560 	phba->pport->fc_myDID = 0;
4561 	phba->pport->fc_prevDID = 0;
4562 
4563 	spin_lock_irq(&phba->hbalock);
4564 	psli->sli_flag &= ~(LPFC_PROCESS_LA);
4565 	phba->fcf.fcf_flag = 0;
4566 	spin_unlock_irq(&phba->hbalock);
4567 
4568 	/* SLI4 INTF 2: if FW dump is being taken skip INIT_PORT */
4569 	if (phba->hba_flag & HBA_FW_DUMP_OP) {
4570 		phba->hba_flag &= ~HBA_FW_DUMP_OP;
4571 		return rc;
4572 	}
4573 
4574 	/* Now physically reset the device */
4575 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4576 			"0389 Performing PCI function reset!\n");
4577 
4578 	/* Turn off parity checking and serr during the physical reset */
4579 	pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value);
4580 	pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
4581 			      ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4582 
4583 	/* Perform FCoE PCI function reset before freeing queue memory */
4584 	rc = lpfc_pci_function_reset(phba);
4585 
4586 	/* Restore PCI cmd register */
4587 	pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4588 
4589 	return rc;
4590 }
4591 
4592 /**
4593  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
4594  * @phba: Pointer to HBA context object.
4595  *
4596  * This function is called in the SLI initialization code path to
4597  * restart the HBA. The caller is not required to hold any lock.
4598  * This function writes MBX_RESTART mailbox command to the SLIM and
4599  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
4600  * function to free any pending commands. The function enables
4601  * POST only during the first initialization. The function returns zero.
4602  * The function does not guarantee completion of MBX_RESTART mailbox
4603  * command before the return of this function.
4604  **/
4605 static int
4606 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
4607 {
4608 	MAILBOX_t *mb;
4609 	struct lpfc_sli *psli;
4610 	volatile uint32_t word0;
4611 	void __iomem *to_slim;
4612 	uint32_t hba_aer_enabled;
4613 
4614 	spin_lock_irq(&phba->hbalock);
4615 
4616 	/* Take PCIe device Advanced Error Reporting (AER) state */
4617 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4618 
4619 	psli = &phba->sli;
4620 
4621 	/* Restart HBA */
4622 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4623 			"0337 Restart HBA Data: x%x x%x\n",
4624 			(phba->pport) ? phba->pport->port_state : 0,
4625 			psli->sli_flag);
4626 
4627 	word0 = 0;
4628 	mb = (MAILBOX_t *) &word0;
4629 	mb->mbxCommand = MBX_RESTART;
4630 	mb->mbxHc = 1;
4631 
4632 	lpfc_reset_barrier(phba);
4633 
4634 	to_slim = phba->MBslimaddr;
4635 	writel(*(uint32_t *) mb, to_slim);
4636 	readl(to_slim); /* flush */
4637 
4638 	/* Only skip post after fc_ffinit is completed */
4639 	if (phba->pport && phba->pport->port_state)
4640 		word0 = 1;	/* This is really setting up word1 */
4641 	else
4642 		word0 = 0;	/* This is really setting up word1 */
4643 	to_slim = phba->MBslimaddr + sizeof (uint32_t);
4644 	writel(*(uint32_t *) mb, to_slim);
4645 	readl(to_slim); /* flush */
4646 
4647 	lpfc_sli_brdreset(phba);
4648 	if (phba->pport)
4649 		phba->pport->stopped = 0;
4650 	phba->link_state = LPFC_INIT_START;
4651 	phba->hba_flag = 0;
4652 	spin_unlock_irq(&phba->hbalock);
4653 
4654 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4655 	psli->stats_start = ktime_get_seconds();
4656 
4657 	/* Give the INITFF and Post time to settle. */
4658 	mdelay(100);
4659 
4660 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4661 	if (hba_aer_enabled)
4662 		pci_disable_pcie_error_reporting(phba->pcidev);
4663 
4664 	lpfc_hba_down_post(phba);
4665 
4666 	return 0;
4667 }
4668 
4669 /**
4670  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
4671  * @phba: Pointer to HBA context object.
4672  *
4673  * This function is called in the SLI initialization code path to restart
4674  * a SLI4 HBA. The caller is not required to hold any lock.
4675  * At the end of the function, it calls lpfc_hba_down_post function to
4676  * free any pending commands.
4677  **/
4678 static int
4679 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
4680 {
4681 	struct lpfc_sli *psli = &phba->sli;
4682 	uint32_t hba_aer_enabled;
4683 	int rc;
4684 
4685 	/* Restart HBA */
4686 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4687 			"0296 Restart HBA Data: x%x x%x\n",
4688 			phba->pport->port_state, psli->sli_flag);
4689 
4690 	/* Take PCIe device Advanced Error Reporting (AER) state */
4691 	hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4692 
4693 	rc = lpfc_sli4_brdreset(phba);
4694 	if (rc)
4695 		return rc;
4696 
4697 	spin_lock_irq(&phba->hbalock);
4698 	phba->pport->stopped = 0;
4699 	phba->link_state = LPFC_INIT_START;
4700 	phba->hba_flag = 0;
4701 	spin_unlock_irq(&phba->hbalock);
4702 
4703 	memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4704 	psli->stats_start = ktime_get_seconds();
4705 
4706 	/* Reset HBA AER if it was enabled, note hba_flag was reset above */
4707 	if (hba_aer_enabled)
4708 		pci_disable_pcie_error_reporting(phba->pcidev);
4709 
4710 	lpfc_hba_down_post(phba);
4711 	lpfc_sli4_queue_destroy(phba);
4712 
4713 	return rc;
4714 }
4715 
4716 /**
4717  * lpfc_sli_brdrestart - Wrapper func for restarting hba
4718  * @phba: Pointer to HBA context object.
4719  *
4720  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
4721  * API jump table function pointer from the lpfc_hba struct.
4722 **/
4723 int
4724 lpfc_sli_brdrestart(struct lpfc_hba *phba)
4725 {
4726 	return phba->lpfc_sli_brdrestart(phba);
4727 }
4728 
4729 /**
4730  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
4731  * @phba: Pointer to HBA context object.
4732  *
4733  * This function is called after a HBA restart to wait for successful
4734  * restart of the HBA. Successful restart of the HBA is indicated by
4735  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
4736  * iteration, the function will restart the HBA again. The function returns
4737  * zero if HBA successfully restarted else returns negative error code.
4738  **/
4739 int
4740 lpfc_sli_chipset_init(struct lpfc_hba *phba)
4741 {
4742 	uint32_t status, i = 0;
4743 
4744 	/* Read the HBA Host Status Register */
4745 	if (lpfc_readl(phba->HSregaddr, &status))
4746 		return -EIO;
4747 
4748 	/* Check status register to see what current state is */
4749 	i = 0;
4750 	while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
4751 
4752 		/* Check every 10ms for 10 retries, then every 100ms for 90
4753 		 * retries, then every 1 sec for 50 retires for a total of
4754 		 * ~60 seconds before reset the board again and check every
4755 		 * 1 sec for 50 retries. The up to 60 seconds before the
4756 		 * board ready is required by the Falcon FIPS zeroization
4757 		 * complete, and any reset the board in between shall cause
4758 		 * restart of zeroization, further delay the board ready.
4759 		 */
4760 		if (i++ >= 200) {
4761 			/* Adapter failed to init, timeout, status reg
4762 			   <status> */
4763 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4764 					"0436 Adapter failed to init, "
4765 					"timeout, status reg x%x, "
4766 					"FW Data: A8 x%x AC x%x\n", status,
4767 					readl(phba->MBslimaddr + 0xa8),
4768 					readl(phba->MBslimaddr + 0xac));
4769 			phba->link_state = LPFC_HBA_ERROR;
4770 			return -ETIMEDOUT;
4771 		}
4772 
4773 		/* Check to see if any errors occurred during init */
4774 		if (status & HS_FFERM) {
4775 			/* ERROR: During chipset initialization */
4776 			/* Adapter failed to init, chipset, status reg
4777 			   <status> */
4778 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4779 					"0437 Adapter failed to init, "
4780 					"chipset, status reg x%x, "
4781 					"FW Data: A8 x%x AC x%x\n", status,
4782 					readl(phba->MBslimaddr + 0xa8),
4783 					readl(phba->MBslimaddr + 0xac));
4784 			phba->link_state = LPFC_HBA_ERROR;
4785 			return -EIO;
4786 		}
4787 
4788 		if (i <= 10)
4789 			msleep(10);
4790 		else if (i <= 100)
4791 			msleep(100);
4792 		else
4793 			msleep(1000);
4794 
4795 		if (i == 150) {
4796 			/* Do post */
4797 			phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4798 			lpfc_sli_brdrestart(phba);
4799 		}
4800 		/* Read the HBA Host Status Register */
4801 		if (lpfc_readl(phba->HSregaddr, &status))
4802 			return -EIO;
4803 	}
4804 
4805 	/* Check to see if any errors occurred during init */
4806 	if (status & HS_FFERM) {
4807 		/* ERROR: During chipset initialization */
4808 		/* Adapter failed to init, chipset, status reg <status> */
4809 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4810 				"0438 Adapter failed to init, chipset, "
4811 				"status reg x%x, "
4812 				"FW Data: A8 x%x AC x%x\n", status,
4813 				readl(phba->MBslimaddr + 0xa8),
4814 				readl(phba->MBslimaddr + 0xac));
4815 		phba->link_state = LPFC_HBA_ERROR;
4816 		return -EIO;
4817 	}
4818 
4819 	/* Clear all interrupt enable conditions */
4820 	writel(0, phba->HCregaddr);
4821 	readl(phba->HCregaddr); /* flush */
4822 
4823 	/* setup host attn register */
4824 	writel(0xffffffff, phba->HAregaddr);
4825 	readl(phba->HAregaddr); /* flush */
4826 	return 0;
4827 }
4828 
4829 /**
4830  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
4831  *
4832  * This function calculates and returns the number of HBQs required to be
4833  * configured.
4834  **/
4835 int
4836 lpfc_sli_hbq_count(void)
4837 {
4838 	return ARRAY_SIZE(lpfc_hbq_defs);
4839 }
4840 
4841 /**
4842  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
4843  *
4844  * This function adds the number of hbq entries in every HBQ to get
4845  * the total number of hbq entries required for the HBA and returns
4846  * the total count.
4847  **/
4848 static int
4849 lpfc_sli_hbq_entry_count(void)
4850 {
4851 	int  hbq_count = lpfc_sli_hbq_count();
4852 	int  count = 0;
4853 	int  i;
4854 
4855 	for (i = 0; i < hbq_count; ++i)
4856 		count += lpfc_hbq_defs[i]->entry_count;
4857 	return count;
4858 }
4859 
4860 /**
4861  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
4862  *
4863  * This function calculates amount of memory required for all hbq entries
4864  * to be configured and returns the total memory required.
4865  **/
4866 int
4867 lpfc_sli_hbq_size(void)
4868 {
4869 	return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
4870 }
4871 
4872 /**
4873  * lpfc_sli_hbq_setup - configure and initialize HBQs
4874  * @phba: Pointer to HBA context object.
4875  *
4876  * This function is called during the SLI initialization to configure
4877  * all the HBQs and post buffers to the HBQ. The caller is not
4878  * required to hold any locks. This function will return zero if successful
4879  * else it will return negative error code.
4880  **/
4881 static int
4882 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
4883 {
4884 	int  hbq_count = lpfc_sli_hbq_count();
4885 	LPFC_MBOXQ_t *pmb;
4886 	MAILBOX_t *pmbox;
4887 	uint32_t hbqno;
4888 	uint32_t hbq_entry_index;
4889 
4890 				/* Get a Mailbox buffer to setup mailbox
4891 				 * commands for HBA initialization
4892 				 */
4893 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4894 
4895 	if (!pmb)
4896 		return -ENOMEM;
4897 
4898 	pmbox = &pmb->u.mb;
4899 
4900 	/* Initialize the struct lpfc_sli_hbq structure for each hbq */
4901 	phba->link_state = LPFC_INIT_MBX_CMDS;
4902 	phba->hbq_in_use = 1;
4903 
4904 	hbq_entry_index = 0;
4905 	for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
4906 		phba->hbqs[hbqno].next_hbqPutIdx = 0;
4907 		phba->hbqs[hbqno].hbqPutIdx      = 0;
4908 		phba->hbqs[hbqno].local_hbqGetIdx   = 0;
4909 		phba->hbqs[hbqno].entry_count =
4910 			lpfc_hbq_defs[hbqno]->entry_count;
4911 		lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
4912 			hbq_entry_index, pmb);
4913 		hbq_entry_index += phba->hbqs[hbqno].entry_count;
4914 
4915 		if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
4916 			/* Adapter failed to init, mbxCmd <cmd> CFG_RING,
4917 			   mbxStatus <status>, ring <num> */
4918 
4919 			lpfc_printf_log(phba, KERN_ERR,
4920 					LOG_SLI | LOG_VPORT,
4921 					"1805 Adapter failed to init. "
4922 					"Data: x%x x%x x%x\n",
4923 					pmbox->mbxCommand,
4924 					pmbox->mbxStatus, hbqno);
4925 
4926 			phba->link_state = LPFC_HBA_ERROR;
4927 			mempool_free(pmb, phba->mbox_mem_pool);
4928 			return -ENXIO;
4929 		}
4930 	}
4931 	phba->hbq_count = hbq_count;
4932 
4933 	mempool_free(pmb, phba->mbox_mem_pool);
4934 
4935 	/* Initially populate or replenish the HBQs */
4936 	for (hbqno = 0; hbqno < hbq_count; ++hbqno)
4937 		lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
4938 	return 0;
4939 }
4940 
4941 /**
4942  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
4943  * @phba: Pointer to HBA context object.
4944  *
4945  * This function is called during the SLI initialization to configure
4946  * all the HBQs and post buffers to the HBQ. The caller is not
4947  * required to hold any locks. This function will return zero if successful
4948  * else it will return negative error code.
4949  **/
4950 static int
4951 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
4952 {
4953 	phba->hbq_in_use = 1;
4954 	phba->hbqs[LPFC_ELS_HBQ].entry_count =
4955 		lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
4956 	phba->hbq_count = 1;
4957 	lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
4958 	/* Initially populate or replenish the HBQs */
4959 	return 0;
4960 }
4961 
4962 /**
4963  * lpfc_sli_config_port - Issue config port mailbox command
4964  * @phba: Pointer to HBA context object.
4965  * @sli_mode: sli mode - 2/3
4966  *
4967  * This function is called by the sli initialization code path
4968  * to issue config_port mailbox command. This function restarts the
4969  * HBA firmware and issues a config_port mailbox command to configure
4970  * the SLI interface in the sli mode specified by sli_mode
4971  * variable. The caller is not required to hold any locks.
4972  * The function returns 0 if successful, else returns negative error
4973  * code.
4974  **/
4975 int
4976 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
4977 {
4978 	LPFC_MBOXQ_t *pmb;
4979 	uint32_t resetcount = 0, rc = 0, done = 0;
4980 
4981 	pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4982 	if (!pmb) {
4983 		phba->link_state = LPFC_HBA_ERROR;
4984 		return -ENOMEM;
4985 	}
4986 
4987 	phba->sli_rev = sli_mode;
4988 	while (resetcount < 2 && !done) {
4989 		spin_lock_irq(&phba->hbalock);
4990 		phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
4991 		spin_unlock_irq(&phba->hbalock);
4992 		phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4993 		lpfc_sli_brdrestart(phba);
4994 		rc = lpfc_sli_chipset_init(phba);
4995 		if (rc)
4996 			break;
4997 
4998 		spin_lock_irq(&phba->hbalock);
4999 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5000 		spin_unlock_irq(&phba->hbalock);
5001 		resetcount++;
5002 
5003 		/* Call pre CONFIG_PORT mailbox command initialization.  A
5004 		 * value of 0 means the call was successful.  Any other
5005 		 * nonzero value is a failure, but if ERESTART is returned,
5006 		 * the driver may reset the HBA and try again.
5007 		 */
5008 		rc = lpfc_config_port_prep(phba);
5009 		if (rc == -ERESTART) {
5010 			phba->link_state = LPFC_LINK_UNKNOWN;
5011 			continue;
5012 		} else if (rc)
5013 			break;
5014 
5015 		phba->link_state = LPFC_INIT_MBX_CMDS;
5016 		lpfc_config_port(phba, pmb);
5017 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5018 		phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5019 					LPFC_SLI3_HBQ_ENABLED |
5020 					LPFC_SLI3_CRP_ENABLED |
5021 					LPFC_SLI3_DSS_ENABLED);
5022 		if (rc != MBX_SUCCESS) {
5023 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5024 				"0442 Adapter failed to init, mbxCmd x%x "
5025 				"CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5026 				pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5027 			spin_lock_irq(&phba->hbalock);
5028 			phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5029 			spin_unlock_irq(&phba->hbalock);
5030 			rc = -ENXIO;
5031 		} else {
5032 			/* Allow asynchronous mailbox command to go through */
5033 			spin_lock_irq(&phba->hbalock);
5034 			phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5035 			spin_unlock_irq(&phba->hbalock);
5036 			done = 1;
5037 
5038 			if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5039 			    (pmb->u.mb.un.varCfgPort.gasabt == 0))
5040 				lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5041 					"3110 Port did not grant ASABT\n");
5042 		}
5043 	}
5044 	if (!done) {
5045 		rc = -EINVAL;
5046 		goto do_prep_failed;
5047 	}
5048 	if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5049 		if (!pmb->u.mb.un.varCfgPort.cMA) {
5050 			rc = -ENXIO;
5051 			goto do_prep_failed;
5052 		}
5053 		if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5054 			phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5055 			phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5056 			phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5057 				phba->max_vpi : phba->max_vports;
5058 
5059 		} else
5060 			phba->max_vpi = 0;
5061 		phba->fips_level = 0;
5062 		phba->fips_spec_rev = 0;
5063 		if (pmb->u.mb.un.varCfgPort.gdss) {
5064 			phba->sli3_options |= LPFC_SLI3_DSS_ENABLED;
5065 			phba->fips_level = pmb->u.mb.un.varCfgPort.fips_level;
5066 			phba->fips_spec_rev = pmb->u.mb.un.varCfgPort.fips_rev;
5067 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5068 					"2850 Security Crypto Active. FIPS x%d "
5069 					"(Spec Rev: x%d)",
5070 					phba->fips_level, phba->fips_spec_rev);
5071 		}
5072 		if (pmb->u.mb.un.varCfgPort.sec_err) {
5073 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5074 					"2856 Config Port Security Crypto "
5075 					"Error: x%x ",
5076 					pmb->u.mb.un.varCfgPort.sec_err);
5077 		}
5078 		if (pmb->u.mb.un.varCfgPort.gerbm)
5079 			phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5080 		if (pmb->u.mb.un.varCfgPort.gcrp)
5081 			phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5082 
5083 		phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5084 		phba->port_gp = phba->mbox->us.s3_pgp.port;
5085 
5086 		if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5087 			if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5088 				phba->cfg_enable_bg = 0;
5089 				phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5090 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5091 						"0443 Adapter did not grant "
5092 						"BlockGuard\n");
5093 			}
5094 		}
5095 	} else {
5096 		phba->hbq_get = NULL;
5097 		phba->port_gp = phba->mbox->us.s2.port;
5098 		phba->max_vpi = 0;
5099 	}
5100 do_prep_failed:
5101 	mempool_free(pmb, phba->mbox_mem_pool);
5102 	return rc;
5103 }
5104 
5105 
5106 /**
5107  * lpfc_sli_hba_setup - SLI initialization function
5108  * @phba: Pointer to HBA context object.
5109  *
5110  * This function is the main SLI initialization function. This function
5111  * is called by the HBA initialization code, HBA reset code and HBA
5112  * error attention handler code. Caller is not required to hold any
5113  * locks. This function issues config_port mailbox command to configure
5114  * the SLI, setup iocb rings and HBQ rings. In the end the function
5115  * calls the config_port_post function to issue init_link mailbox
5116  * command and to start the discovery. The function will return zero
5117  * if successful, else it will return negative error code.
5118  **/
5119 int
5120 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5121 {
5122 	uint32_t rc;
5123 	int  mode = 3, i;
5124 	int longs;
5125 
5126 	switch (phba->cfg_sli_mode) {
5127 	case 2:
5128 		if (phba->cfg_enable_npiv) {
5129 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
5130 				"1824 NPIV enabled: Override sli_mode "
5131 				"parameter (%d) to auto (0).\n",
5132 				phba->cfg_sli_mode);
5133 			break;
5134 		}
5135 		mode = 2;
5136 		break;
5137 	case 0:
5138 	case 3:
5139 		break;
5140 	default:
5141 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
5142 				"1819 Unrecognized sli_mode parameter: %d.\n",
5143 				phba->cfg_sli_mode);
5144 
5145 		break;
5146 	}
5147 	phba->fcp_embed_io = 0;	/* SLI4 FC support only */
5148 
5149 	rc = lpfc_sli_config_port(phba, mode);
5150 
5151 	if (rc && phba->cfg_sli_mode == 3)
5152 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
5153 				"1820 Unable to select SLI-3.  "
5154 				"Not supported by adapter.\n");
5155 	if (rc && mode != 2)
5156 		rc = lpfc_sli_config_port(phba, 2);
5157 	else if (rc && mode == 2)
5158 		rc = lpfc_sli_config_port(phba, 3);
5159 	if (rc)
5160 		goto lpfc_sli_hba_setup_error;
5161 
5162 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
5163 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
5164 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
5165 		if (!rc) {
5166 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5167 					"2709 This device supports "
5168 					"Advanced Error Reporting (AER)\n");
5169 			spin_lock_irq(&phba->hbalock);
5170 			phba->hba_flag |= HBA_AER_ENABLED;
5171 			spin_unlock_irq(&phba->hbalock);
5172 		} else {
5173 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5174 					"2708 This device does not support "
5175 					"Advanced Error Reporting (AER): %d\n",
5176 					rc);
5177 			phba->cfg_aer_support = 0;
5178 		}
5179 	}
5180 
5181 	if (phba->sli_rev == 3) {
5182 		phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5183 		phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5184 	} else {
5185 		phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5186 		phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5187 		phba->sli3_options = 0;
5188 	}
5189 
5190 	lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5191 			"0444 Firmware in SLI %x mode. Max_vpi %d\n",
5192 			phba->sli_rev, phba->max_vpi);
5193 	rc = lpfc_sli_ring_map(phba);
5194 
5195 	if (rc)
5196 		goto lpfc_sli_hba_setup_error;
5197 
5198 	/* Initialize VPIs. */
5199 	if (phba->sli_rev == LPFC_SLI_REV3) {
5200 		/*
5201 		 * The VPI bitmask and physical ID array are allocated
5202 		 * and initialized once only - at driver load.  A port
5203 		 * reset doesn't need to reinitialize this memory.
5204 		 */
5205 		if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5206 			longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5207 			phba->vpi_bmask = kcalloc(longs,
5208 						  sizeof(unsigned long),
5209 						  GFP_KERNEL);
5210 			if (!phba->vpi_bmask) {
5211 				rc = -ENOMEM;
5212 				goto lpfc_sli_hba_setup_error;
5213 			}
5214 
5215 			phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5216 						sizeof(uint16_t),
5217 						GFP_KERNEL);
5218 			if (!phba->vpi_ids) {
5219 				kfree(phba->vpi_bmask);
5220 				rc = -ENOMEM;
5221 				goto lpfc_sli_hba_setup_error;
5222 			}
5223 			for (i = 0; i < phba->max_vpi; i++)
5224 				phba->vpi_ids[i] = i;
5225 		}
5226 	}
5227 
5228 	/* Init HBQs */
5229 	if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5230 		rc = lpfc_sli_hbq_setup(phba);
5231 		if (rc)
5232 			goto lpfc_sli_hba_setup_error;
5233 	}
5234 	spin_lock_irq(&phba->hbalock);
5235 	phba->sli.sli_flag |= LPFC_PROCESS_LA;
5236 	spin_unlock_irq(&phba->hbalock);
5237 
5238 	rc = lpfc_config_port_post(phba);
5239 	if (rc)
5240 		goto lpfc_sli_hba_setup_error;
5241 
5242 	return rc;
5243 
5244 lpfc_sli_hba_setup_error:
5245 	phba->link_state = LPFC_HBA_ERROR;
5246 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5247 			"0445 Firmware initialization failed\n");
5248 	return rc;
5249 }
5250 
5251 /**
5252  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5253  * @phba: Pointer to HBA context object.
5254  * @mboxq: mailbox pointer.
5255  * This function issue a dump mailbox command to read config region
5256  * 23 and parse the records in the region and populate driver
5257  * data structure.
5258  **/
5259 static int
5260 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5261 {
5262 	LPFC_MBOXQ_t *mboxq;
5263 	struct lpfc_dmabuf *mp;
5264 	struct lpfc_mqe *mqe;
5265 	uint32_t data_length;
5266 	int rc;
5267 
5268 	/* Program the default value of vlan_id and fc_map */
5269 	phba->valid_vlan = 0;
5270 	phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5271 	phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5272 	phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5273 
5274 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5275 	if (!mboxq)
5276 		return -ENOMEM;
5277 
5278 	mqe = &mboxq->u.mqe;
5279 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5280 		rc = -ENOMEM;
5281 		goto out_free_mboxq;
5282 	}
5283 
5284 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5285 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5286 
5287 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5288 			"(%d):2571 Mailbox cmd x%x Status x%x "
5289 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5290 			"x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5291 			"CQ: x%x x%x x%x x%x\n",
5292 			mboxq->vport ? mboxq->vport->vpi : 0,
5293 			bf_get(lpfc_mqe_command, mqe),
5294 			bf_get(lpfc_mqe_status, mqe),
5295 			mqe->un.mb_words[0], mqe->un.mb_words[1],
5296 			mqe->un.mb_words[2], mqe->un.mb_words[3],
5297 			mqe->un.mb_words[4], mqe->un.mb_words[5],
5298 			mqe->un.mb_words[6], mqe->un.mb_words[7],
5299 			mqe->un.mb_words[8], mqe->un.mb_words[9],
5300 			mqe->un.mb_words[10], mqe->un.mb_words[11],
5301 			mqe->un.mb_words[12], mqe->un.mb_words[13],
5302 			mqe->un.mb_words[14], mqe->un.mb_words[15],
5303 			mqe->un.mb_words[16], mqe->un.mb_words[50],
5304 			mboxq->mcqe.word0,
5305 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
5306 			mboxq->mcqe.trailer);
5307 
5308 	if (rc) {
5309 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5310 		kfree(mp);
5311 		rc = -EIO;
5312 		goto out_free_mboxq;
5313 	}
5314 	data_length = mqe->un.mb_words[5];
5315 	if (data_length > DMP_RGN23_SIZE) {
5316 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
5317 		kfree(mp);
5318 		rc = -EIO;
5319 		goto out_free_mboxq;
5320 	}
5321 
5322 	lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5323 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
5324 	kfree(mp);
5325 	rc = 0;
5326 
5327 out_free_mboxq:
5328 	mempool_free(mboxq, phba->mbox_mem_pool);
5329 	return rc;
5330 }
5331 
5332 /**
5333  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5334  * @phba: pointer to lpfc hba data structure.
5335  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5336  * @vpd: pointer to the memory to hold resulting port vpd data.
5337  * @vpd_size: On input, the number of bytes allocated to @vpd.
5338  *	      On output, the number of data bytes in @vpd.
5339  *
5340  * This routine executes a READ_REV SLI4 mailbox command.  In
5341  * addition, this routine gets the port vpd data.
5342  *
5343  * Return codes
5344  * 	0 - successful
5345  * 	-ENOMEM - could not allocated memory.
5346  **/
5347 static int
5348 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5349 		    uint8_t *vpd, uint32_t *vpd_size)
5350 {
5351 	int rc = 0;
5352 	uint32_t dma_size;
5353 	struct lpfc_dmabuf *dmabuf;
5354 	struct lpfc_mqe *mqe;
5355 
5356 	dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5357 	if (!dmabuf)
5358 		return -ENOMEM;
5359 
5360 	/*
5361 	 * Get a DMA buffer for the vpd data resulting from the READ_REV
5362 	 * mailbox command.
5363 	 */
5364 	dma_size = *vpd_size;
5365 	dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5366 					  &dmabuf->phys, GFP_KERNEL);
5367 	if (!dmabuf->virt) {
5368 		kfree(dmabuf);
5369 		return -ENOMEM;
5370 	}
5371 
5372 	/*
5373 	 * The SLI4 implementation of READ_REV conflicts at word1,
5374 	 * bits 31:16 and SLI4 adds vpd functionality not present
5375 	 * in SLI3.  This code corrects the conflicts.
5376 	 */
5377 	lpfc_read_rev(phba, mboxq);
5378 	mqe = &mboxq->u.mqe;
5379 	mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5380 	mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5381 	mqe->un.read_rev.word1 &= 0x0000FFFF;
5382 	bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5383 	bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5384 
5385 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5386 	if (rc) {
5387 		dma_free_coherent(&phba->pcidev->dev, dma_size,
5388 				  dmabuf->virt, dmabuf->phys);
5389 		kfree(dmabuf);
5390 		return -EIO;
5391 	}
5392 
5393 	/*
5394 	 * The available vpd length cannot be bigger than the
5395 	 * DMA buffer passed to the port.  Catch the less than
5396 	 * case and update the caller's size.
5397 	 */
5398 	if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5399 		*vpd_size = mqe->un.read_rev.avail_vpd_len;
5400 
5401 	memcpy(vpd, dmabuf->virt, *vpd_size);
5402 
5403 	dma_free_coherent(&phba->pcidev->dev, dma_size,
5404 			  dmabuf->virt, dmabuf->phys);
5405 	kfree(dmabuf);
5406 	return 0;
5407 }
5408 
5409 /**
5410  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
5411  * @phba: pointer to lpfc hba data structure.
5412  *
5413  * This routine retrieves SLI4 device physical port name this PCI function
5414  * is attached to.
5415  *
5416  * Return codes
5417  *      0 - successful
5418  *      otherwise - failed to retrieve physical port name
5419  **/
5420 static int
5421 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
5422 {
5423 	LPFC_MBOXQ_t *mboxq;
5424 	struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5425 	struct lpfc_controller_attribute *cntl_attr;
5426 	struct lpfc_mbx_get_port_name *get_port_name;
5427 	void *virtaddr = NULL;
5428 	uint32_t alloclen, reqlen;
5429 	uint32_t shdr_status, shdr_add_status;
5430 	union lpfc_sli4_cfg_shdr *shdr;
5431 	char cport_name = 0;
5432 	int rc;
5433 
5434 	/* We assume nothing at this point */
5435 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5436 	phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
5437 
5438 	mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5439 	if (!mboxq)
5440 		return -ENOMEM;
5441 	/* obtain link type and link number via READ_CONFIG */
5442 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5443 	lpfc_sli4_read_config(phba);
5444 	if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
5445 		goto retrieve_ppname;
5446 
5447 	/* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
5448 	reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5449 	alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5450 			LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5451 			LPFC_SLI4_MBX_NEMBED);
5452 	if (alloclen < reqlen) {
5453 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5454 				"3084 Allocated DMA memory size (%d) is "
5455 				"less than the requested DMA memory size "
5456 				"(%d)\n", alloclen, reqlen);
5457 		rc = -ENOMEM;
5458 		goto out_free_mboxq;
5459 	}
5460 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5461 	virtaddr = mboxq->sge_array->addr[0];
5462 	mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5463 	shdr = &mbx_cntl_attr->cfg_shdr;
5464 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5465 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5466 	if (shdr_status || shdr_add_status || rc) {
5467 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5468 				"3085 Mailbox x%x (x%x/x%x) failed, "
5469 				"rc:x%x, status:x%x, add_status:x%x\n",
5470 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5471 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5472 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5473 				rc, shdr_status, shdr_add_status);
5474 		rc = -ENXIO;
5475 		goto out_free_mboxq;
5476 	}
5477 	cntl_attr = &mbx_cntl_attr->cntl_attr;
5478 	phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5479 	phba->sli4_hba.lnk_info.lnk_tp =
5480 		bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5481 	phba->sli4_hba.lnk_info.lnk_no =
5482 		bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5483 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5484 			"3086 lnk_type:%d, lnk_numb:%d\n",
5485 			phba->sli4_hba.lnk_info.lnk_tp,
5486 			phba->sli4_hba.lnk_info.lnk_no);
5487 
5488 retrieve_ppname:
5489 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5490 		LPFC_MBOX_OPCODE_GET_PORT_NAME,
5491 		sizeof(struct lpfc_mbx_get_port_name) -
5492 		sizeof(struct lpfc_sli4_cfg_mhdr),
5493 		LPFC_SLI4_MBX_EMBED);
5494 	get_port_name = &mboxq->u.mqe.un.get_port_name;
5495 	shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5496 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
5497 	bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
5498 		phba->sli4_hba.lnk_info.lnk_tp);
5499 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5500 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5501 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5502 	if (shdr_status || shdr_add_status || rc) {
5503 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5504 				"3087 Mailbox x%x (x%x/x%x) failed: "
5505 				"rc:x%x, status:x%x, add_status:x%x\n",
5506 				bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5507 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5508 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5509 				rc, shdr_status, shdr_add_status);
5510 		rc = -ENXIO;
5511 		goto out_free_mboxq;
5512 	}
5513 	switch (phba->sli4_hba.lnk_info.lnk_no) {
5514 	case LPFC_LINK_NUMBER_0:
5515 		cport_name = bf_get(lpfc_mbx_get_port_name_name0,
5516 				&get_port_name->u.response);
5517 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5518 		break;
5519 	case LPFC_LINK_NUMBER_1:
5520 		cport_name = bf_get(lpfc_mbx_get_port_name_name1,
5521 				&get_port_name->u.response);
5522 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5523 		break;
5524 	case LPFC_LINK_NUMBER_2:
5525 		cport_name = bf_get(lpfc_mbx_get_port_name_name2,
5526 				&get_port_name->u.response);
5527 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5528 		break;
5529 	case LPFC_LINK_NUMBER_3:
5530 		cport_name = bf_get(lpfc_mbx_get_port_name_name3,
5531 				&get_port_name->u.response);
5532 		phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5533 		break;
5534 	default:
5535 		break;
5536 	}
5537 
5538 	if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
5539 		phba->Port[0] = cport_name;
5540 		phba->Port[1] = '\0';
5541 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5542 				"3091 SLI get port name: %s\n", phba->Port);
5543 	}
5544 
5545 out_free_mboxq:
5546 	if (rc != MBX_TIMEOUT) {
5547 		if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5548 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
5549 		else
5550 			mempool_free(mboxq, phba->mbox_mem_pool);
5551 	}
5552 	return rc;
5553 }
5554 
5555 /**
5556  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
5557  * @phba: pointer to lpfc hba data structure.
5558  *
5559  * This routine is called to explicitly arm the SLI4 device's completion and
5560  * event queues
5561  **/
5562 static void
5563 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
5564 {
5565 	int qidx;
5566 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
5567 
5568 	sli4_hba->sli4_cq_release(sli4_hba->mbx_cq, LPFC_QUEUE_REARM);
5569 	sli4_hba->sli4_cq_release(sli4_hba->els_cq, LPFC_QUEUE_REARM);
5570 	if (sli4_hba->nvmels_cq)
5571 		sli4_hba->sli4_cq_release(sli4_hba->nvmels_cq,
5572 						LPFC_QUEUE_REARM);
5573 
5574 	if (sli4_hba->fcp_cq)
5575 		for (qidx = 0; qidx < phba->cfg_fcp_io_channel; qidx++)
5576 			sli4_hba->sli4_cq_release(sli4_hba->fcp_cq[qidx],
5577 						LPFC_QUEUE_REARM);
5578 
5579 	if (sli4_hba->nvme_cq)
5580 		for (qidx = 0; qidx < phba->cfg_nvme_io_channel; qidx++)
5581 			sli4_hba->sli4_cq_release(sli4_hba->nvme_cq[qidx],
5582 						LPFC_QUEUE_REARM);
5583 
5584 	if (phba->cfg_fof)
5585 		sli4_hba->sli4_cq_release(sli4_hba->oas_cq, LPFC_QUEUE_REARM);
5586 
5587 	if (sli4_hba->hba_eq)
5588 		for (qidx = 0; qidx < phba->io_channel_irqs; qidx++)
5589 			sli4_hba->sli4_eq_release(sli4_hba->hba_eq[qidx],
5590 							LPFC_QUEUE_REARM);
5591 
5592 	if (phba->nvmet_support) {
5593 		for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
5594 			sli4_hba->sli4_cq_release(
5595 				sli4_hba->nvmet_cqset[qidx],
5596 				LPFC_QUEUE_REARM);
5597 		}
5598 	}
5599 
5600 	if (phba->cfg_fof)
5601 		sli4_hba->sli4_eq_release(sli4_hba->fof_eq, LPFC_QUEUE_REARM);
5602 }
5603 
5604 /**
5605  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
5606  * @phba: Pointer to HBA context object.
5607  * @type: The resource extent type.
5608  * @extnt_count: buffer to hold port available extent count.
5609  * @extnt_size: buffer to hold element count per extent.
5610  *
5611  * This function calls the port and retrievs the number of available
5612  * extents and their size for a particular extent type.
5613  *
5614  * Returns: 0 if successful.  Nonzero otherwise.
5615  **/
5616 int
5617 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
5618 			       uint16_t *extnt_count, uint16_t *extnt_size)
5619 {
5620 	int rc = 0;
5621 	uint32_t length;
5622 	uint32_t mbox_tmo;
5623 	struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
5624 	LPFC_MBOXQ_t *mbox;
5625 
5626 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5627 	if (!mbox)
5628 		return -ENOMEM;
5629 
5630 	/* Find out how many extents are available for this resource type */
5631 	length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
5632 		  sizeof(struct lpfc_sli4_cfg_mhdr));
5633 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5634 			 LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
5635 			 length, LPFC_SLI4_MBX_EMBED);
5636 
5637 	/* Send an extents count of 0 - the GET doesn't use it. */
5638 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5639 					LPFC_SLI4_MBX_EMBED);
5640 	if (unlikely(rc)) {
5641 		rc = -EIO;
5642 		goto err_exit;
5643 	}
5644 
5645 	if (!phba->sli4_hba.intr_enable)
5646 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5647 	else {
5648 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5649 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5650 	}
5651 	if (unlikely(rc)) {
5652 		rc = -EIO;
5653 		goto err_exit;
5654 	}
5655 
5656 	rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
5657 	if (bf_get(lpfc_mbox_hdr_status,
5658 		   &rsrc_info->header.cfg_shdr.response)) {
5659 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5660 				"2930 Failed to get resource extents "
5661 				"Status 0x%x Add'l Status 0x%x\n",
5662 				bf_get(lpfc_mbox_hdr_status,
5663 				       &rsrc_info->header.cfg_shdr.response),
5664 				bf_get(lpfc_mbox_hdr_add_status,
5665 				       &rsrc_info->header.cfg_shdr.response));
5666 		rc = -EIO;
5667 		goto err_exit;
5668 	}
5669 
5670 	*extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
5671 			      &rsrc_info->u.rsp);
5672 	*extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
5673 			     &rsrc_info->u.rsp);
5674 
5675 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5676 			"3162 Retrieved extents type-%d from port: count:%d, "
5677 			"size:%d\n", type, *extnt_count, *extnt_size);
5678 
5679 err_exit:
5680 	mempool_free(mbox, phba->mbox_mem_pool);
5681 	return rc;
5682 }
5683 
5684 /**
5685  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
5686  * @phba: Pointer to HBA context object.
5687  * @type: The extent type to check.
5688  *
5689  * This function reads the current available extents from the port and checks
5690  * if the extent count or extent size has changed since the last access.
5691  * Callers use this routine post port reset to understand if there is a
5692  * extent reprovisioning requirement.
5693  *
5694  * Returns:
5695  *   -Error: error indicates problem.
5696  *   1: Extent count or size has changed.
5697  *   0: No changes.
5698  **/
5699 static int
5700 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
5701 {
5702 	uint16_t curr_ext_cnt, rsrc_ext_cnt;
5703 	uint16_t size_diff, rsrc_ext_size;
5704 	int rc = 0;
5705 	struct lpfc_rsrc_blks *rsrc_entry;
5706 	struct list_head *rsrc_blk_list = NULL;
5707 
5708 	size_diff = 0;
5709 	curr_ext_cnt = 0;
5710 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5711 					    &rsrc_ext_cnt,
5712 					    &rsrc_ext_size);
5713 	if (unlikely(rc))
5714 		return -EIO;
5715 
5716 	switch (type) {
5717 	case LPFC_RSC_TYPE_FCOE_RPI:
5718 		rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5719 		break;
5720 	case LPFC_RSC_TYPE_FCOE_VPI:
5721 		rsrc_blk_list = &phba->lpfc_vpi_blk_list;
5722 		break;
5723 	case LPFC_RSC_TYPE_FCOE_XRI:
5724 		rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5725 		break;
5726 	case LPFC_RSC_TYPE_FCOE_VFI:
5727 		rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5728 		break;
5729 	default:
5730 		break;
5731 	}
5732 
5733 	list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
5734 		curr_ext_cnt++;
5735 		if (rsrc_entry->rsrc_size != rsrc_ext_size)
5736 			size_diff++;
5737 	}
5738 
5739 	if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
5740 		rc = 1;
5741 
5742 	return rc;
5743 }
5744 
5745 /**
5746  * lpfc_sli4_cfg_post_extnts -
5747  * @phba: Pointer to HBA context object.
5748  * @extnt_cnt - number of available extents.
5749  * @type - the extent type (rpi, xri, vfi, vpi).
5750  * @emb - buffer to hold either MBX_EMBED or MBX_NEMBED operation.
5751  * @mbox - pointer to the caller's allocated mailbox structure.
5752  *
5753  * This function executes the extents allocation request.  It also
5754  * takes care of the amount of memory needed to allocate or get the
5755  * allocated extents. It is the caller's responsibility to evaluate
5756  * the response.
5757  *
5758  * Returns:
5759  *   -Error:  Error value describes the condition found.
5760  *   0: if successful
5761  **/
5762 static int
5763 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
5764 			  uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
5765 {
5766 	int rc = 0;
5767 	uint32_t req_len;
5768 	uint32_t emb_len;
5769 	uint32_t alloc_len, mbox_tmo;
5770 
5771 	/* Calculate the total requested length of the dma memory */
5772 	req_len = extnt_cnt * sizeof(uint16_t);
5773 
5774 	/*
5775 	 * Calculate the size of an embedded mailbox.  The uint32_t
5776 	 * accounts for extents-specific word.
5777 	 */
5778 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
5779 		sizeof(uint32_t);
5780 
5781 	/*
5782 	 * Presume the allocation and response will fit into an embedded
5783 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
5784 	 */
5785 	*emb = LPFC_SLI4_MBX_EMBED;
5786 	if (req_len > emb_len) {
5787 		req_len = extnt_cnt * sizeof(uint16_t) +
5788 			sizeof(union lpfc_sli4_cfg_shdr) +
5789 			sizeof(uint32_t);
5790 		*emb = LPFC_SLI4_MBX_NEMBED;
5791 	}
5792 
5793 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5794 				     LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
5795 				     req_len, *emb);
5796 	if (alloc_len < req_len) {
5797 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5798 			"2982 Allocated DMA memory size (x%x) is "
5799 			"less than the requested DMA memory "
5800 			"size (x%x)\n", alloc_len, req_len);
5801 		return -ENOMEM;
5802 	}
5803 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
5804 	if (unlikely(rc))
5805 		return -EIO;
5806 
5807 	if (!phba->sli4_hba.intr_enable)
5808 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5809 	else {
5810 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5811 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5812 	}
5813 
5814 	if (unlikely(rc))
5815 		rc = -EIO;
5816 	return rc;
5817 }
5818 
5819 /**
5820  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
5821  * @phba: Pointer to HBA context object.
5822  * @type:  The resource extent type to allocate.
5823  *
5824  * This function allocates the number of elements for the specified
5825  * resource type.
5826  **/
5827 static int
5828 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
5829 {
5830 	bool emb = false;
5831 	uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
5832 	uint16_t rsrc_id, rsrc_start, j, k;
5833 	uint16_t *ids;
5834 	int i, rc;
5835 	unsigned long longs;
5836 	unsigned long *bmask;
5837 	struct lpfc_rsrc_blks *rsrc_blks;
5838 	LPFC_MBOXQ_t *mbox;
5839 	uint32_t length;
5840 	struct lpfc_id_range *id_array = NULL;
5841 	void *virtaddr = NULL;
5842 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
5843 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
5844 	struct list_head *ext_blk_list;
5845 
5846 	rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5847 					    &rsrc_cnt,
5848 					    &rsrc_size);
5849 	if (unlikely(rc))
5850 		return -EIO;
5851 
5852 	if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
5853 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5854 			"3009 No available Resource Extents "
5855 			"for resource type 0x%x: Count: 0x%x, "
5856 			"Size 0x%x\n", type, rsrc_cnt,
5857 			rsrc_size);
5858 		return -ENOMEM;
5859 	}
5860 
5861 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
5862 			"2903 Post resource extents type-0x%x: "
5863 			"count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
5864 
5865 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5866 	if (!mbox)
5867 		return -ENOMEM;
5868 
5869 	rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
5870 	if (unlikely(rc)) {
5871 		rc = -EIO;
5872 		goto err_exit;
5873 	}
5874 
5875 	/*
5876 	 * Figure out where the response is located.  Then get local pointers
5877 	 * to the response data.  The port does not guarantee to respond to
5878 	 * all extents counts request so update the local variable with the
5879 	 * allocated count from the port.
5880 	 */
5881 	if (emb == LPFC_SLI4_MBX_EMBED) {
5882 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
5883 		id_array = &rsrc_ext->u.rsp.id[0];
5884 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
5885 	} else {
5886 		virtaddr = mbox->sge_array->addr[0];
5887 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
5888 		rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
5889 		id_array = &n_rsrc->id;
5890 	}
5891 
5892 	longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
5893 	rsrc_id_cnt = rsrc_cnt * rsrc_size;
5894 
5895 	/*
5896 	 * Based on the resource size and count, correct the base and max
5897 	 * resource values.
5898 	 */
5899 	length = sizeof(struct lpfc_rsrc_blks);
5900 	switch (type) {
5901 	case LPFC_RSC_TYPE_FCOE_RPI:
5902 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
5903 						   sizeof(unsigned long),
5904 						   GFP_KERNEL);
5905 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
5906 			rc = -ENOMEM;
5907 			goto err_exit;
5908 		}
5909 		phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
5910 						 sizeof(uint16_t),
5911 						 GFP_KERNEL);
5912 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
5913 			kfree(phba->sli4_hba.rpi_bmask);
5914 			rc = -ENOMEM;
5915 			goto err_exit;
5916 		}
5917 
5918 		/*
5919 		 * The next_rpi was initialized with the maximum available
5920 		 * count but the port may allocate a smaller number.  Catch
5921 		 * that case and update the next_rpi.
5922 		 */
5923 		phba->sli4_hba.next_rpi = rsrc_id_cnt;
5924 
5925 		/* Initialize local ptrs for common extent processing later. */
5926 		bmask = phba->sli4_hba.rpi_bmask;
5927 		ids = phba->sli4_hba.rpi_ids;
5928 		ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5929 		break;
5930 	case LPFC_RSC_TYPE_FCOE_VPI:
5931 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
5932 					  GFP_KERNEL);
5933 		if (unlikely(!phba->vpi_bmask)) {
5934 			rc = -ENOMEM;
5935 			goto err_exit;
5936 		}
5937 		phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
5938 					 GFP_KERNEL);
5939 		if (unlikely(!phba->vpi_ids)) {
5940 			kfree(phba->vpi_bmask);
5941 			rc = -ENOMEM;
5942 			goto err_exit;
5943 		}
5944 
5945 		/* Initialize local ptrs for common extent processing later. */
5946 		bmask = phba->vpi_bmask;
5947 		ids = phba->vpi_ids;
5948 		ext_blk_list = &phba->lpfc_vpi_blk_list;
5949 		break;
5950 	case LPFC_RSC_TYPE_FCOE_XRI:
5951 		phba->sli4_hba.xri_bmask = kcalloc(longs,
5952 						   sizeof(unsigned long),
5953 						   GFP_KERNEL);
5954 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
5955 			rc = -ENOMEM;
5956 			goto err_exit;
5957 		}
5958 		phba->sli4_hba.max_cfg_param.xri_used = 0;
5959 		phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
5960 						 sizeof(uint16_t),
5961 						 GFP_KERNEL);
5962 		if (unlikely(!phba->sli4_hba.xri_ids)) {
5963 			kfree(phba->sli4_hba.xri_bmask);
5964 			rc = -ENOMEM;
5965 			goto err_exit;
5966 		}
5967 
5968 		/* Initialize local ptrs for common extent processing later. */
5969 		bmask = phba->sli4_hba.xri_bmask;
5970 		ids = phba->sli4_hba.xri_ids;
5971 		ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5972 		break;
5973 	case LPFC_RSC_TYPE_FCOE_VFI:
5974 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
5975 						   sizeof(unsigned long),
5976 						   GFP_KERNEL);
5977 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
5978 			rc = -ENOMEM;
5979 			goto err_exit;
5980 		}
5981 		phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
5982 						 sizeof(uint16_t),
5983 						 GFP_KERNEL);
5984 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
5985 			kfree(phba->sli4_hba.vfi_bmask);
5986 			rc = -ENOMEM;
5987 			goto err_exit;
5988 		}
5989 
5990 		/* Initialize local ptrs for common extent processing later. */
5991 		bmask = phba->sli4_hba.vfi_bmask;
5992 		ids = phba->sli4_hba.vfi_ids;
5993 		ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5994 		break;
5995 	default:
5996 		/* Unsupported Opcode.  Fail call. */
5997 		id_array = NULL;
5998 		bmask = NULL;
5999 		ids = NULL;
6000 		ext_blk_list = NULL;
6001 		goto err_exit;
6002 	}
6003 
6004 	/*
6005 	 * Complete initializing the extent configuration with the
6006 	 * allocated ids assigned to this function.  The bitmask serves
6007 	 * as an index into the array and manages the available ids.  The
6008 	 * array just stores the ids communicated to the port via the wqes.
6009 	 */
6010 	for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6011 		if ((i % 2) == 0)
6012 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6013 					 &id_array[k]);
6014 		else
6015 			rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6016 					 &id_array[k]);
6017 
6018 		rsrc_blks = kzalloc(length, GFP_KERNEL);
6019 		if (unlikely(!rsrc_blks)) {
6020 			rc = -ENOMEM;
6021 			kfree(bmask);
6022 			kfree(ids);
6023 			goto err_exit;
6024 		}
6025 		rsrc_blks->rsrc_start = rsrc_id;
6026 		rsrc_blks->rsrc_size = rsrc_size;
6027 		list_add_tail(&rsrc_blks->list, ext_blk_list);
6028 		rsrc_start = rsrc_id;
6029 		if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6030 			phba->sli4_hba.scsi_xri_start = rsrc_start +
6031 				lpfc_sli4_get_iocb_cnt(phba);
6032 			phba->sli4_hba.nvme_xri_start =
6033 				phba->sli4_hba.scsi_xri_start +
6034 				phba->sli4_hba.scsi_xri_max;
6035 		}
6036 
6037 		while (rsrc_id < (rsrc_start + rsrc_size)) {
6038 			ids[j] = rsrc_id;
6039 			rsrc_id++;
6040 			j++;
6041 		}
6042 		/* Entire word processed.  Get next word.*/
6043 		if ((i % 2) == 1)
6044 			k++;
6045 	}
6046  err_exit:
6047 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6048 	return rc;
6049 }
6050 
6051 
6052 
6053 /**
6054  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6055  * @phba: Pointer to HBA context object.
6056  * @type: the extent's type.
6057  *
6058  * This function deallocates all extents of a particular resource type.
6059  * SLI4 does not allow for deallocating a particular extent range.  It
6060  * is the caller's responsibility to release all kernel memory resources.
6061  **/
6062 static int
6063 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6064 {
6065 	int rc;
6066 	uint32_t length, mbox_tmo = 0;
6067 	LPFC_MBOXQ_t *mbox;
6068 	struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6069 	struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6070 
6071 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6072 	if (!mbox)
6073 		return -ENOMEM;
6074 
6075 	/*
6076 	 * This function sends an embedded mailbox because it only sends the
6077 	 * the resource type.  All extents of this type are released by the
6078 	 * port.
6079 	 */
6080 	length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6081 		  sizeof(struct lpfc_sli4_cfg_mhdr));
6082 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6083 			 LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6084 			 length, LPFC_SLI4_MBX_EMBED);
6085 
6086 	/* Send an extents count of 0 - the dealloc doesn't use it. */
6087 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6088 					LPFC_SLI4_MBX_EMBED);
6089 	if (unlikely(rc)) {
6090 		rc = -EIO;
6091 		goto out_free_mbox;
6092 	}
6093 	if (!phba->sli4_hba.intr_enable)
6094 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6095 	else {
6096 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6097 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6098 	}
6099 	if (unlikely(rc)) {
6100 		rc = -EIO;
6101 		goto out_free_mbox;
6102 	}
6103 
6104 	dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6105 	if (bf_get(lpfc_mbox_hdr_status,
6106 		   &dealloc_rsrc->header.cfg_shdr.response)) {
6107 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
6108 				"2919 Failed to release resource extents "
6109 				"for type %d - Status 0x%x Add'l Status 0x%x. "
6110 				"Resource memory not released.\n",
6111 				type,
6112 				bf_get(lpfc_mbox_hdr_status,
6113 				    &dealloc_rsrc->header.cfg_shdr.response),
6114 				bf_get(lpfc_mbox_hdr_add_status,
6115 				    &dealloc_rsrc->header.cfg_shdr.response));
6116 		rc = -EIO;
6117 		goto out_free_mbox;
6118 	}
6119 
6120 	/* Release kernel memory resources for the specific type. */
6121 	switch (type) {
6122 	case LPFC_RSC_TYPE_FCOE_VPI:
6123 		kfree(phba->vpi_bmask);
6124 		kfree(phba->vpi_ids);
6125 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6126 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6127 				    &phba->lpfc_vpi_blk_list, list) {
6128 			list_del_init(&rsrc_blk->list);
6129 			kfree(rsrc_blk);
6130 		}
6131 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6132 		break;
6133 	case LPFC_RSC_TYPE_FCOE_XRI:
6134 		kfree(phba->sli4_hba.xri_bmask);
6135 		kfree(phba->sli4_hba.xri_ids);
6136 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6137 				    &phba->sli4_hba.lpfc_xri_blk_list, list) {
6138 			list_del_init(&rsrc_blk->list);
6139 			kfree(rsrc_blk);
6140 		}
6141 		break;
6142 	case LPFC_RSC_TYPE_FCOE_VFI:
6143 		kfree(phba->sli4_hba.vfi_bmask);
6144 		kfree(phba->sli4_hba.vfi_ids);
6145 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6146 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6147 				    &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6148 			list_del_init(&rsrc_blk->list);
6149 			kfree(rsrc_blk);
6150 		}
6151 		break;
6152 	case LPFC_RSC_TYPE_FCOE_RPI:
6153 		/* RPI bitmask and physical id array are cleaned up earlier. */
6154 		list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6155 				    &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6156 			list_del_init(&rsrc_blk->list);
6157 			kfree(rsrc_blk);
6158 		}
6159 		break;
6160 	default:
6161 		break;
6162 	}
6163 
6164 	bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6165 
6166  out_free_mbox:
6167 	mempool_free(mbox, phba->mbox_mem_pool);
6168 	return rc;
6169 }
6170 
6171 static void
6172 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6173 		  uint32_t feature)
6174 {
6175 	uint32_t len;
6176 
6177 	len = sizeof(struct lpfc_mbx_set_feature) -
6178 		sizeof(struct lpfc_sli4_cfg_mhdr);
6179 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6180 			 LPFC_MBOX_OPCODE_SET_FEATURES, len,
6181 			 LPFC_SLI4_MBX_EMBED);
6182 
6183 	switch (feature) {
6184 	case LPFC_SET_UE_RECOVERY:
6185 		bf_set(lpfc_mbx_set_feature_UER,
6186 		       &mbox->u.mqe.un.set_feature, 1);
6187 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6188 		mbox->u.mqe.un.set_feature.param_len = 8;
6189 		break;
6190 	case LPFC_SET_MDS_DIAGS:
6191 		bf_set(lpfc_mbx_set_feature_mds,
6192 		       &mbox->u.mqe.un.set_feature, 1);
6193 		bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6194 		       &mbox->u.mqe.un.set_feature, 1);
6195 		mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6196 		mbox->u.mqe.un.set_feature.param_len = 8;
6197 		break;
6198 	}
6199 
6200 	return;
6201 }
6202 
6203 /**
6204  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6205  * @phba: Pointer to HBA context object.
6206  *
6207  * Disable FW logging into host memory on the adapter. To
6208  * be done before reading logs from the host memory.
6209  **/
6210 void
6211 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6212 {
6213 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6214 
6215 	ras_fwlog->ras_active = false;
6216 
6217 	/* Disable FW logging to host memory */
6218 	writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6219 	       phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6220 }
6221 
6222 /**
6223  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6224  * @phba: Pointer to HBA context object.
6225  *
6226  * This function is called to free memory allocated for RAS FW logging
6227  * support in the driver.
6228  **/
6229 void
6230 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6231 {
6232 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6233 	struct lpfc_dmabuf *dmabuf, *next;
6234 
6235 	if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6236 		list_for_each_entry_safe(dmabuf, next,
6237 				    &ras_fwlog->fwlog_buff_list,
6238 				    list) {
6239 			list_del(&dmabuf->list);
6240 			dma_free_coherent(&phba->pcidev->dev,
6241 					  LPFC_RAS_MAX_ENTRY_SIZE,
6242 					  dmabuf->virt, dmabuf->phys);
6243 			kfree(dmabuf);
6244 		}
6245 	}
6246 
6247 	if (ras_fwlog->lwpd.virt) {
6248 		dma_free_coherent(&phba->pcidev->dev,
6249 				  sizeof(uint32_t) * 2,
6250 				  ras_fwlog->lwpd.virt,
6251 				  ras_fwlog->lwpd.phys);
6252 		ras_fwlog->lwpd.virt = NULL;
6253 	}
6254 
6255 	ras_fwlog->ras_active = false;
6256 }
6257 
6258 /**
6259  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6260  * @phba: Pointer to HBA context object.
6261  * @fwlog_buff_count: Count of buffers to be created.
6262  *
6263  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6264  * to update FW log is posted to the adapter.
6265  * Buffer count is calculated based on module param ras_fwlog_buffsize
6266  * Size of each buffer posted to FW is 64K.
6267  **/
6268 
6269 static int
6270 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6271 			uint32_t fwlog_buff_count)
6272 {
6273 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6274 	struct lpfc_dmabuf *dmabuf;
6275 	int rc = 0, i = 0;
6276 
6277 	/* Initialize List */
6278 	INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6279 
6280 	/* Allocate memory for the LWPD */
6281 	ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6282 					    sizeof(uint32_t) * 2,
6283 					    &ras_fwlog->lwpd.phys,
6284 					    GFP_KERNEL);
6285 	if (!ras_fwlog->lwpd.virt) {
6286 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6287 				"6185 LWPD Memory Alloc Failed\n");
6288 
6289 		return -ENOMEM;
6290 	}
6291 
6292 	ras_fwlog->fw_buffcount = fwlog_buff_count;
6293 	for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6294 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6295 				 GFP_KERNEL);
6296 		if (!dmabuf) {
6297 			rc = -ENOMEM;
6298 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6299 					"6186 Memory Alloc failed FW logging");
6300 			goto free_mem;
6301 		}
6302 
6303 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6304 						  LPFC_RAS_MAX_ENTRY_SIZE,
6305 						  &dmabuf->phys, GFP_KERNEL);
6306 		if (!dmabuf->virt) {
6307 			kfree(dmabuf);
6308 			rc = -ENOMEM;
6309 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6310 					"6187 DMA Alloc Failed FW logging");
6311 			goto free_mem;
6312 		}
6313 		dmabuf->buffer_tag = i;
6314 		list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6315 	}
6316 
6317 free_mem:
6318 	if (rc)
6319 		lpfc_sli4_ras_dma_free(phba);
6320 
6321 	return rc;
6322 }
6323 
6324 /**
6325  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6326  * @phba: pointer to lpfc hba data structure.
6327  * @pmboxq: pointer to the driver internal queue element for mailbox command.
6328  *
6329  * Completion handler for driver's RAS MBX command to the device.
6330  **/
6331 static void
6332 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6333 {
6334 	MAILBOX_t *mb;
6335 	union lpfc_sli4_cfg_shdr *shdr;
6336 	uint32_t shdr_status, shdr_add_status;
6337 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6338 
6339 	mb = &pmb->u.mb;
6340 
6341 	shdr = (union lpfc_sli4_cfg_shdr *)
6342 		&pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6343 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6344 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6345 
6346 	if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6347 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
6348 				"6188 FW LOG mailbox "
6349 				"completed with status x%x add_status x%x,"
6350 				" mbx status x%x\n",
6351 				shdr_status, shdr_add_status, mb->mbxStatus);
6352 
6353 		ras_fwlog->ras_hwsupport = false;
6354 		goto disable_ras;
6355 	}
6356 
6357 	ras_fwlog->ras_active = true;
6358 	mempool_free(pmb, phba->mbox_mem_pool);
6359 
6360 	return;
6361 
6362 disable_ras:
6363 	/* Free RAS DMA memory */
6364 	lpfc_sli4_ras_dma_free(phba);
6365 	mempool_free(pmb, phba->mbox_mem_pool);
6366 }
6367 
6368 /**
6369  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
6370  * @phba: pointer to lpfc hba data structure.
6371  * @fwlog_level: Logging verbosity level.
6372  * @fwlog_enable: Enable/Disable logging.
6373  *
6374  * Initialize memory and post mailbox command to enable FW logging in host
6375  * memory.
6376  **/
6377 int
6378 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
6379 			 uint32_t fwlog_level,
6380 			 uint32_t fwlog_enable)
6381 {
6382 	struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6383 	struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
6384 	struct lpfc_dmabuf *dmabuf;
6385 	LPFC_MBOXQ_t *mbox;
6386 	uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
6387 	int rc = 0;
6388 
6389 	fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
6390 			  phba->cfg_ras_fwlog_buffsize);
6391 	fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
6392 
6393 	/*
6394 	 * If re-enabling FW logging support use earlier allocated
6395 	 * DMA buffers while posting MBX command.
6396 	 **/
6397 	if (!ras_fwlog->lwpd.virt) {
6398 		rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
6399 		if (rc) {
6400 			lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6401 					"6189 FW Log Memory Allocation Failed");
6402 			return rc;
6403 		}
6404 	}
6405 
6406 	/* Setup Mailbox command */
6407 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6408 	if (!mbox) {
6409 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6410 				"6190 RAS MBX Alloc Failed");
6411 		rc = -ENOMEM;
6412 		goto mem_free;
6413 	}
6414 
6415 	ras_fwlog->fw_loglevel = fwlog_level;
6416 	len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
6417 		sizeof(struct lpfc_sli4_cfg_mhdr));
6418 
6419 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
6420 			 LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
6421 			 len, LPFC_SLI4_MBX_EMBED);
6422 
6423 	mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
6424 	bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
6425 	       fwlog_enable);
6426 	bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
6427 	       ras_fwlog->fw_loglevel);
6428 	bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
6429 	       ras_fwlog->fw_buffcount);
6430 	bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
6431 	       LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
6432 
6433 	/* Update DMA buffer address */
6434 	list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
6435 		memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
6436 
6437 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
6438 			putPaddrLow(dmabuf->phys);
6439 
6440 		mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
6441 			putPaddrHigh(dmabuf->phys);
6442 	}
6443 
6444 	/* Update LPWD address */
6445 	mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
6446 	mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
6447 
6448 	mbox->vport = phba->pport;
6449 	mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
6450 
6451 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
6452 
6453 	if (rc == MBX_NOT_FINISHED) {
6454 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6455 				"6191 FW-Log Mailbox failed. "
6456 				"status %d mbxStatus : x%x", rc,
6457 				bf_get(lpfc_mqe_status, &mbox->u.mqe));
6458 		mempool_free(mbox, phba->mbox_mem_pool);
6459 		rc = -EIO;
6460 		goto mem_free;
6461 	} else
6462 		rc = 0;
6463 mem_free:
6464 	if (rc)
6465 		lpfc_sli4_ras_dma_free(phba);
6466 
6467 	return rc;
6468 }
6469 
6470 /**
6471  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
6472  * @phba: Pointer to HBA context object.
6473  *
6474  * Check if RAS is supported on the adapter and initialize it.
6475  **/
6476 void
6477 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
6478 {
6479 	/* Check RAS FW Log needs to be enabled or not */
6480 	if (lpfc_check_fwlog_support(phba))
6481 		return;
6482 
6483 	lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
6484 				 LPFC_RAS_ENABLE_LOGGING);
6485 }
6486 
6487 /**
6488  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
6489  * @phba: Pointer to HBA context object.
6490  *
6491  * This function allocates all SLI4 resource identifiers.
6492  **/
6493 int
6494 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
6495 {
6496 	int i, rc, error = 0;
6497 	uint16_t count, base;
6498 	unsigned long longs;
6499 
6500 	if (!phba->sli4_hba.rpi_hdrs_in_use)
6501 		phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
6502 	if (phba->sli4_hba.extents_in_use) {
6503 		/*
6504 		 * The port supports resource extents. The XRI, VPI, VFI, RPI
6505 		 * resource extent count must be read and allocated before
6506 		 * provisioning the resource id arrays.
6507 		 */
6508 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6509 		    LPFC_IDX_RSRC_RDY) {
6510 			/*
6511 			 * Extent-based resources are set - the driver could
6512 			 * be in a port reset. Figure out if any corrective
6513 			 * actions need to be taken.
6514 			 */
6515 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6516 						 LPFC_RSC_TYPE_FCOE_VFI);
6517 			if (rc != 0)
6518 				error++;
6519 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6520 						 LPFC_RSC_TYPE_FCOE_VPI);
6521 			if (rc != 0)
6522 				error++;
6523 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6524 						 LPFC_RSC_TYPE_FCOE_XRI);
6525 			if (rc != 0)
6526 				error++;
6527 			rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6528 						 LPFC_RSC_TYPE_FCOE_RPI);
6529 			if (rc != 0)
6530 				error++;
6531 
6532 			/*
6533 			 * It's possible that the number of resources
6534 			 * provided to this port instance changed between
6535 			 * resets.  Detect this condition and reallocate
6536 			 * resources.  Otherwise, there is no action.
6537 			 */
6538 			if (error) {
6539 				lpfc_printf_log(phba, KERN_INFO,
6540 						LOG_MBOX | LOG_INIT,
6541 						"2931 Detected extent resource "
6542 						"change.  Reallocating all "
6543 						"extents.\n");
6544 				rc = lpfc_sli4_dealloc_extent(phba,
6545 						 LPFC_RSC_TYPE_FCOE_VFI);
6546 				rc = lpfc_sli4_dealloc_extent(phba,
6547 						 LPFC_RSC_TYPE_FCOE_VPI);
6548 				rc = lpfc_sli4_dealloc_extent(phba,
6549 						 LPFC_RSC_TYPE_FCOE_XRI);
6550 				rc = lpfc_sli4_dealloc_extent(phba,
6551 						 LPFC_RSC_TYPE_FCOE_RPI);
6552 			} else
6553 				return 0;
6554 		}
6555 
6556 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
6557 		if (unlikely(rc))
6558 			goto err_exit;
6559 
6560 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
6561 		if (unlikely(rc))
6562 			goto err_exit;
6563 
6564 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
6565 		if (unlikely(rc))
6566 			goto err_exit;
6567 
6568 		rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
6569 		if (unlikely(rc))
6570 			goto err_exit;
6571 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6572 		       LPFC_IDX_RSRC_RDY);
6573 		return rc;
6574 	} else {
6575 		/*
6576 		 * The port does not support resource extents.  The XRI, VPI,
6577 		 * VFI, RPI resource ids were determined from READ_CONFIG.
6578 		 * Just allocate the bitmasks and provision the resource id
6579 		 * arrays.  If a port reset is active, the resources don't
6580 		 * need any action - just exit.
6581 		 */
6582 		if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6583 		    LPFC_IDX_RSRC_RDY) {
6584 			lpfc_sli4_dealloc_resource_identifiers(phba);
6585 			lpfc_sli4_remove_rpis(phba);
6586 		}
6587 		/* RPIs. */
6588 		count = phba->sli4_hba.max_cfg_param.max_rpi;
6589 		if (count <= 0) {
6590 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6591 					"3279 Invalid provisioning of "
6592 					"rpi:%d\n", count);
6593 			rc = -EINVAL;
6594 			goto err_exit;
6595 		}
6596 		base = phba->sli4_hba.max_cfg_param.rpi_base;
6597 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6598 		phba->sli4_hba.rpi_bmask = kcalloc(longs,
6599 						   sizeof(unsigned long),
6600 						   GFP_KERNEL);
6601 		if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6602 			rc = -ENOMEM;
6603 			goto err_exit;
6604 		}
6605 		phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
6606 						 GFP_KERNEL);
6607 		if (unlikely(!phba->sli4_hba.rpi_ids)) {
6608 			rc = -ENOMEM;
6609 			goto free_rpi_bmask;
6610 		}
6611 
6612 		for (i = 0; i < count; i++)
6613 			phba->sli4_hba.rpi_ids[i] = base + i;
6614 
6615 		/* VPIs. */
6616 		count = phba->sli4_hba.max_cfg_param.max_vpi;
6617 		if (count <= 0) {
6618 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6619 					"3280 Invalid provisioning of "
6620 					"vpi:%d\n", count);
6621 			rc = -EINVAL;
6622 			goto free_rpi_ids;
6623 		}
6624 		base = phba->sli4_hba.max_cfg_param.vpi_base;
6625 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6626 		phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6627 					  GFP_KERNEL);
6628 		if (unlikely(!phba->vpi_bmask)) {
6629 			rc = -ENOMEM;
6630 			goto free_rpi_ids;
6631 		}
6632 		phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
6633 					GFP_KERNEL);
6634 		if (unlikely(!phba->vpi_ids)) {
6635 			rc = -ENOMEM;
6636 			goto free_vpi_bmask;
6637 		}
6638 
6639 		for (i = 0; i < count; i++)
6640 			phba->vpi_ids[i] = base + i;
6641 
6642 		/* XRIs. */
6643 		count = phba->sli4_hba.max_cfg_param.max_xri;
6644 		if (count <= 0) {
6645 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6646 					"3281 Invalid provisioning of "
6647 					"xri:%d\n", count);
6648 			rc = -EINVAL;
6649 			goto free_vpi_ids;
6650 		}
6651 		base = phba->sli4_hba.max_cfg_param.xri_base;
6652 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6653 		phba->sli4_hba.xri_bmask = kcalloc(longs,
6654 						   sizeof(unsigned long),
6655 						   GFP_KERNEL);
6656 		if (unlikely(!phba->sli4_hba.xri_bmask)) {
6657 			rc = -ENOMEM;
6658 			goto free_vpi_ids;
6659 		}
6660 		phba->sli4_hba.max_cfg_param.xri_used = 0;
6661 		phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
6662 						 GFP_KERNEL);
6663 		if (unlikely(!phba->sli4_hba.xri_ids)) {
6664 			rc = -ENOMEM;
6665 			goto free_xri_bmask;
6666 		}
6667 
6668 		for (i = 0; i < count; i++)
6669 			phba->sli4_hba.xri_ids[i] = base + i;
6670 
6671 		/* VFIs. */
6672 		count = phba->sli4_hba.max_cfg_param.max_vfi;
6673 		if (count <= 0) {
6674 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6675 					"3282 Invalid provisioning of "
6676 					"vfi:%d\n", count);
6677 			rc = -EINVAL;
6678 			goto free_xri_ids;
6679 		}
6680 		base = phba->sli4_hba.max_cfg_param.vfi_base;
6681 		longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6682 		phba->sli4_hba.vfi_bmask = kcalloc(longs,
6683 						   sizeof(unsigned long),
6684 						   GFP_KERNEL);
6685 		if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6686 			rc = -ENOMEM;
6687 			goto free_xri_ids;
6688 		}
6689 		phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
6690 						 GFP_KERNEL);
6691 		if (unlikely(!phba->sli4_hba.vfi_ids)) {
6692 			rc = -ENOMEM;
6693 			goto free_vfi_bmask;
6694 		}
6695 
6696 		for (i = 0; i < count; i++)
6697 			phba->sli4_hba.vfi_ids[i] = base + i;
6698 
6699 		/*
6700 		 * Mark all resources ready.  An HBA reset doesn't need
6701 		 * to reset the initialization.
6702 		 */
6703 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6704 		       LPFC_IDX_RSRC_RDY);
6705 		return 0;
6706 	}
6707 
6708  free_vfi_bmask:
6709 	kfree(phba->sli4_hba.vfi_bmask);
6710 	phba->sli4_hba.vfi_bmask = NULL;
6711  free_xri_ids:
6712 	kfree(phba->sli4_hba.xri_ids);
6713 	phba->sli4_hba.xri_ids = NULL;
6714  free_xri_bmask:
6715 	kfree(phba->sli4_hba.xri_bmask);
6716 	phba->sli4_hba.xri_bmask = NULL;
6717  free_vpi_ids:
6718 	kfree(phba->vpi_ids);
6719 	phba->vpi_ids = NULL;
6720  free_vpi_bmask:
6721 	kfree(phba->vpi_bmask);
6722 	phba->vpi_bmask = NULL;
6723  free_rpi_ids:
6724 	kfree(phba->sli4_hba.rpi_ids);
6725 	phba->sli4_hba.rpi_ids = NULL;
6726  free_rpi_bmask:
6727 	kfree(phba->sli4_hba.rpi_bmask);
6728 	phba->sli4_hba.rpi_bmask = NULL;
6729  err_exit:
6730 	return rc;
6731 }
6732 
6733 /**
6734  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
6735  * @phba: Pointer to HBA context object.
6736  *
6737  * This function allocates the number of elements for the specified
6738  * resource type.
6739  **/
6740 int
6741 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
6742 {
6743 	if (phba->sli4_hba.extents_in_use) {
6744 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
6745 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
6746 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
6747 		lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
6748 	} else {
6749 		kfree(phba->vpi_bmask);
6750 		phba->sli4_hba.max_cfg_param.vpi_used = 0;
6751 		kfree(phba->vpi_ids);
6752 		bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6753 		kfree(phba->sli4_hba.xri_bmask);
6754 		kfree(phba->sli4_hba.xri_ids);
6755 		kfree(phba->sli4_hba.vfi_bmask);
6756 		kfree(phba->sli4_hba.vfi_ids);
6757 		bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6758 		bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6759 	}
6760 
6761 	return 0;
6762 }
6763 
6764 /**
6765  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
6766  * @phba: Pointer to HBA context object.
6767  * @type: The resource extent type.
6768  * @extnt_count: buffer to hold port extent count response
6769  * @extnt_size: buffer to hold port extent size response.
6770  *
6771  * This function calls the port to read the host allocated extents
6772  * for a particular type.
6773  **/
6774 int
6775 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
6776 			       uint16_t *extnt_cnt, uint16_t *extnt_size)
6777 {
6778 	bool emb;
6779 	int rc = 0;
6780 	uint16_t curr_blks = 0;
6781 	uint32_t req_len, emb_len;
6782 	uint32_t alloc_len, mbox_tmo;
6783 	struct list_head *blk_list_head;
6784 	struct lpfc_rsrc_blks *rsrc_blk;
6785 	LPFC_MBOXQ_t *mbox;
6786 	void *virtaddr = NULL;
6787 	struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6788 	struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6789 	union  lpfc_sli4_cfg_shdr *shdr;
6790 
6791 	switch (type) {
6792 	case LPFC_RSC_TYPE_FCOE_VPI:
6793 		blk_list_head = &phba->lpfc_vpi_blk_list;
6794 		break;
6795 	case LPFC_RSC_TYPE_FCOE_XRI:
6796 		blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
6797 		break;
6798 	case LPFC_RSC_TYPE_FCOE_VFI:
6799 		blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
6800 		break;
6801 	case LPFC_RSC_TYPE_FCOE_RPI:
6802 		blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
6803 		break;
6804 	default:
6805 		return -EIO;
6806 	}
6807 
6808 	/* Count the number of extents currently allocatd for this type. */
6809 	list_for_each_entry(rsrc_blk, blk_list_head, list) {
6810 		if (curr_blks == 0) {
6811 			/*
6812 			 * The GET_ALLOCATED mailbox does not return the size,
6813 			 * just the count.  The size should be just the size
6814 			 * stored in the current allocated block and all sizes
6815 			 * for an extent type are the same so set the return
6816 			 * value now.
6817 			 */
6818 			*extnt_size = rsrc_blk->rsrc_size;
6819 		}
6820 		curr_blks++;
6821 	}
6822 
6823 	/*
6824 	 * Calculate the size of an embedded mailbox.  The uint32_t
6825 	 * accounts for extents-specific word.
6826 	 */
6827 	emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6828 		sizeof(uint32_t);
6829 
6830 	/*
6831 	 * Presume the allocation and response will fit into an embedded
6832 	 * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6833 	 */
6834 	emb = LPFC_SLI4_MBX_EMBED;
6835 	req_len = emb_len;
6836 	if (req_len > emb_len) {
6837 		req_len = curr_blks * sizeof(uint16_t) +
6838 			sizeof(union lpfc_sli4_cfg_shdr) +
6839 			sizeof(uint32_t);
6840 		emb = LPFC_SLI4_MBX_NEMBED;
6841 	}
6842 
6843 	mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6844 	if (!mbox)
6845 		return -ENOMEM;
6846 	memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
6847 
6848 	alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6849 				     LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
6850 				     req_len, emb);
6851 	if (alloc_len < req_len) {
6852 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6853 			"2983 Allocated DMA memory size (x%x) is "
6854 			"less than the requested DMA memory "
6855 			"size (x%x)\n", alloc_len, req_len);
6856 		rc = -ENOMEM;
6857 		goto err_exit;
6858 	}
6859 	rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
6860 	if (unlikely(rc)) {
6861 		rc = -EIO;
6862 		goto err_exit;
6863 	}
6864 
6865 	if (!phba->sli4_hba.intr_enable)
6866 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6867 	else {
6868 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6869 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6870 	}
6871 
6872 	if (unlikely(rc)) {
6873 		rc = -EIO;
6874 		goto err_exit;
6875 	}
6876 
6877 	/*
6878 	 * Figure out where the response is located.  Then get local pointers
6879 	 * to the response data.  The port does not guarantee to respond to
6880 	 * all extents counts request so update the local variable with the
6881 	 * allocated count from the port.
6882 	 */
6883 	if (emb == LPFC_SLI4_MBX_EMBED) {
6884 		rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6885 		shdr = &rsrc_ext->header.cfg_shdr;
6886 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6887 	} else {
6888 		virtaddr = mbox->sge_array->addr[0];
6889 		n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6890 		shdr = &n_rsrc->cfg_shdr;
6891 		*extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6892 	}
6893 
6894 	if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
6895 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
6896 			"2984 Failed to read allocated resources "
6897 			"for type %d - Status 0x%x Add'l Status 0x%x.\n",
6898 			type,
6899 			bf_get(lpfc_mbox_hdr_status, &shdr->response),
6900 			bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
6901 		rc = -EIO;
6902 		goto err_exit;
6903 	}
6904  err_exit:
6905 	lpfc_sli4_mbox_cmd_free(phba, mbox);
6906 	return rc;
6907 }
6908 
6909 /**
6910  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
6911  * @phba: pointer to lpfc hba data structure.
6912  * @pring: Pointer to driver SLI ring object.
6913  * @sgl_list: linked link of sgl buffers to post
6914  * @cnt: number of linked list buffers
6915  *
6916  * This routine walks the list of buffers that have been allocated and
6917  * repost them to the port by using SGL block post. This is needed after a
6918  * pci_function_reset/warm_start or start. It attempts to construct blocks
6919  * of buffer sgls which contains contiguous xris and uses the non-embedded
6920  * SGL block post mailbox commands to post them to the port. For single
6921  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
6922  * mailbox command for posting.
6923  *
6924  * Returns: 0 = success, non-zero failure.
6925  **/
6926 static int
6927 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
6928 			  struct list_head *sgl_list, int cnt)
6929 {
6930 	struct lpfc_sglq *sglq_entry = NULL;
6931 	struct lpfc_sglq *sglq_entry_next = NULL;
6932 	struct lpfc_sglq *sglq_entry_first = NULL;
6933 	int status, total_cnt;
6934 	int post_cnt = 0, num_posted = 0, block_cnt = 0;
6935 	int last_xritag = NO_XRI;
6936 	LIST_HEAD(prep_sgl_list);
6937 	LIST_HEAD(blck_sgl_list);
6938 	LIST_HEAD(allc_sgl_list);
6939 	LIST_HEAD(post_sgl_list);
6940 	LIST_HEAD(free_sgl_list);
6941 
6942 	spin_lock_irq(&phba->hbalock);
6943 	spin_lock(&phba->sli4_hba.sgl_list_lock);
6944 	list_splice_init(sgl_list, &allc_sgl_list);
6945 	spin_unlock(&phba->sli4_hba.sgl_list_lock);
6946 	spin_unlock_irq(&phba->hbalock);
6947 
6948 	total_cnt = cnt;
6949 	list_for_each_entry_safe(sglq_entry, sglq_entry_next,
6950 				 &allc_sgl_list, list) {
6951 		list_del_init(&sglq_entry->list);
6952 		block_cnt++;
6953 		if ((last_xritag != NO_XRI) &&
6954 		    (sglq_entry->sli4_xritag != last_xritag + 1)) {
6955 			/* a hole in xri block, form a sgl posting block */
6956 			list_splice_init(&prep_sgl_list, &blck_sgl_list);
6957 			post_cnt = block_cnt - 1;
6958 			/* prepare list for next posting block */
6959 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
6960 			block_cnt = 1;
6961 		} else {
6962 			/* prepare list for next posting block */
6963 			list_add_tail(&sglq_entry->list, &prep_sgl_list);
6964 			/* enough sgls for non-embed sgl mbox command */
6965 			if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
6966 				list_splice_init(&prep_sgl_list,
6967 						 &blck_sgl_list);
6968 				post_cnt = block_cnt;
6969 				block_cnt = 0;
6970 			}
6971 		}
6972 		num_posted++;
6973 
6974 		/* keep track of last sgl's xritag */
6975 		last_xritag = sglq_entry->sli4_xritag;
6976 
6977 		/* end of repost sgl list condition for buffers */
6978 		if (num_posted == total_cnt) {
6979 			if (post_cnt == 0) {
6980 				list_splice_init(&prep_sgl_list,
6981 						 &blck_sgl_list);
6982 				post_cnt = block_cnt;
6983 			} else if (block_cnt == 1) {
6984 				status = lpfc_sli4_post_sgl(phba,
6985 						sglq_entry->phys, 0,
6986 						sglq_entry->sli4_xritag);
6987 				if (!status) {
6988 					/* successful, put sgl to posted list */
6989 					list_add_tail(&sglq_entry->list,
6990 						      &post_sgl_list);
6991 				} else {
6992 					/* Failure, put sgl to free list */
6993 					lpfc_printf_log(phba, KERN_WARNING,
6994 						LOG_SLI,
6995 						"3159 Failed to post "
6996 						"sgl, xritag:x%x\n",
6997 						sglq_entry->sli4_xritag);
6998 					list_add_tail(&sglq_entry->list,
6999 						      &free_sgl_list);
7000 					total_cnt--;
7001 				}
7002 			}
7003 		}
7004 
7005 		/* continue until a nembed page worth of sgls */
7006 		if (post_cnt == 0)
7007 			continue;
7008 
7009 		/* post the buffer list sgls as a block */
7010 		status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7011 						 post_cnt);
7012 
7013 		if (!status) {
7014 			/* success, put sgl list to posted sgl list */
7015 			list_splice_init(&blck_sgl_list, &post_sgl_list);
7016 		} else {
7017 			/* Failure, put sgl list to free sgl list */
7018 			sglq_entry_first = list_first_entry(&blck_sgl_list,
7019 							    struct lpfc_sglq,
7020 							    list);
7021 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7022 					"3160 Failed to post sgl-list, "
7023 					"xritag:x%x-x%x\n",
7024 					sglq_entry_first->sli4_xritag,
7025 					(sglq_entry_first->sli4_xritag +
7026 					 post_cnt - 1));
7027 			list_splice_init(&blck_sgl_list, &free_sgl_list);
7028 			total_cnt -= post_cnt;
7029 		}
7030 
7031 		/* don't reset xirtag due to hole in xri block */
7032 		if (block_cnt == 0)
7033 			last_xritag = NO_XRI;
7034 
7035 		/* reset sgl post count for next round of posting */
7036 		post_cnt = 0;
7037 	}
7038 
7039 	/* free the sgls failed to post */
7040 	lpfc_free_sgl_list(phba, &free_sgl_list);
7041 
7042 	/* push sgls posted to the available list */
7043 	if (!list_empty(&post_sgl_list)) {
7044 		spin_lock_irq(&phba->hbalock);
7045 		spin_lock(&phba->sli4_hba.sgl_list_lock);
7046 		list_splice_init(&post_sgl_list, sgl_list);
7047 		spin_unlock(&phba->sli4_hba.sgl_list_lock);
7048 		spin_unlock_irq(&phba->hbalock);
7049 	} else {
7050 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7051 				"3161 Failure to post sgl to port.\n");
7052 		return -EIO;
7053 	}
7054 
7055 	/* return the number of XRIs actually posted */
7056 	return total_cnt;
7057 }
7058 
7059 void
7060 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7061 {
7062 	uint32_t len;
7063 
7064 	len = sizeof(struct lpfc_mbx_set_host_data) -
7065 		sizeof(struct lpfc_sli4_cfg_mhdr);
7066 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7067 			 LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7068 			 LPFC_SLI4_MBX_EMBED);
7069 
7070 	mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7071 	mbox->u.mqe.un.set_host_data.param_len =
7072 					LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7073 	snprintf(mbox->u.mqe.un.set_host_data.data,
7074 		 LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7075 		 "Linux %s v"LPFC_DRIVER_VERSION,
7076 		 (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7077 }
7078 
7079 int
7080 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7081 		    struct lpfc_queue *drq, int count, int idx)
7082 {
7083 	int rc, i;
7084 	struct lpfc_rqe hrqe;
7085 	struct lpfc_rqe drqe;
7086 	struct lpfc_rqb *rqbp;
7087 	unsigned long flags;
7088 	struct rqb_dmabuf *rqb_buffer;
7089 	LIST_HEAD(rqb_buf_list);
7090 
7091 	spin_lock_irqsave(&phba->hbalock, flags);
7092 	rqbp = hrq->rqbp;
7093 	for (i = 0; i < count; i++) {
7094 		/* IF RQ is already full, don't bother */
7095 		if (rqbp->buffer_count + i >= rqbp->entry_count - 1)
7096 			break;
7097 		rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7098 		if (!rqb_buffer)
7099 			break;
7100 		rqb_buffer->hrq = hrq;
7101 		rqb_buffer->drq = drq;
7102 		rqb_buffer->idx = idx;
7103 		list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7104 	}
7105 	while (!list_empty(&rqb_buf_list)) {
7106 		list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7107 				 hbuf.list);
7108 
7109 		hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7110 		hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7111 		drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7112 		drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7113 		rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7114 		if (rc < 0) {
7115 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7116 					"6421 Cannot post to HRQ %d: %x %x %x "
7117 					"DRQ %x %x\n",
7118 					hrq->queue_id,
7119 					hrq->host_index,
7120 					hrq->hba_index,
7121 					hrq->entry_count,
7122 					drq->host_index,
7123 					drq->hba_index);
7124 			rqbp->rqb_free_buffer(phba, rqb_buffer);
7125 		} else {
7126 			list_add_tail(&rqb_buffer->hbuf.list,
7127 				      &rqbp->rqb_buffer_list);
7128 			rqbp->buffer_count++;
7129 		}
7130 	}
7131 	spin_unlock_irqrestore(&phba->hbalock, flags);
7132 	return 1;
7133 }
7134 
7135 /**
7136  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
7137  * @phba: Pointer to HBA context object.
7138  *
7139  * This function is the main SLI4 device initialization PCI function. This
7140  * function is called by the HBA initialization code, HBA reset code and
7141  * HBA error attention handler code. Caller is not required to hold any
7142  * locks.
7143  **/
7144 int
7145 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
7146 {
7147 	int rc, i, cnt;
7148 	LPFC_MBOXQ_t *mboxq;
7149 	struct lpfc_mqe *mqe;
7150 	uint8_t *vpd;
7151 	uint32_t vpd_size;
7152 	uint32_t ftr_rsp = 0;
7153 	struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
7154 	struct lpfc_vport *vport = phba->pport;
7155 	struct lpfc_dmabuf *mp;
7156 	struct lpfc_rqb *rqbp;
7157 
7158 	/* Perform a PCI function reset to start from clean */
7159 	rc = lpfc_pci_function_reset(phba);
7160 	if (unlikely(rc))
7161 		return -ENODEV;
7162 
7163 	/* Check the HBA Host Status Register for readyness */
7164 	rc = lpfc_sli4_post_status_check(phba);
7165 	if (unlikely(rc))
7166 		return -ENODEV;
7167 	else {
7168 		spin_lock_irq(&phba->hbalock);
7169 		phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
7170 		spin_unlock_irq(&phba->hbalock);
7171 	}
7172 
7173 	/*
7174 	 * Allocate a single mailbox container for initializing the
7175 	 * port.
7176 	 */
7177 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7178 	if (!mboxq)
7179 		return -ENOMEM;
7180 
7181 	/* Issue READ_REV to collect vpd and FW information. */
7182 	vpd_size = SLI4_PAGE_SIZE;
7183 	vpd = kzalloc(vpd_size, GFP_KERNEL);
7184 	if (!vpd) {
7185 		rc = -ENOMEM;
7186 		goto out_free_mbox;
7187 	}
7188 
7189 	rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
7190 	if (unlikely(rc)) {
7191 		kfree(vpd);
7192 		goto out_free_mbox;
7193 	}
7194 
7195 	mqe = &mboxq->u.mqe;
7196 	phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
7197 	if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
7198 		phba->hba_flag |= HBA_FCOE_MODE;
7199 		phba->fcp_embed_io = 0;	/* SLI4 FC support only */
7200 	} else {
7201 		phba->hba_flag &= ~HBA_FCOE_MODE;
7202 	}
7203 
7204 	if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
7205 		LPFC_DCBX_CEE_MODE)
7206 		phba->hba_flag |= HBA_FIP_SUPPORT;
7207 	else
7208 		phba->hba_flag &= ~HBA_FIP_SUPPORT;
7209 
7210 	phba->hba_flag &= ~HBA_FCP_IOQ_FLUSH;
7211 
7212 	if (phba->sli_rev != LPFC_SLI_REV4) {
7213 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7214 			"0376 READ_REV Error. SLI Level %d "
7215 			"FCoE enabled %d\n",
7216 			phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
7217 		rc = -EIO;
7218 		kfree(vpd);
7219 		goto out_free_mbox;
7220 	}
7221 
7222 	/*
7223 	 * Continue initialization with default values even if driver failed
7224 	 * to read FCoE param config regions, only read parameters if the
7225 	 * board is FCoE
7226 	 */
7227 	if (phba->hba_flag & HBA_FCOE_MODE &&
7228 	    lpfc_sli4_read_fcoe_params(phba))
7229 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
7230 			"2570 Failed to read FCoE parameters\n");
7231 
7232 	/*
7233 	 * Retrieve sli4 device physical port name, failure of doing it
7234 	 * is considered as non-fatal.
7235 	 */
7236 	rc = lpfc_sli4_retrieve_pport_name(phba);
7237 	if (!rc)
7238 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7239 				"3080 Successful retrieving SLI4 device "
7240 				"physical port name: %s.\n", phba->Port);
7241 
7242 	/*
7243 	 * Evaluate the read rev and vpd data. Populate the driver
7244 	 * state with the results. If this routine fails, the failure
7245 	 * is not fatal as the driver will use generic values.
7246 	 */
7247 	rc = lpfc_parse_vpd(phba, vpd, vpd_size);
7248 	if (unlikely(!rc)) {
7249 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7250 				"0377 Error %d parsing vpd. "
7251 				"Using defaults.\n", rc);
7252 		rc = 0;
7253 	}
7254 	kfree(vpd);
7255 
7256 	/* Save information as VPD data */
7257 	phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
7258 	phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
7259 
7260 	/*
7261 	 * This is because first G7 ASIC doesn't support the standard
7262 	 * 0x5a NVME cmd descriptor type/subtype
7263 	 */
7264 	if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7265 			LPFC_SLI_INTF_IF_TYPE_6) &&
7266 	    (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
7267 	    (phba->vpd.rev.smRev == 0) &&
7268 	    (phba->cfg_nvme_embed_cmd == 1))
7269 		phba->cfg_nvme_embed_cmd = 0;
7270 
7271 	phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
7272 	phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
7273 					 &mqe->un.read_rev);
7274 	phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
7275 				       &mqe->un.read_rev);
7276 	phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
7277 					    &mqe->un.read_rev);
7278 	phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
7279 					   &mqe->un.read_rev);
7280 	phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
7281 	memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
7282 	phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
7283 	memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
7284 	phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
7285 	memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
7286 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7287 			"(%d):0380 READ_REV Status x%x "
7288 			"fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
7289 			mboxq->vport ? mboxq->vport->vpi : 0,
7290 			bf_get(lpfc_mqe_status, mqe),
7291 			phba->vpd.rev.opFwName,
7292 			phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
7293 			phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
7294 
7295 	/* Reset the DFT_LUN_Q_DEPTH to (max xri >> 3)  */
7296 	rc = (phba->sli4_hba.max_cfg_param.max_xri >> 3);
7297 	if (phba->pport->cfg_lun_queue_depth > rc) {
7298 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7299 				"3362 LUN queue depth changed from %d to %d\n",
7300 				phba->pport->cfg_lun_queue_depth, rc);
7301 		phba->pport->cfg_lun_queue_depth = rc;
7302 	}
7303 
7304 	if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7305 	    LPFC_SLI_INTF_IF_TYPE_0) {
7306 		lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
7307 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7308 		if (rc == MBX_SUCCESS) {
7309 			phba->hba_flag |= HBA_RECOVERABLE_UE;
7310 			/* Set 1Sec interval to detect UE */
7311 			phba->eratt_poll_interval = 1;
7312 			phba->sli4_hba.ue_to_sr = bf_get(
7313 					lpfc_mbx_set_feature_UESR,
7314 					&mboxq->u.mqe.un.set_feature);
7315 			phba->sli4_hba.ue_to_rp = bf_get(
7316 					lpfc_mbx_set_feature_UERP,
7317 					&mboxq->u.mqe.un.set_feature);
7318 		}
7319 	}
7320 
7321 	if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
7322 		/* Enable MDS Diagnostics only if the SLI Port supports it */
7323 		lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
7324 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7325 		if (rc != MBX_SUCCESS)
7326 			phba->mds_diags_support = 0;
7327 	}
7328 
7329 	/*
7330 	 * Discover the port's supported feature set and match it against the
7331 	 * hosts requests.
7332 	 */
7333 	lpfc_request_features(phba, mboxq);
7334 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7335 	if (unlikely(rc)) {
7336 		rc = -EIO;
7337 		goto out_free_mbox;
7338 	}
7339 
7340 	/*
7341 	 * The port must support FCP initiator mode as this is the
7342 	 * only mode running in the host.
7343 	 */
7344 	if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
7345 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7346 				"0378 No support for fcpi mode.\n");
7347 		ftr_rsp++;
7348 	}
7349 
7350 	/* Performance Hints are ONLY for FCoE */
7351 	if (phba->hba_flag & HBA_FCOE_MODE) {
7352 		if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
7353 			phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
7354 		else
7355 			phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
7356 	}
7357 
7358 	/*
7359 	 * If the port cannot support the host's requested features
7360 	 * then turn off the global config parameters to disable the
7361 	 * feature in the driver.  This is not a fatal error.
7362 	 */
7363 	if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
7364 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
7365 			phba->cfg_enable_bg = 0;
7366 			phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
7367 			ftr_rsp++;
7368 		}
7369 	}
7370 
7371 	if (phba->max_vpi && phba->cfg_enable_npiv &&
7372 	    !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7373 		ftr_rsp++;
7374 
7375 	if (ftr_rsp) {
7376 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7377 				"0379 Feature Mismatch Data: x%08x %08x "
7378 				"x%x x%x x%x\n", mqe->un.req_ftrs.word2,
7379 				mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
7380 				phba->cfg_enable_npiv, phba->max_vpi);
7381 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
7382 			phba->cfg_enable_bg = 0;
7383 		if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7384 			phba->cfg_enable_npiv = 0;
7385 	}
7386 
7387 	/* These SLI3 features are assumed in SLI4 */
7388 	spin_lock_irq(&phba->hbalock);
7389 	phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
7390 	spin_unlock_irq(&phba->hbalock);
7391 
7392 	/*
7393 	 * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
7394 	 * calls depends on these resources to complete port setup.
7395 	 */
7396 	rc = lpfc_sli4_alloc_resource_identifiers(phba);
7397 	if (rc) {
7398 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7399 				"2920 Failed to alloc Resource IDs "
7400 				"rc = x%x\n", rc);
7401 		goto out_free_mbox;
7402 	}
7403 
7404 	lpfc_set_host_data(phba, mboxq);
7405 
7406 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7407 	if (rc) {
7408 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7409 				"2134 Failed to set host os driver version %x",
7410 				rc);
7411 	}
7412 
7413 	/* Read the port's service parameters. */
7414 	rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
7415 	if (rc) {
7416 		phba->link_state = LPFC_HBA_ERROR;
7417 		rc = -ENOMEM;
7418 		goto out_free_mbox;
7419 	}
7420 
7421 	mboxq->vport = vport;
7422 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7423 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
7424 	if (rc == MBX_SUCCESS) {
7425 		memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
7426 		rc = 0;
7427 	}
7428 
7429 	/*
7430 	 * This memory was allocated by the lpfc_read_sparam routine. Release
7431 	 * it to the mbuf pool.
7432 	 */
7433 	lpfc_mbuf_free(phba, mp->virt, mp->phys);
7434 	kfree(mp);
7435 	mboxq->ctx_buf = NULL;
7436 	if (unlikely(rc)) {
7437 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7438 				"0382 READ_SPARAM command failed "
7439 				"status %d, mbxStatus x%x\n",
7440 				rc, bf_get(lpfc_mqe_status, mqe));
7441 		phba->link_state = LPFC_HBA_ERROR;
7442 		rc = -EIO;
7443 		goto out_free_mbox;
7444 	}
7445 
7446 	lpfc_update_vport_wwn(vport);
7447 
7448 	/* Update the fc_host data structures with new wwn. */
7449 	fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
7450 	fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
7451 
7452 	/* Create all the SLI4 queues */
7453 	rc = lpfc_sli4_queue_create(phba);
7454 	if (rc) {
7455 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7456 				"3089 Failed to allocate queues\n");
7457 		rc = -ENODEV;
7458 		goto out_free_mbox;
7459 	}
7460 	/* Set up all the queues to the device */
7461 	rc = lpfc_sli4_queue_setup(phba);
7462 	if (unlikely(rc)) {
7463 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7464 				"0381 Error %d during queue setup.\n ", rc);
7465 		goto out_stop_timers;
7466 	}
7467 	/* Initialize the driver internal SLI layer lists. */
7468 	lpfc_sli4_setup(phba);
7469 	lpfc_sli4_queue_init(phba);
7470 
7471 	/* update host els xri-sgl sizes and mappings */
7472 	rc = lpfc_sli4_els_sgl_update(phba);
7473 	if (unlikely(rc)) {
7474 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7475 				"1400 Failed to update xri-sgl size and "
7476 				"mapping: %d\n", rc);
7477 		goto out_destroy_queue;
7478 	}
7479 
7480 	/* register the els sgl pool to the port */
7481 	rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
7482 				       phba->sli4_hba.els_xri_cnt);
7483 	if (unlikely(rc < 0)) {
7484 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7485 				"0582 Error %d during els sgl post "
7486 				"operation\n", rc);
7487 		rc = -ENODEV;
7488 		goto out_destroy_queue;
7489 	}
7490 	phba->sli4_hba.els_xri_cnt = rc;
7491 
7492 	if (phba->nvmet_support) {
7493 		/* update host nvmet xri-sgl sizes and mappings */
7494 		rc = lpfc_sli4_nvmet_sgl_update(phba);
7495 		if (unlikely(rc)) {
7496 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7497 					"6308 Failed to update nvmet-sgl size "
7498 					"and mapping: %d\n", rc);
7499 			goto out_destroy_queue;
7500 		}
7501 
7502 		/* register the nvmet sgl pool to the port */
7503 		rc = lpfc_sli4_repost_sgl_list(
7504 			phba,
7505 			&phba->sli4_hba.lpfc_nvmet_sgl_list,
7506 			phba->sli4_hba.nvmet_xri_cnt);
7507 		if (unlikely(rc < 0)) {
7508 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7509 					"3117 Error %d during nvmet "
7510 					"sgl post\n", rc);
7511 			rc = -ENODEV;
7512 			goto out_destroy_queue;
7513 		}
7514 		phba->sli4_hba.nvmet_xri_cnt = rc;
7515 
7516 		cnt = phba->cfg_iocb_cnt * 1024;
7517 		/* We need 1 iocbq for every SGL, for IO processing */
7518 		cnt += phba->sli4_hba.nvmet_xri_cnt;
7519 	} else {
7520 		/* update host scsi xri-sgl sizes and mappings */
7521 		rc = lpfc_sli4_scsi_sgl_update(phba);
7522 		if (unlikely(rc)) {
7523 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7524 					"6309 Failed to update scsi-sgl size "
7525 					"and mapping: %d\n", rc);
7526 			goto out_destroy_queue;
7527 		}
7528 
7529 		/* update host nvme xri-sgl sizes and mappings */
7530 		rc = lpfc_sli4_nvme_sgl_update(phba);
7531 		if (unlikely(rc)) {
7532 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7533 					"6082 Failed to update nvme-sgl size "
7534 					"and mapping: %d\n", rc);
7535 			goto out_destroy_queue;
7536 		}
7537 
7538 		cnt = phba->cfg_iocb_cnt * 1024;
7539 	}
7540 
7541 	if (!phba->sli.iocbq_lookup) {
7542 		/* Initialize and populate the iocb list per host */
7543 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7544 				"2821 initialize iocb list %d total %d\n",
7545 				phba->cfg_iocb_cnt, cnt);
7546 		rc = lpfc_init_iocb_list(phba, cnt);
7547 		if (rc) {
7548 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7549 					"1413 Failed to init iocb list.\n");
7550 			goto out_destroy_queue;
7551 		}
7552 	}
7553 
7554 	if (phba->nvmet_support)
7555 		lpfc_nvmet_create_targetport(phba);
7556 
7557 	if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
7558 		/* Post initial buffers to all RQs created */
7559 		for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
7560 			rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
7561 			INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
7562 			rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
7563 			rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
7564 			rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
7565 			rqbp->buffer_count = 0;
7566 
7567 			lpfc_post_rq_buffer(
7568 				phba, phba->sli4_hba.nvmet_mrq_hdr[i],
7569 				phba->sli4_hba.nvmet_mrq_data[i],
7570 				phba->cfg_nvmet_mrq_post, i);
7571 		}
7572 	}
7573 
7574 	if (phba->cfg_enable_fc4_type & LPFC_ENABLE_FCP) {
7575 		/* register the allocated scsi sgl pool to the port */
7576 		rc = lpfc_sli4_repost_scsi_sgl_list(phba);
7577 		if (unlikely(rc)) {
7578 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7579 					"0383 Error %d during scsi sgl post "
7580 					"operation\n", rc);
7581 			/* Some Scsi buffers were moved to abort scsi list */
7582 			/* A pci function reset will repost them */
7583 			rc = -ENODEV;
7584 			goto out_destroy_queue;
7585 		}
7586 	}
7587 
7588 	if ((phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) &&
7589 	    (phba->nvmet_support == 0)) {
7590 
7591 		/* register the allocated nvme sgl pool to the port */
7592 		rc = lpfc_repost_nvme_sgl_list(phba);
7593 		if (unlikely(rc)) {
7594 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7595 					"6116 Error %d during nvme sgl post "
7596 					"operation\n", rc);
7597 			/* Some NVME buffers were moved to abort nvme list */
7598 			/* A pci function reset will repost them */
7599 			rc = -ENODEV;
7600 			goto out_destroy_queue;
7601 		}
7602 	}
7603 
7604 	/* Post the rpi header region to the device. */
7605 	rc = lpfc_sli4_post_all_rpi_hdrs(phba);
7606 	if (unlikely(rc)) {
7607 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7608 				"0393 Error %d during rpi post operation\n",
7609 				rc);
7610 		rc = -ENODEV;
7611 		goto out_destroy_queue;
7612 	}
7613 	lpfc_sli4_node_prep(phba);
7614 
7615 	if (!(phba->hba_flag & HBA_FCOE_MODE)) {
7616 		if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
7617 			/*
7618 			 * The FC Port needs to register FCFI (index 0)
7619 			 */
7620 			lpfc_reg_fcfi(phba, mboxq);
7621 			mboxq->vport = phba->pport;
7622 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7623 			if (rc != MBX_SUCCESS)
7624 				goto out_unset_queue;
7625 			rc = 0;
7626 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
7627 						&mboxq->u.mqe.un.reg_fcfi);
7628 		} else {
7629 			/* We are a NVME Target mode with MRQ > 1 */
7630 
7631 			/* First register the FCFI */
7632 			lpfc_reg_fcfi_mrq(phba, mboxq, 0);
7633 			mboxq->vport = phba->pport;
7634 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7635 			if (rc != MBX_SUCCESS)
7636 				goto out_unset_queue;
7637 			rc = 0;
7638 			phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
7639 						&mboxq->u.mqe.un.reg_fcfi_mrq);
7640 
7641 			/* Next register the MRQs */
7642 			lpfc_reg_fcfi_mrq(phba, mboxq, 1);
7643 			mboxq->vport = phba->pport;
7644 			rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7645 			if (rc != MBX_SUCCESS)
7646 				goto out_unset_queue;
7647 			rc = 0;
7648 		}
7649 		/* Check if the port is configured to be disabled */
7650 		lpfc_sli_read_link_ste(phba);
7651 	}
7652 
7653 	/* Arm the CQs and then EQs on device */
7654 	lpfc_sli4_arm_cqeq_intr(phba);
7655 
7656 	/* Indicate device interrupt mode */
7657 	phba->sli4_hba.intr_enable = 1;
7658 
7659 	/* Allow asynchronous mailbox command to go through */
7660 	spin_lock_irq(&phba->hbalock);
7661 	phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7662 	spin_unlock_irq(&phba->hbalock);
7663 
7664 	/* Post receive buffers to the device */
7665 	lpfc_sli4_rb_setup(phba);
7666 
7667 	/* Reset HBA FCF states after HBA reset */
7668 	phba->fcf.fcf_flag = 0;
7669 	phba->fcf.current_rec.flag = 0;
7670 
7671 	/* Start the ELS watchdog timer */
7672 	mod_timer(&vport->els_tmofunc,
7673 		  jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
7674 
7675 	/* Start heart beat timer */
7676 	mod_timer(&phba->hb_tmofunc,
7677 		  jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
7678 	phba->hb_outstanding = 0;
7679 	phba->last_completion_time = jiffies;
7680 
7681 	/* Start error attention (ERATT) polling timer */
7682 	mod_timer(&phba->eratt_poll,
7683 		  jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
7684 
7685 	/* Enable PCIe device Advanced Error Reporting (AER) if configured */
7686 	if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
7687 		rc = pci_enable_pcie_error_reporting(phba->pcidev);
7688 		if (!rc) {
7689 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7690 					"2829 This device supports "
7691 					"Advanced Error Reporting (AER)\n");
7692 			spin_lock_irq(&phba->hbalock);
7693 			phba->hba_flag |= HBA_AER_ENABLED;
7694 			spin_unlock_irq(&phba->hbalock);
7695 		} else {
7696 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7697 					"2830 This device does not support "
7698 					"Advanced Error Reporting (AER)\n");
7699 			phba->cfg_aer_support = 0;
7700 		}
7701 		rc = 0;
7702 	}
7703 
7704 	/*
7705 	 * The port is ready, set the host's link state to LINK_DOWN
7706 	 * in preparation for link interrupts.
7707 	 */
7708 	spin_lock_irq(&phba->hbalock);
7709 	phba->link_state = LPFC_LINK_DOWN;
7710 
7711 	/* Check if physical ports are trunked */
7712 	if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
7713 		phba->trunk_link.link0.state = LPFC_LINK_DOWN;
7714 	if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
7715 		phba->trunk_link.link1.state = LPFC_LINK_DOWN;
7716 	if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
7717 		phba->trunk_link.link2.state = LPFC_LINK_DOWN;
7718 	if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
7719 		phba->trunk_link.link3.state = LPFC_LINK_DOWN;
7720 	spin_unlock_irq(&phba->hbalock);
7721 
7722 	if (!(phba->hba_flag & HBA_FCOE_MODE) &&
7723 	    (phba->hba_flag & LINK_DISABLED)) {
7724 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
7725 				"3103 Adapter Link is disabled.\n");
7726 		lpfc_down_link(phba, mboxq);
7727 		rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7728 		if (rc != MBX_SUCCESS) {
7729 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
7730 					"3104 Adapter failed to issue "
7731 					"DOWN_LINK mbox cmd, rc:x%x\n", rc);
7732 			goto out_unset_queue;
7733 		}
7734 	} else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
7735 		/* don't perform init_link on SLI4 FC port loopback test */
7736 		if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
7737 			rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
7738 			if (rc)
7739 				goto out_unset_queue;
7740 		}
7741 	}
7742 	mempool_free(mboxq, phba->mbox_mem_pool);
7743 	return rc;
7744 out_unset_queue:
7745 	/* Unset all the queues set up in this routine when error out */
7746 	lpfc_sli4_queue_unset(phba);
7747 out_destroy_queue:
7748 	lpfc_free_iocb_list(phba);
7749 	lpfc_sli4_queue_destroy(phba);
7750 out_stop_timers:
7751 	lpfc_stop_hba_timers(phba);
7752 out_free_mbox:
7753 	mempool_free(mboxq, phba->mbox_mem_pool);
7754 	return rc;
7755 }
7756 
7757 /**
7758  * lpfc_mbox_timeout - Timeout call back function for mbox timer
7759  * @ptr: context object - pointer to hba structure.
7760  *
7761  * This is the callback function for mailbox timer. The mailbox
7762  * timer is armed when a new mailbox command is issued and the timer
7763  * is deleted when the mailbox complete. The function is called by
7764  * the kernel timer code when a mailbox does not complete within
7765  * expected time. This function wakes up the worker thread to
7766  * process the mailbox timeout and returns. All the processing is
7767  * done by the worker thread function lpfc_mbox_timeout_handler.
7768  **/
7769 void
7770 lpfc_mbox_timeout(struct timer_list *t)
7771 {
7772 	struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
7773 	unsigned long iflag;
7774 	uint32_t tmo_posted;
7775 
7776 	spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
7777 	tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
7778 	if (!tmo_posted)
7779 		phba->pport->work_port_events |= WORKER_MBOX_TMO;
7780 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
7781 
7782 	if (!tmo_posted)
7783 		lpfc_worker_wake_up(phba);
7784 	return;
7785 }
7786 
7787 /**
7788  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
7789  *                                    are pending
7790  * @phba: Pointer to HBA context object.
7791  *
7792  * This function checks if any mailbox completions are present on the mailbox
7793  * completion queue.
7794  **/
7795 static bool
7796 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
7797 {
7798 
7799 	uint32_t idx;
7800 	struct lpfc_queue *mcq;
7801 	struct lpfc_mcqe *mcqe;
7802 	bool pending_completions = false;
7803 	uint8_t	qe_valid;
7804 
7805 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
7806 		return false;
7807 
7808 	/* Check for completions on mailbox completion queue */
7809 
7810 	mcq = phba->sli4_hba.mbx_cq;
7811 	idx = mcq->hba_index;
7812 	qe_valid = mcq->qe_valid;
7813 	while (bf_get_le32(lpfc_cqe_valid, mcq->qe[idx].cqe) == qe_valid) {
7814 		mcqe = (struct lpfc_mcqe *)mcq->qe[idx].cqe;
7815 		if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
7816 		    (!bf_get_le32(lpfc_trailer_async, mcqe))) {
7817 			pending_completions = true;
7818 			break;
7819 		}
7820 		idx = (idx + 1) % mcq->entry_count;
7821 		if (mcq->hba_index == idx)
7822 			break;
7823 
7824 		/* if the index wrapped around, toggle the valid bit */
7825 		if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
7826 			qe_valid = (qe_valid) ? 0 : 1;
7827 	}
7828 	return pending_completions;
7829 
7830 }
7831 
7832 /**
7833  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
7834  *					      that were missed.
7835  * @phba: Pointer to HBA context object.
7836  *
7837  * For sli4, it is possible to miss an interrupt. As such mbox completions
7838  * maybe missed causing erroneous mailbox timeouts to occur. This function
7839  * checks to see if mbox completions are on the mailbox completion queue
7840  * and will process all the completions associated with the eq for the
7841  * mailbox completion queue.
7842  **/
7843 bool
7844 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
7845 {
7846 	struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
7847 	uint32_t eqidx;
7848 	struct lpfc_queue *fpeq = NULL;
7849 	struct lpfc_eqe *eqe;
7850 	bool mbox_pending;
7851 
7852 	if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
7853 		return false;
7854 
7855 	/* Find the eq associated with the mcq */
7856 
7857 	if (sli4_hba->hba_eq)
7858 		for (eqidx = 0; eqidx < phba->io_channel_irqs; eqidx++)
7859 			if (sli4_hba->hba_eq[eqidx]->queue_id ==
7860 			    sli4_hba->mbx_cq->assoc_qid) {
7861 				fpeq = sli4_hba->hba_eq[eqidx];
7862 				break;
7863 			}
7864 	if (!fpeq)
7865 		return false;
7866 
7867 	/* Turn off interrupts from this EQ */
7868 
7869 	sli4_hba->sli4_eq_clr_intr(fpeq);
7870 
7871 	/* Check to see if a mbox completion is pending */
7872 
7873 	mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
7874 
7875 	/*
7876 	 * If a mbox completion is pending, process all the events on EQ
7877 	 * associated with the mbox completion queue (this could include
7878 	 * mailbox commands, async events, els commands, receive queue data
7879 	 * and fcp commands)
7880 	 */
7881 
7882 	if (mbox_pending)
7883 		while ((eqe = lpfc_sli4_eq_get(fpeq))) {
7884 			lpfc_sli4_hba_handle_eqe(phba, eqe, eqidx);
7885 			fpeq->EQ_processed++;
7886 		}
7887 
7888 	/* Always clear and re-arm the EQ */
7889 
7890 	sli4_hba->sli4_eq_release(fpeq, LPFC_QUEUE_REARM);
7891 
7892 	return mbox_pending;
7893 
7894 }
7895 
7896 /**
7897  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
7898  * @phba: Pointer to HBA context object.
7899  *
7900  * This function is called from worker thread when a mailbox command times out.
7901  * The caller is not required to hold any locks. This function will reset the
7902  * HBA and recover all the pending commands.
7903  **/
7904 void
7905 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
7906 {
7907 	LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
7908 	MAILBOX_t *mb = NULL;
7909 
7910 	struct lpfc_sli *psli = &phba->sli;
7911 
7912 	/* If the mailbox completed, process the completion and return */
7913 	if (lpfc_sli4_process_missed_mbox_completions(phba))
7914 		return;
7915 
7916 	if (pmbox != NULL)
7917 		mb = &pmbox->u.mb;
7918 	/* Check the pmbox pointer first.  There is a race condition
7919 	 * between the mbox timeout handler getting executed in the
7920 	 * worklist and the mailbox actually completing. When this
7921 	 * race condition occurs, the mbox_active will be NULL.
7922 	 */
7923 	spin_lock_irq(&phba->hbalock);
7924 	if (pmbox == NULL) {
7925 		lpfc_printf_log(phba, KERN_WARNING,
7926 				LOG_MBOX | LOG_SLI,
7927 				"0353 Active Mailbox cleared - mailbox timeout "
7928 				"exiting\n");
7929 		spin_unlock_irq(&phba->hbalock);
7930 		return;
7931 	}
7932 
7933 	/* Mbox cmd <mbxCommand> timeout */
7934 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7935 			"0310 Mailbox command x%x timeout Data: x%x x%x x%p\n",
7936 			mb->mbxCommand,
7937 			phba->pport->port_state,
7938 			phba->sli.sli_flag,
7939 			phba->sli.mbox_active);
7940 	spin_unlock_irq(&phba->hbalock);
7941 
7942 	/* Setting state unknown so lpfc_sli_abort_iocb_ring
7943 	 * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
7944 	 * it to fail all outstanding SCSI IO.
7945 	 */
7946 	spin_lock_irq(&phba->pport->work_port_lock);
7947 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
7948 	spin_unlock_irq(&phba->pport->work_port_lock);
7949 	spin_lock_irq(&phba->hbalock);
7950 	phba->link_state = LPFC_LINK_UNKNOWN;
7951 	psli->sli_flag &= ~LPFC_SLI_ACTIVE;
7952 	spin_unlock_irq(&phba->hbalock);
7953 
7954 	lpfc_sli_abort_fcp_rings(phba);
7955 
7956 	lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7957 			"0345 Resetting board due to mailbox timeout\n");
7958 
7959 	/* Reset the HBA device */
7960 	lpfc_reset_hba(phba);
7961 }
7962 
7963 /**
7964  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
7965  * @phba: Pointer to HBA context object.
7966  * @pmbox: Pointer to mailbox object.
7967  * @flag: Flag indicating how the mailbox need to be processed.
7968  *
7969  * This function is called by discovery code and HBA management code
7970  * to submit a mailbox command to firmware with SLI-3 interface spec. This
7971  * function gets the hbalock to protect the data structures.
7972  * The mailbox command can be submitted in polling mode, in which case
7973  * this function will wait in a polling loop for the completion of the
7974  * mailbox.
7975  * If the mailbox is submitted in no_wait mode (not polling) the
7976  * function will submit the command and returns immediately without waiting
7977  * for the mailbox completion. The no_wait is supported only when HBA
7978  * is in SLI2/SLI3 mode - interrupts are enabled.
7979  * The SLI interface allows only one mailbox pending at a time. If the
7980  * mailbox is issued in polling mode and there is already a mailbox
7981  * pending, then the function will return an error. If the mailbox is issued
7982  * in NO_WAIT mode and there is a mailbox pending already, the function
7983  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
7984  * The sli layer owns the mailbox object until the completion of mailbox
7985  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
7986  * return codes the caller owns the mailbox command after the return of
7987  * the function.
7988  **/
7989 static int
7990 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
7991 		       uint32_t flag)
7992 {
7993 	MAILBOX_t *mbx;
7994 	struct lpfc_sli *psli = &phba->sli;
7995 	uint32_t status, evtctr;
7996 	uint32_t ha_copy, hc_copy;
7997 	int i;
7998 	unsigned long timeout;
7999 	unsigned long drvr_flag = 0;
8000 	uint32_t word0, ldata;
8001 	void __iomem *to_slim;
8002 	int processing_queue = 0;
8003 
8004 	spin_lock_irqsave(&phba->hbalock, drvr_flag);
8005 	if (!pmbox) {
8006 		phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8007 		/* processing mbox queue from intr_handler */
8008 		if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8009 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8010 			return MBX_SUCCESS;
8011 		}
8012 		processing_queue = 1;
8013 		pmbox = lpfc_mbox_get(phba);
8014 		if (!pmbox) {
8015 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8016 			return MBX_SUCCESS;
8017 		}
8018 	}
8019 
8020 	if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
8021 		pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
8022 		if(!pmbox->vport) {
8023 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8024 			lpfc_printf_log(phba, KERN_ERR,
8025 					LOG_MBOX | LOG_VPORT,
8026 					"1806 Mbox x%x failed. No vport\n",
8027 					pmbox->u.mb.mbxCommand);
8028 			dump_stack();
8029 			goto out_not_finished;
8030 		}
8031 	}
8032 
8033 	/* If the PCI channel is in offline state, do not post mbox. */
8034 	if (unlikely(pci_channel_offline(phba->pcidev))) {
8035 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8036 		goto out_not_finished;
8037 	}
8038 
8039 	/* If HBA has a deferred error attention, fail the iocb. */
8040 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
8041 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8042 		goto out_not_finished;
8043 	}
8044 
8045 	psli = &phba->sli;
8046 
8047 	mbx = &pmbox->u.mb;
8048 	status = MBX_SUCCESS;
8049 
8050 	if (phba->link_state == LPFC_HBA_ERROR) {
8051 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8052 
8053 		/* Mbox command <mbxCommand> cannot issue */
8054 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8055 				"(%d):0311 Mailbox command x%x cannot "
8056 				"issue Data: x%x x%x\n",
8057 				pmbox->vport ? pmbox->vport->vpi : 0,
8058 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8059 		goto out_not_finished;
8060 	}
8061 
8062 	if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
8063 		if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
8064 			!(hc_copy & HC_MBINT_ENA)) {
8065 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8066 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8067 				"(%d):2528 Mailbox command x%x cannot "
8068 				"issue Data: x%x x%x\n",
8069 				pmbox->vport ? pmbox->vport->vpi : 0,
8070 				pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8071 			goto out_not_finished;
8072 		}
8073 	}
8074 
8075 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8076 		/* Polling for a mbox command when another one is already active
8077 		 * is not allowed in SLI. Also, the driver must have established
8078 		 * SLI2 mode to queue and process multiple mbox commands.
8079 		 */
8080 
8081 		if (flag & MBX_POLL) {
8082 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8083 
8084 			/* Mbox command <mbxCommand> cannot issue */
8085 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8086 					"(%d):2529 Mailbox command x%x "
8087 					"cannot issue Data: x%x x%x\n",
8088 					pmbox->vport ? pmbox->vport->vpi : 0,
8089 					pmbox->u.mb.mbxCommand,
8090 					psli->sli_flag, flag);
8091 			goto out_not_finished;
8092 		}
8093 
8094 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
8095 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8096 			/* Mbox command <mbxCommand> cannot issue */
8097 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8098 					"(%d):2530 Mailbox command x%x "
8099 					"cannot issue Data: x%x x%x\n",
8100 					pmbox->vport ? pmbox->vport->vpi : 0,
8101 					pmbox->u.mb.mbxCommand,
8102 					psli->sli_flag, flag);
8103 			goto out_not_finished;
8104 		}
8105 
8106 		/* Another mailbox command is still being processed, queue this
8107 		 * command to be processed later.
8108 		 */
8109 		lpfc_mbox_put(phba, pmbox);
8110 
8111 		/* Mbox cmd issue - BUSY */
8112 		lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8113 				"(%d):0308 Mbox cmd issue - BUSY Data: "
8114 				"x%x x%x x%x x%x\n",
8115 				pmbox->vport ? pmbox->vport->vpi : 0xffffff,
8116 				mbx->mbxCommand,
8117 				phba->pport ? phba->pport->port_state : 0xff,
8118 				psli->sli_flag, flag);
8119 
8120 		psli->slistat.mbox_busy++;
8121 		spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8122 
8123 		if (pmbox->vport) {
8124 			lpfc_debugfs_disc_trc(pmbox->vport,
8125 				LPFC_DISC_TRC_MBOX_VPORT,
8126 				"MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
8127 				(uint32_t)mbx->mbxCommand,
8128 				mbx->un.varWords[0], mbx->un.varWords[1]);
8129 		}
8130 		else {
8131 			lpfc_debugfs_disc_trc(phba->pport,
8132 				LPFC_DISC_TRC_MBOX,
8133 				"MBOX Bsy:        cmd:x%x mb:x%x x%x",
8134 				(uint32_t)mbx->mbxCommand,
8135 				mbx->un.varWords[0], mbx->un.varWords[1]);
8136 		}
8137 
8138 		return MBX_BUSY;
8139 	}
8140 
8141 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8142 
8143 	/* If we are not polling, we MUST be in SLI2 mode */
8144 	if (flag != MBX_POLL) {
8145 		if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
8146 		    (mbx->mbxCommand != MBX_KILL_BOARD)) {
8147 			psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8148 			spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8149 			/* Mbox command <mbxCommand> cannot issue */
8150 			lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8151 					"(%d):2531 Mailbox command x%x "
8152 					"cannot issue Data: x%x x%x\n",
8153 					pmbox->vport ? pmbox->vport->vpi : 0,
8154 					pmbox->u.mb.mbxCommand,
8155 					psli->sli_flag, flag);
8156 			goto out_not_finished;
8157 		}
8158 		/* timeout active mbox command */
8159 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8160 					   1000);
8161 		mod_timer(&psli->mbox_tmo, jiffies + timeout);
8162 	}
8163 
8164 	/* Mailbox cmd <cmd> issue */
8165 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8166 			"(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
8167 			"x%x\n",
8168 			pmbox->vport ? pmbox->vport->vpi : 0,
8169 			mbx->mbxCommand,
8170 			phba->pport ? phba->pport->port_state : 0xff,
8171 			psli->sli_flag, flag);
8172 
8173 	if (mbx->mbxCommand != MBX_HEARTBEAT) {
8174 		if (pmbox->vport) {
8175 			lpfc_debugfs_disc_trc(pmbox->vport,
8176 				LPFC_DISC_TRC_MBOX_VPORT,
8177 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
8178 				(uint32_t)mbx->mbxCommand,
8179 				mbx->un.varWords[0], mbx->un.varWords[1]);
8180 		}
8181 		else {
8182 			lpfc_debugfs_disc_trc(phba->pport,
8183 				LPFC_DISC_TRC_MBOX,
8184 				"MBOX Send:       cmd:x%x mb:x%x x%x",
8185 				(uint32_t)mbx->mbxCommand,
8186 				mbx->un.varWords[0], mbx->un.varWords[1]);
8187 		}
8188 	}
8189 
8190 	psli->slistat.mbox_cmd++;
8191 	evtctr = psli->slistat.mbox_event;
8192 
8193 	/* next set own bit for the adapter and copy over command word */
8194 	mbx->mbxOwner = OWN_CHIP;
8195 
8196 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8197 		/* Populate mbox extension offset word. */
8198 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
8199 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8200 				= (uint8_t *)phba->mbox_ext
8201 				  - (uint8_t *)phba->mbox;
8202 		}
8203 
8204 		/* Copy the mailbox extension data */
8205 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
8206 			lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
8207 					      (uint8_t *)phba->mbox_ext,
8208 					      pmbox->in_ext_byte_len);
8209 		}
8210 		/* Copy command data to host SLIM area */
8211 		lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
8212 	} else {
8213 		/* Populate mbox extension offset word. */
8214 		if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
8215 			*(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8216 				= MAILBOX_HBA_EXT_OFFSET;
8217 
8218 		/* Copy the mailbox extension data */
8219 		if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
8220 			lpfc_memcpy_to_slim(phba->MBslimaddr +
8221 				MAILBOX_HBA_EXT_OFFSET,
8222 				pmbox->ctx_buf, pmbox->in_ext_byte_len);
8223 
8224 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
8225 			/* copy command data into host mbox for cmpl */
8226 			lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
8227 					      MAILBOX_CMD_SIZE);
8228 
8229 		/* First copy mbox command data to HBA SLIM, skip past first
8230 		   word */
8231 		to_slim = phba->MBslimaddr + sizeof (uint32_t);
8232 		lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
8233 			    MAILBOX_CMD_SIZE - sizeof (uint32_t));
8234 
8235 		/* Next copy over first word, with mbxOwner set */
8236 		ldata = *((uint32_t *)mbx);
8237 		to_slim = phba->MBslimaddr;
8238 		writel(ldata, to_slim);
8239 		readl(to_slim); /* flush */
8240 
8241 		if (mbx->mbxCommand == MBX_CONFIG_PORT)
8242 			/* switch over to host mailbox */
8243 			psli->sli_flag |= LPFC_SLI_ACTIVE;
8244 	}
8245 
8246 	wmb();
8247 
8248 	switch (flag) {
8249 	case MBX_NOWAIT:
8250 		/* Set up reference to mailbox command */
8251 		psli->mbox_active = pmbox;
8252 		/* Interrupt board to do it */
8253 		writel(CA_MBATT, phba->CAregaddr);
8254 		readl(phba->CAregaddr); /* flush */
8255 		/* Don't wait for it to finish, just return */
8256 		break;
8257 
8258 	case MBX_POLL:
8259 		/* Set up null reference to mailbox command */
8260 		psli->mbox_active = NULL;
8261 		/* Interrupt board to do it */
8262 		writel(CA_MBATT, phba->CAregaddr);
8263 		readl(phba->CAregaddr); /* flush */
8264 
8265 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8266 			/* First read mbox status word */
8267 			word0 = *((uint32_t *)phba->mbox);
8268 			word0 = le32_to_cpu(word0);
8269 		} else {
8270 			/* First read mbox status word */
8271 			if (lpfc_readl(phba->MBslimaddr, &word0)) {
8272 				spin_unlock_irqrestore(&phba->hbalock,
8273 						       drvr_flag);
8274 				goto out_not_finished;
8275 			}
8276 		}
8277 
8278 		/* Read the HBA Host Attention Register */
8279 		if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8280 			spin_unlock_irqrestore(&phba->hbalock,
8281 						       drvr_flag);
8282 			goto out_not_finished;
8283 		}
8284 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8285 							1000) + jiffies;
8286 		i = 0;
8287 		/* Wait for command to complete */
8288 		while (((word0 & OWN_CHIP) == OWN_CHIP) ||
8289 		       (!(ha_copy & HA_MBATT) &&
8290 			(phba->link_state > LPFC_WARM_START))) {
8291 			if (time_after(jiffies, timeout)) {
8292 				psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8293 				spin_unlock_irqrestore(&phba->hbalock,
8294 						       drvr_flag);
8295 				goto out_not_finished;
8296 			}
8297 
8298 			/* Check if we took a mbox interrupt while we were
8299 			   polling */
8300 			if (((word0 & OWN_CHIP) != OWN_CHIP)
8301 			    && (evtctr != psli->slistat.mbox_event))
8302 				break;
8303 
8304 			if (i++ > 10) {
8305 				spin_unlock_irqrestore(&phba->hbalock,
8306 						       drvr_flag);
8307 				msleep(1);
8308 				spin_lock_irqsave(&phba->hbalock, drvr_flag);
8309 			}
8310 
8311 			if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8312 				/* First copy command data */
8313 				word0 = *((uint32_t *)phba->mbox);
8314 				word0 = le32_to_cpu(word0);
8315 				if (mbx->mbxCommand == MBX_CONFIG_PORT) {
8316 					MAILBOX_t *slimmb;
8317 					uint32_t slimword0;
8318 					/* Check real SLIM for any errors */
8319 					slimword0 = readl(phba->MBslimaddr);
8320 					slimmb = (MAILBOX_t *) & slimword0;
8321 					if (((slimword0 & OWN_CHIP) != OWN_CHIP)
8322 					    && slimmb->mbxStatus) {
8323 						psli->sli_flag &=
8324 						    ~LPFC_SLI_ACTIVE;
8325 						word0 = slimword0;
8326 					}
8327 				}
8328 			} else {
8329 				/* First copy command data */
8330 				word0 = readl(phba->MBslimaddr);
8331 			}
8332 			/* Read the HBA Host Attention Register */
8333 			if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8334 				spin_unlock_irqrestore(&phba->hbalock,
8335 						       drvr_flag);
8336 				goto out_not_finished;
8337 			}
8338 		}
8339 
8340 		if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8341 			/* copy results back to user */
8342 			lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
8343 						MAILBOX_CMD_SIZE);
8344 			/* Copy the mailbox extension data */
8345 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8346 				lpfc_sli_pcimem_bcopy(phba->mbox_ext,
8347 						      pmbox->ctx_buf,
8348 						      pmbox->out_ext_byte_len);
8349 			}
8350 		} else {
8351 			/* First copy command data */
8352 			lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
8353 						MAILBOX_CMD_SIZE);
8354 			/* Copy the mailbox extension data */
8355 			if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8356 				lpfc_memcpy_from_slim(
8357 					pmbox->ctx_buf,
8358 					phba->MBslimaddr +
8359 					MAILBOX_HBA_EXT_OFFSET,
8360 					pmbox->out_ext_byte_len);
8361 			}
8362 		}
8363 
8364 		writel(HA_MBATT, phba->HAregaddr);
8365 		readl(phba->HAregaddr); /* flush */
8366 
8367 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8368 		status = mbx->mbxStatus;
8369 	}
8370 
8371 	spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8372 	return status;
8373 
8374 out_not_finished:
8375 	if (processing_queue) {
8376 		pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
8377 		lpfc_mbox_cmpl_put(phba, pmbox);
8378 	}
8379 	return MBX_NOT_FINISHED;
8380 }
8381 
8382 /**
8383  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
8384  * @phba: Pointer to HBA context object.
8385  *
8386  * The function blocks the posting of SLI4 asynchronous mailbox commands from
8387  * the driver internal pending mailbox queue. It will then try to wait out the
8388  * possible outstanding mailbox command before return.
8389  *
8390  * Returns:
8391  * 	0 - the outstanding mailbox command completed; otherwise, the wait for
8392  * 	the outstanding mailbox command timed out.
8393  **/
8394 static int
8395 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
8396 {
8397 	struct lpfc_sli *psli = &phba->sli;
8398 	int rc = 0;
8399 	unsigned long timeout = 0;
8400 
8401 	/* Mark the asynchronous mailbox command posting as blocked */
8402 	spin_lock_irq(&phba->hbalock);
8403 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
8404 	/* Determine how long we might wait for the active mailbox
8405 	 * command to be gracefully completed by firmware.
8406 	 */
8407 	if (phba->sli.mbox_active)
8408 		timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
8409 						phba->sli.mbox_active) *
8410 						1000) + jiffies;
8411 	spin_unlock_irq(&phba->hbalock);
8412 
8413 	/* Make sure the mailbox is really active */
8414 	if (timeout)
8415 		lpfc_sli4_process_missed_mbox_completions(phba);
8416 
8417 	/* Wait for the outstnading mailbox command to complete */
8418 	while (phba->sli.mbox_active) {
8419 		/* Check active mailbox complete status every 2ms */
8420 		msleep(2);
8421 		if (time_after(jiffies, timeout)) {
8422 			/* Timeout, marked the outstanding cmd not complete */
8423 			rc = 1;
8424 			break;
8425 		}
8426 	}
8427 
8428 	/* Can not cleanly block async mailbox command, fails it */
8429 	if (rc) {
8430 		spin_lock_irq(&phba->hbalock);
8431 		psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8432 		spin_unlock_irq(&phba->hbalock);
8433 	}
8434 	return rc;
8435 }
8436 
8437 /**
8438  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
8439  * @phba: Pointer to HBA context object.
8440  *
8441  * The function unblocks and resume posting of SLI4 asynchronous mailbox
8442  * commands from the driver internal pending mailbox queue. It makes sure
8443  * that there is no outstanding mailbox command before resuming posting
8444  * asynchronous mailbox commands. If, for any reason, there is outstanding
8445  * mailbox command, it will try to wait it out before resuming asynchronous
8446  * mailbox command posting.
8447  **/
8448 static void
8449 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
8450 {
8451 	struct lpfc_sli *psli = &phba->sli;
8452 
8453 	spin_lock_irq(&phba->hbalock);
8454 	if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8455 		/* Asynchronous mailbox posting is not blocked, do nothing */
8456 		spin_unlock_irq(&phba->hbalock);
8457 		return;
8458 	}
8459 
8460 	/* Outstanding synchronous mailbox command is guaranteed to be done,
8461 	 * successful or timeout, after timing-out the outstanding mailbox
8462 	 * command shall always be removed, so just unblock posting async
8463 	 * mailbox command and resume
8464 	 */
8465 	psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8466 	spin_unlock_irq(&phba->hbalock);
8467 
8468 	/* wake up worker thread to post asynchronlous mailbox command */
8469 	lpfc_worker_wake_up(phba);
8470 }
8471 
8472 /**
8473  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
8474  * @phba: Pointer to HBA context object.
8475  * @mboxq: Pointer to mailbox object.
8476  *
8477  * The function waits for the bootstrap mailbox register ready bit from
8478  * port for twice the regular mailbox command timeout value.
8479  *
8480  *      0 - no timeout on waiting for bootstrap mailbox register ready.
8481  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
8482  **/
8483 static int
8484 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8485 {
8486 	uint32_t db_ready;
8487 	unsigned long timeout;
8488 	struct lpfc_register bmbx_reg;
8489 
8490 	timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
8491 				   * 1000) + jiffies;
8492 
8493 	do {
8494 		bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
8495 		db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
8496 		if (!db_ready)
8497 			msleep(2);
8498 
8499 		if (time_after(jiffies, timeout))
8500 			return MBXERR_ERROR;
8501 	} while (!db_ready);
8502 
8503 	return 0;
8504 }
8505 
8506 /**
8507  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
8508  * @phba: Pointer to HBA context object.
8509  * @mboxq: Pointer to mailbox object.
8510  *
8511  * The function posts a mailbox to the port.  The mailbox is expected
8512  * to be comletely filled in and ready for the port to operate on it.
8513  * This routine executes a synchronous completion operation on the
8514  * mailbox by polling for its completion.
8515  *
8516  * The caller must not be holding any locks when calling this routine.
8517  *
8518  * Returns:
8519  *	MBX_SUCCESS - mailbox posted successfully
8520  *	Any of the MBX error values.
8521  **/
8522 static int
8523 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8524 {
8525 	int rc = MBX_SUCCESS;
8526 	unsigned long iflag;
8527 	uint32_t mcqe_status;
8528 	uint32_t mbx_cmnd;
8529 	struct lpfc_sli *psli = &phba->sli;
8530 	struct lpfc_mqe *mb = &mboxq->u.mqe;
8531 	struct lpfc_bmbx_create *mbox_rgn;
8532 	struct dma_address *dma_address;
8533 
8534 	/*
8535 	 * Only one mailbox can be active to the bootstrap mailbox region
8536 	 * at a time and there is no queueing provided.
8537 	 */
8538 	spin_lock_irqsave(&phba->hbalock, iflag);
8539 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8540 		spin_unlock_irqrestore(&phba->hbalock, iflag);
8541 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8542 				"(%d):2532 Mailbox command x%x (x%x/x%x) "
8543 				"cannot issue Data: x%x x%x\n",
8544 				mboxq->vport ? mboxq->vport->vpi : 0,
8545 				mboxq->u.mb.mbxCommand,
8546 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8547 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8548 				psli->sli_flag, MBX_POLL);
8549 		return MBXERR_ERROR;
8550 	}
8551 	/* The server grabs the token and owns it until release */
8552 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8553 	phba->sli.mbox_active = mboxq;
8554 	spin_unlock_irqrestore(&phba->hbalock, iflag);
8555 
8556 	/* wait for bootstrap mbox register for readyness */
8557 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8558 	if (rc)
8559 		goto exit;
8560 
8561 	/*
8562 	 * Initialize the bootstrap memory region to avoid stale data areas
8563 	 * in the mailbox post.  Then copy the caller's mailbox contents to
8564 	 * the bmbx mailbox region.
8565 	 */
8566 	mbx_cmnd = bf_get(lpfc_mqe_command, mb);
8567 	memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
8568 	lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
8569 			       sizeof(struct lpfc_mqe));
8570 
8571 	/* Post the high mailbox dma address to the port and wait for ready. */
8572 	dma_address = &phba->sli4_hba.bmbx.dma_address;
8573 	writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
8574 
8575 	/* wait for bootstrap mbox register for hi-address write done */
8576 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8577 	if (rc)
8578 		goto exit;
8579 
8580 	/* Post the low mailbox dma address to the port. */
8581 	writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
8582 
8583 	/* wait for bootstrap mbox register for low address write done */
8584 	rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8585 	if (rc)
8586 		goto exit;
8587 
8588 	/*
8589 	 * Read the CQ to ensure the mailbox has completed.
8590 	 * If so, update the mailbox status so that the upper layers
8591 	 * can complete the request normally.
8592 	 */
8593 	lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
8594 			       sizeof(struct lpfc_mqe));
8595 	mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
8596 	lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
8597 			       sizeof(struct lpfc_mcqe));
8598 	mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
8599 	/*
8600 	 * When the CQE status indicates a failure and the mailbox status
8601 	 * indicates success then copy the CQE status into the mailbox status
8602 	 * (and prefix it with x4000).
8603 	 */
8604 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
8605 		if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
8606 			bf_set(lpfc_mqe_status, mb,
8607 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
8608 		rc = MBXERR_ERROR;
8609 	} else
8610 		lpfc_sli4_swap_str(phba, mboxq);
8611 
8612 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8613 			"(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
8614 			"Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
8615 			" x%x x%x CQ: x%x x%x x%x x%x\n",
8616 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
8617 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8618 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8619 			bf_get(lpfc_mqe_status, mb),
8620 			mb->un.mb_words[0], mb->un.mb_words[1],
8621 			mb->un.mb_words[2], mb->un.mb_words[3],
8622 			mb->un.mb_words[4], mb->un.mb_words[5],
8623 			mb->un.mb_words[6], mb->un.mb_words[7],
8624 			mb->un.mb_words[8], mb->un.mb_words[9],
8625 			mb->un.mb_words[10], mb->un.mb_words[11],
8626 			mb->un.mb_words[12], mboxq->mcqe.word0,
8627 			mboxq->mcqe.mcqe_tag0, 	mboxq->mcqe.mcqe_tag1,
8628 			mboxq->mcqe.trailer);
8629 exit:
8630 	/* We are holding the token, no needed for lock when release */
8631 	spin_lock_irqsave(&phba->hbalock, iflag);
8632 	psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8633 	phba->sli.mbox_active = NULL;
8634 	spin_unlock_irqrestore(&phba->hbalock, iflag);
8635 	return rc;
8636 }
8637 
8638 /**
8639  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
8640  * @phba: Pointer to HBA context object.
8641  * @pmbox: Pointer to mailbox object.
8642  * @flag: Flag indicating how the mailbox need to be processed.
8643  *
8644  * This function is called by discovery code and HBA management code to submit
8645  * a mailbox command to firmware with SLI-4 interface spec.
8646  *
8647  * Return codes the caller owns the mailbox command after the return of the
8648  * function.
8649  **/
8650 static int
8651 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
8652 		       uint32_t flag)
8653 {
8654 	struct lpfc_sli *psli = &phba->sli;
8655 	unsigned long iflags;
8656 	int rc;
8657 
8658 	/* dump from issue mailbox command if setup */
8659 	lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
8660 
8661 	rc = lpfc_mbox_dev_check(phba);
8662 	if (unlikely(rc)) {
8663 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8664 				"(%d):2544 Mailbox command x%x (x%x/x%x) "
8665 				"cannot issue Data: x%x x%x\n",
8666 				mboxq->vport ? mboxq->vport->vpi : 0,
8667 				mboxq->u.mb.mbxCommand,
8668 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8669 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8670 				psli->sli_flag, flag);
8671 		goto out_not_finished;
8672 	}
8673 
8674 	/* Detect polling mode and jump to a handler */
8675 	if (!phba->sli4_hba.intr_enable) {
8676 		if (flag == MBX_POLL)
8677 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
8678 		else
8679 			rc = -EIO;
8680 		if (rc != MBX_SUCCESS)
8681 			lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8682 					"(%d):2541 Mailbox command x%x "
8683 					"(x%x/x%x) failure: "
8684 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
8685 					"Data: x%x x%x\n,",
8686 					mboxq->vport ? mboxq->vport->vpi : 0,
8687 					mboxq->u.mb.mbxCommand,
8688 					lpfc_sli_config_mbox_subsys_get(phba,
8689 									mboxq),
8690 					lpfc_sli_config_mbox_opcode_get(phba,
8691 									mboxq),
8692 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
8693 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
8694 					bf_get(lpfc_mcqe_ext_status,
8695 					       &mboxq->mcqe),
8696 					psli->sli_flag, flag);
8697 		return rc;
8698 	} else if (flag == MBX_POLL) {
8699 		lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8700 				"(%d):2542 Try to issue mailbox command "
8701 				"x%x (x%x/x%x) synchronously ahead of async "
8702 				"mailbox command queue: x%x x%x\n",
8703 				mboxq->vport ? mboxq->vport->vpi : 0,
8704 				mboxq->u.mb.mbxCommand,
8705 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8706 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8707 				psli->sli_flag, flag);
8708 		/* Try to block the asynchronous mailbox posting */
8709 		rc = lpfc_sli4_async_mbox_block(phba);
8710 		if (!rc) {
8711 			/* Successfully blocked, now issue sync mbox cmd */
8712 			rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
8713 			if (rc != MBX_SUCCESS)
8714 				lpfc_printf_log(phba, KERN_WARNING,
8715 					LOG_MBOX | LOG_SLI,
8716 					"(%d):2597 Sync Mailbox command "
8717 					"x%x (x%x/x%x) failure: "
8718 					"mqe_sta: x%x mcqe_sta: x%x/x%x "
8719 					"Data: x%x x%x\n,",
8720 					mboxq->vport ? mboxq->vport->vpi : 0,
8721 					mboxq->u.mb.mbxCommand,
8722 					lpfc_sli_config_mbox_subsys_get(phba,
8723 									mboxq),
8724 					lpfc_sli_config_mbox_opcode_get(phba,
8725 									mboxq),
8726 					bf_get(lpfc_mqe_status, &mboxq->u.mqe),
8727 					bf_get(lpfc_mcqe_status, &mboxq->mcqe),
8728 					bf_get(lpfc_mcqe_ext_status,
8729 					       &mboxq->mcqe),
8730 					psli->sli_flag, flag);
8731 			/* Unblock the async mailbox posting afterward */
8732 			lpfc_sli4_async_mbox_unblock(phba);
8733 		}
8734 		return rc;
8735 	}
8736 
8737 	/* Now, interrupt mode asynchrous mailbox command */
8738 	rc = lpfc_mbox_cmd_check(phba, mboxq);
8739 	if (rc) {
8740 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8741 				"(%d):2543 Mailbox command x%x (x%x/x%x) "
8742 				"cannot issue Data: x%x x%x\n",
8743 				mboxq->vport ? mboxq->vport->vpi : 0,
8744 				mboxq->u.mb.mbxCommand,
8745 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8746 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8747 				psli->sli_flag, flag);
8748 		goto out_not_finished;
8749 	}
8750 
8751 	/* Put the mailbox command to the driver internal FIFO */
8752 	psli->slistat.mbox_busy++;
8753 	spin_lock_irqsave(&phba->hbalock, iflags);
8754 	lpfc_mbox_put(phba, mboxq);
8755 	spin_unlock_irqrestore(&phba->hbalock, iflags);
8756 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8757 			"(%d):0354 Mbox cmd issue - Enqueue Data: "
8758 			"x%x (x%x/x%x) x%x x%x x%x\n",
8759 			mboxq->vport ? mboxq->vport->vpi : 0xffffff,
8760 			bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8761 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8762 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8763 			phba->pport->port_state,
8764 			psli->sli_flag, MBX_NOWAIT);
8765 	/* Wake up worker thread to transport mailbox command from head */
8766 	lpfc_worker_wake_up(phba);
8767 
8768 	return MBX_BUSY;
8769 
8770 out_not_finished:
8771 	return MBX_NOT_FINISHED;
8772 }
8773 
8774 /**
8775  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
8776  * @phba: Pointer to HBA context object.
8777  *
8778  * This function is called by worker thread to send a mailbox command to
8779  * SLI4 HBA firmware.
8780  *
8781  **/
8782 int
8783 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
8784 {
8785 	struct lpfc_sli *psli = &phba->sli;
8786 	LPFC_MBOXQ_t *mboxq;
8787 	int rc = MBX_SUCCESS;
8788 	unsigned long iflags;
8789 	struct lpfc_mqe *mqe;
8790 	uint32_t mbx_cmnd;
8791 
8792 	/* Check interrupt mode before post async mailbox command */
8793 	if (unlikely(!phba->sli4_hba.intr_enable))
8794 		return MBX_NOT_FINISHED;
8795 
8796 	/* Check for mailbox command service token */
8797 	spin_lock_irqsave(&phba->hbalock, iflags);
8798 	if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8799 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8800 		return MBX_NOT_FINISHED;
8801 	}
8802 	if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8803 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8804 		return MBX_NOT_FINISHED;
8805 	}
8806 	if (unlikely(phba->sli.mbox_active)) {
8807 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8808 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8809 				"0384 There is pending active mailbox cmd\n");
8810 		return MBX_NOT_FINISHED;
8811 	}
8812 	/* Take the mailbox command service token */
8813 	psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8814 
8815 	/* Get the next mailbox command from head of queue */
8816 	mboxq = lpfc_mbox_get(phba);
8817 
8818 	/* If no more mailbox command waiting for post, we're done */
8819 	if (!mboxq) {
8820 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8821 		spin_unlock_irqrestore(&phba->hbalock, iflags);
8822 		return MBX_SUCCESS;
8823 	}
8824 	phba->sli.mbox_active = mboxq;
8825 	spin_unlock_irqrestore(&phba->hbalock, iflags);
8826 
8827 	/* Check device readiness for posting mailbox command */
8828 	rc = lpfc_mbox_dev_check(phba);
8829 	if (unlikely(rc))
8830 		/* Driver clean routine will clean up pending mailbox */
8831 		goto out_not_finished;
8832 
8833 	/* Prepare the mbox command to be posted */
8834 	mqe = &mboxq->u.mqe;
8835 	mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
8836 
8837 	/* Start timer for the mbox_tmo and log some mailbox post messages */
8838 	mod_timer(&psli->mbox_tmo, (jiffies +
8839 		  msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
8840 
8841 	lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8842 			"(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
8843 			"x%x x%x\n",
8844 			mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
8845 			lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8846 			lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8847 			phba->pport->port_state, psli->sli_flag);
8848 
8849 	if (mbx_cmnd != MBX_HEARTBEAT) {
8850 		if (mboxq->vport) {
8851 			lpfc_debugfs_disc_trc(mboxq->vport,
8852 				LPFC_DISC_TRC_MBOX_VPORT,
8853 				"MBOX Send vport: cmd:x%x mb:x%x x%x",
8854 				mbx_cmnd, mqe->un.mb_words[0],
8855 				mqe->un.mb_words[1]);
8856 		} else {
8857 			lpfc_debugfs_disc_trc(phba->pport,
8858 				LPFC_DISC_TRC_MBOX,
8859 				"MBOX Send: cmd:x%x mb:x%x x%x",
8860 				mbx_cmnd, mqe->un.mb_words[0],
8861 				mqe->un.mb_words[1]);
8862 		}
8863 	}
8864 	psli->slistat.mbox_cmd++;
8865 
8866 	/* Post the mailbox command to the port */
8867 	rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
8868 	if (rc != MBX_SUCCESS) {
8869 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8870 				"(%d):2533 Mailbox command x%x (x%x/x%x) "
8871 				"cannot issue Data: x%x x%x\n",
8872 				mboxq->vport ? mboxq->vport->vpi : 0,
8873 				mboxq->u.mb.mbxCommand,
8874 				lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8875 				lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8876 				psli->sli_flag, MBX_NOWAIT);
8877 		goto out_not_finished;
8878 	}
8879 
8880 	return rc;
8881 
8882 out_not_finished:
8883 	spin_lock_irqsave(&phba->hbalock, iflags);
8884 	if (phba->sli.mbox_active) {
8885 		mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
8886 		__lpfc_mbox_cmpl_put(phba, mboxq);
8887 		/* Release the token */
8888 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8889 		phba->sli.mbox_active = NULL;
8890 	}
8891 	spin_unlock_irqrestore(&phba->hbalock, iflags);
8892 
8893 	return MBX_NOT_FINISHED;
8894 }
8895 
8896 /**
8897  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
8898  * @phba: Pointer to HBA context object.
8899  * @pmbox: Pointer to mailbox object.
8900  * @flag: Flag indicating how the mailbox need to be processed.
8901  *
8902  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
8903  * the API jump table function pointer from the lpfc_hba struct.
8904  *
8905  * Return codes the caller owns the mailbox command after the return of the
8906  * function.
8907  **/
8908 int
8909 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
8910 {
8911 	return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
8912 }
8913 
8914 /**
8915  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
8916  * @phba: The hba struct for which this call is being executed.
8917  * @dev_grp: The HBA PCI-Device group number.
8918  *
8919  * This routine sets up the mbox interface API function jump table in @phba
8920  * struct.
8921  * Returns: 0 - success, -ENODEV - failure.
8922  **/
8923 int
8924 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
8925 {
8926 
8927 	switch (dev_grp) {
8928 	case LPFC_PCI_DEV_LP:
8929 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
8930 		phba->lpfc_sli_handle_slow_ring_event =
8931 				lpfc_sli_handle_slow_ring_event_s3;
8932 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
8933 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
8934 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
8935 		break;
8936 	case LPFC_PCI_DEV_OC:
8937 		phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
8938 		phba->lpfc_sli_handle_slow_ring_event =
8939 				lpfc_sli_handle_slow_ring_event_s4;
8940 		phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
8941 		phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
8942 		phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
8943 		break;
8944 	default:
8945 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8946 				"1420 Invalid HBA PCI-device group: 0x%x\n",
8947 				dev_grp);
8948 		return -ENODEV;
8949 		break;
8950 	}
8951 	return 0;
8952 }
8953 
8954 /**
8955  * __lpfc_sli_ringtx_put - Add an iocb to the txq
8956  * @phba: Pointer to HBA context object.
8957  * @pring: Pointer to driver SLI ring object.
8958  * @piocb: Pointer to address of newly added command iocb.
8959  *
8960  * This function is called with hbalock held to add a command
8961  * iocb to the txq when SLI layer cannot submit the command iocb
8962  * to the ring.
8963  **/
8964 void
8965 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
8966 		    struct lpfc_iocbq *piocb)
8967 {
8968 	lockdep_assert_held(&phba->hbalock);
8969 	/* Insert the caller's iocb in the txq tail for later processing. */
8970 	list_add_tail(&piocb->list, &pring->txq);
8971 }
8972 
8973 /**
8974  * lpfc_sli_next_iocb - Get the next iocb in the txq
8975  * @phba: Pointer to HBA context object.
8976  * @pring: Pointer to driver SLI ring object.
8977  * @piocb: Pointer to address of newly added command iocb.
8978  *
8979  * This function is called with hbalock held before a new
8980  * iocb is submitted to the firmware. This function checks
8981  * txq to flush the iocbs in txq to Firmware before
8982  * submitting new iocbs to the Firmware.
8983  * If there are iocbs in the txq which need to be submitted
8984  * to firmware, lpfc_sli_next_iocb returns the first element
8985  * of the txq after dequeuing it from txq.
8986  * If there is no iocb in the txq then the function will return
8987  * *piocb and *piocb is set to NULL. Caller needs to check
8988  * *piocb to find if there are more commands in the txq.
8989  **/
8990 static struct lpfc_iocbq *
8991 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
8992 		   struct lpfc_iocbq **piocb)
8993 {
8994 	struct lpfc_iocbq * nextiocb;
8995 
8996 	lockdep_assert_held(&phba->hbalock);
8997 
8998 	nextiocb = lpfc_sli_ringtx_get(phba, pring);
8999 	if (!nextiocb) {
9000 		nextiocb = *piocb;
9001 		*piocb = NULL;
9002 	}
9003 
9004 	return nextiocb;
9005 }
9006 
9007 /**
9008  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
9009  * @phba: Pointer to HBA context object.
9010  * @ring_number: SLI ring number to issue iocb on.
9011  * @piocb: Pointer to command iocb.
9012  * @flag: Flag indicating if this command can be put into txq.
9013  *
9014  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
9015  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
9016  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
9017  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
9018  * this function allows only iocbs for posting buffers. This function finds
9019  * next available slot in the command ring and posts the command to the
9020  * available slot and writes the port attention register to request HBA start
9021  * processing new iocb. If there is no slot available in the ring and
9022  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
9023  * the function returns IOCB_BUSY.
9024  *
9025  * This function is called with hbalock held. The function will return success
9026  * after it successfully submit the iocb to firmware or after adding to the
9027  * txq.
9028  **/
9029 static int
9030 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
9031 		    struct lpfc_iocbq *piocb, uint32_t flag)
9032 {
9033 	struct lpfc_iocbq *nextiocb;
9034 	IOCB_t *iocb;
9035 	struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
9036 
9037 	lockdep_assert_held(&phba->hbalock);
9038 
9039 	if (piocb->iocb_cmpl && (!piocb->vport) &&
9040 	   (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
9041 	   (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
9042 		lpfc_printf_log(phba, KERN_ERR,
9043 				LOG_SLI | LOG_VPORT,
9044 				"1807 IOCB x%x failed. No vport\n",
9045 				piocb->iocb.ulpCommand);
9046 		dump_stack();
9047 		return IOCB_ERROR;
9048 	}
9049 
9050 
9051 	/* If the PCI channel is in offline state, do not post iocbs. */
9052 	if (unlikely(pci_channel_offline(phba->pcidev)))
9053 		return IOCB_ERROR;
9054 
9055 	/* If HBA has a deferred error attention, fail the iocb. */
9056 	if (unlikely(phba->hba_flag & DEFER_ERATT))
9057 		return IOCB_ERROR;
9058 
9059 	/*
9060 	 * We should never get an IOCB if we are in a < LINK_DOWN state
9061 	 */
9062 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
9063 		return IOCB_ERROR;
9064 
9065 	/*
9066 	 * Check to see if we are blocking IOCB processing because of a
9067 	 * outstanding event.
9068 	 */
9069 	if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
9070 		goto iocb_busy;
9071 
9072 	if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
9073 		/*
9074 		 * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
9075 		 * can be issued if the link is not up.
9076 		 */
9077 		switch (piocb->iocb.ulpCommand) {
9078 		case CMD_GEN_REQUEST64_CR:
9079 		case CMD_GEN_REQUEST64_CX:
9080 			if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
9081 				(piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
9082 					FC_RCTL_DD_UNSOL_CMD) ||
9083 				(piocb->iocb.un.genreq64.w5.hcsw.Type !=
9084 					MENLO_TRANSPORT_TYPE))
9085 
9086 				goto iocb_busy;
9087 			break;
9088 		case CMD_QUE_RING_BUF_CN:
9089 		case CMD_QUE_RING_BUF64_CN:
9090 			/*
9091 			 * For IOCBs, like QUE_RING_BUF, that have no rsp ring
9092 			 * completion, iocb_cmpl MUST be 0.
9093 			 */
9094 			if (piocb->iocb_cmpl)
9095 				piocb->iocb_cmpl = NULL;
9096 			/*FALLTHROUGH*/
9097 		case CMD_CREATE_XRI_CR:
9098 		case CMD_CLOSE_XRI_CN:
9099 		case CMD_CLOSE_XRI_CX:
9100 			break;
9101 		default:
9102 			goto iocb_busy;
9103 		}
9104 
9105 	/*
9106 	 * For FCP commands, we must be in a state where we can process link
9107 	 * attention events.
9108 	 */
9109 	} else if (unlikely(pring->ringno == LPFC_FCP_RING &&
9110 			    !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
9111 		goto iocb_busy;
9112 	}
9113 
9114 	while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
9115 	       (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
9116 		lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
9117 
9118 	if (iocb)
9119 		lpfc_sli_update_ring(phba, pring);
9120 	else
9121 		lpfc_sli_update_full_ring(phba, pring);
9122 
9123 	if (!piocb)
9124 		return IOCB_SUCCESS;
9125 
9126 	goto out_busy;
9127 
9128  iocb_busy:
9129 	pring->stats.iocb_cmd_delay++;
9130 
9131  out_busy:
9132 
9133 	if (!(flag & SLI_IOCB_RET_IOCB)) {
9134 		__lpfc_sli_ringtx_put(phba, pring, piocb);
9135 		return IOCB_SUCCESS;
9136 	}
9137 
9138 	return IOCB_BUSY;
9139 }
9140 
9141 /**
9142  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
9143  * @phba: Pointer to HBA context object.
9144  * @piocb: Pointer to command iocb.
9145  * @sglq: Pointer to the scatter gather queue object.
9146  *
9147  * This routine converts the bpl or bde that is in the IOCB
9148  * to a sgl list for the sli4 hardware. The physical address
9149  * of the bpl/bde is converted back to a virtual address.
9150  * If the IOCB contains a BPL then the list of BDE's is
9151  * converted to sli4_sge's. If the IOCB contains a single
9152  * BDE then it is converted to a single sli_sge.
9153  * The IOCB is still in cpu endianess so the contents of
9154  * the bpl can be used without byte swapping.
9155  *
9156  * Returns valid XRI = Success, NO_XRI = Failure.
9157 **/
9158 static uint16_t
9159 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
9160 		struct lpfc_sglq *sglq)
9161 {
9162 	uint16_t xritag = NO_XRI;
9163 	struct ulp_bde64 *bpl = NULL;
9164 	struct ulp_bde64 bde;
9165 	struct sli4_sge *sgl  = NULL;
9166 	struct lpfc_dmabuf *dmabuf;
9167 	IOCB_t *icmd;
9168 	int numBdes = 0;
9169 	int i = 0;
9170 	uint32_t offset = 0; /* accumulated offset in the sg request list */
9171 	int inbound = 0; /* number of sg reply entries inbound from firmware */
9172 
9173 	if (!piocbq || !sglq)
9174 		return xritag;
9175 
9176 	sgl  = (struct sli4_sge *)sglq->sgl;
9177 	icmd = &piocbq->iocb;
9178 	if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
9179 		return sglq->sli4_xritag;
9180 	if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9181 		numBdes = icmd->un.genreq64.bdl.bdeSize /
9182 				sizeof(struct ulp_bde64);
9183 		/* The addrHigh and addrLow fields within the IOCB
9184 		 * have not been byteswapped yet so there is no
9185 		 * need to swap them back.
9186 		 */
9187 		if (piocbq->context3)
9188 			dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
9189 		else
9190 			return xritag;
9191 
9192 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
9193 		if (!bpl)
9194 			return xritag;
9195 
9196 		for (i = 0; i < numBdes; i++) {
9197 			/* Should already be byte swapped. */
9198 			sgl->addr_hi = bpl->addrHigh;
9199 			sgl->addr_lo = bpl->addrLow;
9200 
9201 			sgl->word2 = le32_to_cpu(sgl->word2);
9202 			if ((i+1) == numBdes)
9203 				bf_set(lpfc_sli4_sge_last, sgl, 1);
9204 			else
9205 				bf_set(lpfc_sli4_sge_last, sgl, 0);
9206 			/* swap the size field back to the cpu so we
9207 			 * can assign it to the sgl.
9208 			 */
9209 			bde.tus.w = le32_to_cpu(bpl->tus.w);
9210 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
9211 			/* The offsets in the sgl need to be accumulated
9212 			 * separately for the request and reply lists.
9213 			 * The request is always first, the reply follows.
9214 			 */
9215 			if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
9216 				/* add up the reply sg entries */
9217 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
9218 					inbound++;
9219 				/* first inbound? reset the offset */
9220 				if (inbound == 1)
9221 					offset = 0;
9222 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
9223 				bf_set(lpfc_sli4_sge_type, sgl,
9224 					LPFC_SGE_TYPE_DATA);
9225 				offset += bde.tus.f.bdeSize;
9226 			}
9227 			sgl->word2 = cpu_to_le32(sgl->word2);
9228 			bpl++;
9229 			sgl++;
9230 		}
9231 	} else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
9232 			/* The addrHigh and addrLow fields of the BDE have not
9233 			 * been byteswapped yet so they need to be swapped
9234 			 * before putting them in the sgl.
9235 			 */
9236 			sgl->addr_hi =
9237 				cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
9238 			sgl->addr_lo =
9239 				cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
9240 			sgl->word2 = le32_to_cpu(sgl->word2);
9241 			bf_set(lpfc_sli4_sge_last, sgl, 1);
9242 			sgl->word2 = cpu_to_le32(sgl->word2);
9243 			sgl->sge_len =
9244 				cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
9245 	}
9246 	return sglq->sli4_xritag;
9247 }
9248 
9249 /**
9250  * lpfc_sli_iocb2wqe - Convert the IOCB to a work queue entry.
9251  * @phba: Pointer to HBA context object.
9252  * @piocb: Pointer to command iocb.
9253  * @wqe: Pointer to the work queue entry.
9254  *
9255  * This routine converts the iocb command to its Work Queue Entry
9256  * equivalent. The wqe pointer should not have any fields set when
9257  * this routine is called because it will memcpy over them.
9258  * This routine does not set the CQ_ID or the WQEC bits in the
9259  * wqe.
9260  *
9261  * Returns: 0 = Success, IOCB_ERROR = Failure.
9262  **/
9263 static int
9264 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
9265 		union lpfc_wqe128 *wqe)
9266 {
9267 	uint32_t xmit_len = 0, total_len = 0;
9268 	uint8_t ct = 0;
9269 	uint32_t fip;
9270 	uint32_t abort_tag;
9271 	uint8_t command_type = ELS_COMMAND_NON_FIP;
9272 	uint8_t cmnd;
9273 	uint16_t xritag;
9274 	uint16_t abrt_iotag;
9275 	struct lpfc_iocbq *abrtiocbq;
9276 	struct ulp_bde64 *bpl = NULL;
9277 	uint32_t els_id = LPFC_ELS_ID_DEFAULT;
9278 	int numBdes, i;
9279 	struct ulp_bde64 bde;
9280 	struct lpfc_nodelist *ndlp;
9281 	uint32_t *pcmd;
9282 	uint32_t if_type;
9283 
9284 	fip = phba->hba_flag & HBA_FIP_SUPPORT;
9285 	/* The fcp commands will set command type */
9286 	if (iocbq->iocb_flag &  LPFC_IO_FCP)
9287 		command_type = FCP_COMMAND;
9288 	else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
9289 		command_type = ELS_COMMAND_FIP;
9290 	else
9291 		command_type = ELS_COMMAND_NON_FIP;
9292 
9293 	if (phba->fcp_embed_io)
9294 		memset(wqe, 0, sizeof(union lpfc_wqe128));
9295 	/* Some of the fields are in the right position already */
9296 	memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
9297 	if (iocbq->iocb.ulpCommand != CMD_SEND_FRAME) {
9298 		/* The ct field has moved so reset */
9299 		wqe->generic.wqe_com.word7 = 0;
9300 		wqe->generic.wqe_com.word10 = 0;
9301 	}
9302 
9303 	abort_tag = (uint32_t) iocbq->iotag;
9304 	xritag = iocbq->sli4_xritag;
9305 	/* words0-2 bpl convert bde */
9306 	if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9307 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
9308 				sizeof(struct ulp_bde64);
9309 		bpl  = (struct ulp_bde64 *)
9310 			((struct lpfc_dmabuf *)iocbq->context3)->virt;
9311 		if (!bpl)
9312 			return IOCB_ERROR;
9313 
9314 		/* Should already be byte swapped. */
9315 		wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
9316 		wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
9317 		/* swap the size field back to the cpu so we
9318 		 * can assign it to the sgl.
9319 		 */
9320 		wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
9321 		xmit_len = wqe->generic.bde.tus.f.bdeSize;
9322 		total_len = 0;
9323 		for (i = 0; i < numBdes; i++) {
9324 			bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
9325 			total_len += bde.tus.f.bdeSize;
9326 		}
9327 	} else
9328 		xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
9329 
9330 	iocbq->iocb.ulpIoTag = iocbq->iotag;
9331 	cmnd = iocbq->iocb.ulpCommand;
9332 
9333 	switch (iocbq->iocb.ulpCommand) {
9334 	case CMD_ELS_REQUEST64_CR:
9335 		if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
9336 			ndlp = iocbq->context_un.ndlp;
9337 		else
9338 			ndlp = (struct lpfc_nodelist *)iocbq->context1;
9339 		if (!iocbq->iocb.ulpLe) {
9340 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9341 				"2007 Only Limited Edition cmd Format"
9342 				" supported 0x%x\n",
9343 				iocbq->iocb.ulpCommand);
9344 			return IOCB_ERROR;
9345 		}
9346 
9347 		wqe->els_req.payload_len = xmit_len;
9348 		/* Els_reguest64 has a TMO */
9349 		bf_set(wqe_tmo, &wqe->els_req.wqe_com,
9350 			iocbq->iocb.ulpTimeout);
9351 		/* Need a VF for word 4 set the vf bit*/
9352 		bf_set(els_req64_vf, &wqe->els_req, 0);
9353 		/* And a VFID for word 12 */
9354 		bf_set(els_req64_vfid, &wqe->els_req, 0);
9355 		ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
9356 		bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9357 		       iocbq->iocb.ulpContext);
9358 		bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
9359 		bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
9360 		/* CCP CCPE PV PRI in word10 were set in the memcpy */
9361 		if (command_type == ELS_COMMAND_FIP)
9362 			els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
9363 					>> LPFC_FIP_ELS_ID_SHIFT);
9364 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
9365 					iocbq->context2)->virt);
9366 		if_type = bf_get(lpfc_sli_intf_if_type,
9367 					&phba->sli4_hba.sli_intf);
9368 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
9369 			if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
9370 				*pcmd == ELS_CMD_SCR ||
9371 				*pcmd == ELS_CMD_FDISC ||
9372 				*pcmd == ELS_CMD_LOGO ||
9373 				*pcmd == ELS_CMD_PLOGI)) {
9374 				bf_set(els_req64_sp, &wqe->els_req, 1);
9375 				bf_set(els_req64_sid, &wqe->els_req,
9376 					iocbq->vport->fc_myDID);
9377 				if ((*pcmd == ELS_CMD_FLOGI) &&
9378 					!(phba->fc_topology ==
9379 						LPFC_TOPOLOGY_LOOP))
9380 					bf_set(els_req64_sid, &wqe->els_req, 0);
9381 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
9382 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9383 					phba->vpi_ids[iocbq->vport->vpi]);
9384 			} else if (pcmd && iocbq->context1) {
9385 				bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
9386 				bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9387 					phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9388 			}
9389 		}
9390 		bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
9391 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9392 		bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
9393 		bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
9394 		bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
9395 		bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
9396 		bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
9397 		bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
9398 		wqe->els_req.max_response_payload_len = total_len - xmit_len;
9399 		break;
9400 	case CMD_XMIT_SEQUENCE64_CX:
9401 		bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
9402 		       iocbq->iocb.un.ulpWord[3]);
9403 		bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
9404 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
9405 		/* The entire sequence is transmitted for this IOCB */
9406 		xmit_len = total_len;
9407 		cmnd = CMD_XMIT_SEQUENCE64_CR;
9408 		if (phba->link_flag & LS_LOOPBACK_MODE)
9409 			bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
9410 	case CMD_XMIT_SEQUENCE64_CR:
9411 		/* word3 iocb=io_tag32 wqe=reserved */
9412 		wqe->xmit_sequence.rsvd3 = 0;
9413 		/* word4 relative_offset memcpy */
9414 		/* word5 r_ctl/df_ctl memcpy */
9415 		bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
9416 		bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
9417 		bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
9418 		       LPFC_WQE_IOD_WRITE);
9419 		bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
9420 		       LPFC_WQE_LENLOC_WORD12);
9421 		bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
9422 		wqe->xmit_sequence.xmit_len = xmit_len;
9423 		command_type = OTHER_COMMAND;
9424 		break;
9425 	case CMD_XMIT_BCAST64_CN:
9426 		/* word3 iocb=iotag32 wqe=seq_payload_len */
9427 		wqe->xmit_bcast64.seq_payload_len = xmit_len;
9428 		/* word4 iocb=rsvd wqe=rsvd */
9429 		/* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
9430 		/* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
9431 		bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
9432 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9433 		bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
9434 		bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
9435 		bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
9436 		       LPFC_WQE_LENLOC_WORD3);
9437 		bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
9438 		break;
9439 	case CMD_FCP_IWRITE64_CR:
9440 		command_type = FCP_COMMAND_DATA_OUT;
9441 		/* word3 iocb=iotag wqe=payload_offset_len */
9442 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9443 		bf_set(payload_offset_len, &wqe->fcp_iwrite,
9444 		       xmit_len + sizeof(struct fcp_rsp));
9445 		bf_set(cmd_buff_len, &wqe->fcp_iwrite,
9446 		       0);
9447 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
9448 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9449 		bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
9450 		       iocbq->iocb.ulpFCP2Rcvy);
9451 		bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
9452 		/* Always open the exchange */
9453 		bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
9454 		bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
9455 		       LPFC_WQE_LENLOC_WORD4);
9456 		bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
9457 		bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
9458 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9459 			bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
9460 			bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
9461 			if (iocbq->priority) {
9462 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9463 				       (iocbq->priority << 1));
9464 			} else {
9465 				bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9466 				       (phba->cfg_XLanePriority << 1));
9467 			}
9468 		}
9469 		/* Note, word 10 is already initialized to 0 */
9470 
9471 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9472 		if (phba->cfg_enable_pbde)
9473 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 1);
9474 		else
9475 			bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
9476 
9477 		if (phba->fcp_embed_io) {
9478 			struct lpfc_scsi_buf *lpfc_cmd;
9479 			struct sli4_sge *sgl;
9480 			struct fcp_cmnd *fcp_cmnd;
9481 			uint32_t *ptr;
9482 
9483 			/* 128 byte wqe support here */
9484 
9485 			lpfc_cmd = iocbq->context1;
9486 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
9487 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9488 
9489 			/* Word 0-2 - FCP_CMND */
9490 			wqe->generic.bde.tus.f.bdeFlags =
9491 				BUFF_TYPE_BDE_IMMED;
9492 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9493 			wqe->generic.bde.addrHigh = 0;
9494 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9495 
9496 			bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
9497 			bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
9498 
9499 			/* Word 22-29  FCP CMND Payload */
9500 			ptr = &wqe->words[22];
9501 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9502 		}
9503 		break;
9504 	case CMD_FCP_IREAD64_CR:
9505 		/* word3 iocb=iotag wqe=payload_offset_len */
9506 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9507 		bf_set(payload_offset_len, &wqe->fcp_iread,
9508 		       xmit_len + sizeof(struct fcp_rsp));
9509 		bf_set(cmd_buff_len, &wqe->fcp_iread,
9510 		       0);
9511 		/* word4 iocb=parameter wqe=total_xfer_length memcpy */
9512 		/* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9513 		bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
9514 		       iocbq->iocb.ulpFCP2Rcvy);
9515 		bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
9516 		/* Always open the exchange */
9517 		bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
9518 		bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
9519 		       LPFC_WQE_LENLOC_WORD4);
9520 		bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
9521 		bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
9522 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9523 			bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
9524 			bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
9525 			if (iocbq->priority) {
9526 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9527 				       (iocbq->priority << 1));
9528 			} else {
9529 				bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9530 				       (phba->cfg_XLanePriority << 1));
9531 			}
9532 		}
9533 		/* Note, word 10 is already initialized to 0 */
9534 
9535 		/* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9536 		if (phba->cfg_enable_pbde)
9537 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 1);
9538 		else
9539 			bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
9540 
9541 		if (phba->fcp_embed_io) {
9542 			struct lpfc_scsi_buf *lpfc_cmd;
9543 			struct sli4_sge *sgl;
9544 			struct fcp_cmnd *fcp_cmnd;
9545 			uint32_t *ptr;
9546 
9547 			/* 128 byte wqe support here */
9548 
9549 			lpfc_cmd = iocbq->context1;
9550 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
9551 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9552 
9553 			/* Word 0-2 - FCP_CMND */
9554 			wqe->generic.bde.tus.f.bdeFlags =
9555 				BUFF_TYPE_BDE_IMMED;
9556 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9557 			wqe->generic.bde.addrHigh = 0;
9558 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9559 
9560 			bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
9561 			bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
9562 
9563 			/* Word 22-29  FCP CMND Payload */
9564 			ptr = &wqe->words[22];
9565 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9566 		}
9567 		break;
9568 	case CMD_FCP_ICMND64_CR:
9569 		/* word3 iocb=iotag wqe=payload_offset_len */
9570 		/* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9571 		bf_set(payload_offset_len, &wqe->fcp_icmd,
9572 		       xmit_len + sizeof(struct fcp_rsp));
9573 		bf_set(cmd_buff_len, &wqe->fcp_icmd,
9574 		       0);
9575 		/* word3 iocb=IO_TAG wqe=reserved */
9576 		bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
9577 		/* Always open the exchange */
9578 		bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
9579 		bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
9580 		bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
9581 		bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
9582 		       LPFC_WQE_LENLOC_NONE);
9583 		bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
9584 		       iocbq->iocb.ulpFCP2Rcvy);
9585 		if (iocbq->iocb_flag & LPFC_IO_OAS) {
9586 			bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
9587 			bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
9588 			if (iocbq->priority) {
9589 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
9590 				       (iocbq->priority << 1));
9591 			} else {
9592 				bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
9593 				       (phba->cfg_XLanePriority << 1));
9594 			}
9595 		}
9596 		/* Note, word 10 is already initialized to 0 */
9597 
9598 		if (phba->fcp_embed_io) {
9599 			struct lpfc_scsi_buf *lpfc_cmd;
9600 			struct sli4_sge *sgl;
9601 			struct fcp_cmnd *fcp_cmnd;
9602 			uint32_t *ptr;
9603 
9604 			/* 128 byte wqe support here */
9605 
9606 			lpfc_cmd = iocbq->context1;
9607 			sgl = (struct sli4_sge *)lpfc_cmd->fcp_bpl;
9608 			fcp_cmnd = lpfc_cmd->fcp_cmnd;
9609 
9610 			/* Word 0-2 - FCP_CMND */
9611 			wqe->generic.bde.tus.f.bdeFlags =
9612 				BUFF_TYPE_BDE_IMMED;
9613 			wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9614 			wqe->generic.bde.addrHigh = 0;
9615 			wqe->generic.bde.addrLow =  88;  /* Word 22 */
9616 
9617 			bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
9618 			bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
9619 
9620 			/* Word 22-29  FCP CMND Payload */
9621 			ptr = &wqe->words[22];
9622 			memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9623 		}
9624 		break;
9625 	case CMD_GEN_REQUEST64_CR:
9626 		/* For this command calculate the xmit length of the
9627 		 * request bde.
9628 		 */
9629 		xmit_len = 0;
9630 		numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
9631 			sizeof(struct ulp_bde64);
9632 		for (i = 0; i < numBdes; i++) {
9633 			bde.tus.w = le32_to_cpu(bpl[i].tus.w);
9634 			if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
9635 				break;
9636 			xmit_len += bde.tus.f.bdeSize;
9637 		}
9638 		/* word3 iocb=IO_TAG wqe=request_payload_len */
9639 		wqe->gen_req.request_payload_len = xmit_len;
9640 		/* word4 iocb=parameter wqe=relative_offset memcpy */
9641 		/* word5 [rctl, type, df_ctl, la] copied in memcpy */
9642 		/* word6 context tag copied in memcpy */
9643 		if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
9644 			ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
9645 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9646 				"2015 Invalid CT %x command 0x%x\n",
9647 				ct, iocbq->iocb.ulpCommand);
9648 			return IOCB_ERROR;
9649 		}
9650 		bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
9651 		bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
9652 		bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
9653 		bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
9654 		bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
9655 		bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
9656 		bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
9657 		bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
9658 		wqe->gen_req.max_response_payload_len = total_len - xmit_len;
9659 		command_type = OTHER_COMMAND;
9660 		break;
9661 	case CMD_XMIT_ELS_RSP64_CX:
9662 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
9663 		/* words0-2 BDE memcpy */
9664 		/* word3 iocb=iotag32 wqe=response_payload_len */
9665 		wqe->xmit_els_rsp.response_payload_len = xmit_len;
9666 		/* word4 */
9667 		wqe->xmit_els_rsp.word4 = 0;
9668 		/* word5 iocb=rsvd wge=did */
9669 		bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
9670 			 iocbq->iocb.un.xseq64.xmit_els_remoteID);
9671 
9672 		if_type = bf_get(lpfc_sli_intf_if_type,
9673 					&phba->sli4_hba.sli_intf);
9674 		if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
9675 			if (iocbq->vport->fc_flag & FC_PT2PT) {
9676 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
9677 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
9678 					iocbq->vport->fc_myDID);
9679 				if (iocbq->vport->fc_myDID == Fabric_DID) {
9680 					bf_set(wqe_els_did,
9681 						&wqe->xmit_els_rsp.wqe_dest, 0);
9682 				}
9683 			}
9684 		}
9685 		bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
9686 		       ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9687 		bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
9688 		bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
9689 		       iocbq->iocb.unsli3.rcvsli3.ox_id);
9690 		if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
9691 			bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
9692 			       phba->vpi_ids[iocbq->vport->vpi]);
9693 		bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
9694 		bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
9695 		bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
9696 		bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
9697 		       LPFC_WQE_LENLOC_WORD3);
9698 		bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
9699 		bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
9700 		       phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9701 		pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
9702 					iocbq->context2)->virt);
9703 		if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
9704 				bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
9705 				bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
9706 					iocbq->vport->fc_myDID);
9707 				bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
9708 				bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
9709 					phba->vpi_ids[phba->pport->vpi]);
9710 		}
9711 		command_type = OTHER_COMMAND;
9712 		break;
9713 	case CMD_CLOSE_XRI_CN:
9714 	case CMD_ABORT_XRI_CN:
9715 	case CMD_ABORT_XRI_CX:
9716 		/* words 0-2 memcpy should be 0 rserved */
9717 		/* port will send abts */
9718 		abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
9719 		if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
9720 			abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
9721 			fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
9722 		} else
9723 			fip = 0;
9724 
9725 		if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
9726 			/*
9727 			 * The link is down, or the command was ELS_FIP
9728 			 * so the fw does not need to send abts
9729 			 * on the wire.
9730 			 */
9731 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
9732 		else
9733 			bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
9734 		bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
9735 		/* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
9736 		wqe->abort_cmd.rsrvd5 = 0;
9737 		bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
9738 			((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9739 		abort_tag = iocbq->iocb.un.acxri.abortIoTag;
9740 		/*
9741 		 * The abort handler will send us CMD_ABORT_XRI_CN or
9742 		 * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
9743 		 */
9744 		bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
9745 		bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
9746 		bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
9747 		       LPFC_WQE_LENLOC_NONE);
9748 		cmnd = CMD_ABORT_XRI_CX;
9749 		command_type = OTHER_COMMAND;
9750 		xritag = 0;
9751 		break;
9752 	case CMD_XMIT_BLS_RSP64_CX:
9753 		ndlp = (struct lpfc_nodelist *)iocbq->context1;
9754 		/* As BLS ABTS RSP WQE is very different from other WQEs,
9755 		 * we re-construct this WQE here based on information in
9756 		 * iocbq from scratch.
9757 		 */
9758 		memset(wqe, 0, sizeof(union lpfc_wqe));
9759 		/* OX_ID is invariable to who sent ABTS to CT exchange */
9760 		bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
9761 		       bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
9762 		if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
9763 		    LPFC_ABTS_UNSOL_INT) {
9764 			/* ABTS sent by initiator to CT exchange, the
9765 			 * RX_ID field will be filled with the newly
9766 			 * allocated responder XRI.
9767 			 */
9768 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
9769 			       iocbq->sli4_xritag);
9770 		} else {
9771 			/* ABTS sent by responder to CT exchange, the
9772 			 * RX_ID field will be filled with the responder
9773 			 * RX_ID from ABTS.
9774 			 */
9775 			bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
9776 			       bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
9777 		}
9778 		bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
9779 		bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
9780 
9781 		/* Use CT=VPI */
9782 		bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
9783 			ndlp->nlp_DID);
9784 		bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
9785 			iocbq->iocb.ulpContext);
9786 		bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
9787 		bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
9788 			phba->vpi_ids[phba->pport->vpi]);
9789 		bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
9790 		bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
9791 		       LPFC_WQE_LENLOC_NONE);
9792 		/* Overwrite the pre-set comnd type with OTHER_COMMAND */
9793 		command_type = OTHER_COMMAND;
9794 		if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
9795 			bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
9796 			       bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
9797 			bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
9798 			       bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
9799 			bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
9800 			       bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
9801 		}
9802 
9803 		break;
9804 	case CMD_SEND_FRAME:
9805 		bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
9806 		bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
9807 		return 0;
9808 	case CMD_XRI_ABORTED_CX:
9809 	case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
9810 	case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
9811 	case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
9812 	case CMD_FCP_TRSP64_CX: /* Target mode rcv */
9813 	case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
9814 	default:
9815 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9816 				"2014 Invalid command 0x%x\n",
9817 				iocbq->iocb.ulpCommand);
9818 		return IOCB_ERROR;
9819 		break;
9820 	}
9821 
9822 	if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
9823 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
9824 	else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
9825 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
9826 	else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
9827 		bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
9828 	iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
9829 			      LPFC_IO_DIF_INSERT);
9830 	bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
9831 	bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
9832 	wqe->generic.wqe_com.abort_tag = abort_tag;
9833 	bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
9834 	bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
9835 	bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
9836 	bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
9837 	return 0;
9838 }
9839 
9840 /**
9841  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
9842  * @phba: Pointer to HBA context object.
9843  * @ring_number: SLI ring number to issue iocb on.
9844  * @piocb: Pointer to command iocb.
9845  * @flag: Flag indicating if this command can be put into txq.
9846  *
9847  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
9848  * an iocb command to an HBA with SLI-4 interface spec.
9849  *
9850  * This function is called with hbalock held. The function will return success
9851  * after it successfully submit the iocb to firmware or after adding to the
9852  * txq.
9853  **/
9854 static int
9855 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
9856 			 struct lpfc_iocbq *piocb, uint32_t flag)
9857 {
9858 	struct lpfc_sglq *sglq;
9859 	union lpfc_wqe128 wqe;
9860 	struct lpfc_queue *wq;
9861 	struct lpfc_sli_ring *pring;
9862 
9863 	/* Get the WQ */
9864 	if ((piocb->iocb_flag & LPFC_IO_FCP) ||
9865 	    (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
9866 		if (!phba->cfg_fof || (!(piocb->iocb_flag & LPFC_IO_OAS)))
9867 			wq = phba->sli4_hba.fcp_wq[piocb->hba_wqidx];
9868 		else
9869 			wq = phba->sli4_hba.oas_wq;
9870 	} else {
9871 		wq = phba->sli4_hba.els_wq;
9872 	}
9873 
9874 	/* Get corresponding ring */
9875 	pring = wq->pring;
9876 
9877 	/*
9878 	 * The WQE can be either 64 or 128 bytes,
9879 	 */
9880 
9881 	lockdep_assert_held(&phba->hbalock);
9882 
9883 	if (piocb->sli4_xritag == NO_XRI) {
9884 		if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
9885 		    piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
9886 			sglq = NULL;
9887 		else {
9888 			if (!list_empty(&pring->txq)) {
9889 				if (!(flag & SLI_IOCB_RET_IOCB)) {
9890 					__lpfc_sli_ringtx_put(phba,
9891 						pring, piocb);
9892 					return IOCB_SUCCESS;
9893 				} else {
9894 					return IOCB_BUSY;
9895 				}
9896 			} else {
9897 				sglq = __lpfc_sli_get_els_sglq(phba, piocb);
9898 				if (!sglq) {
9899 					if (!(flag & SLI_IOCB_RET_IOCB)) {
9900 						__lpfc_sli_ringtx_put(phba,
9901 								pring,
9902 								piocb);
9903 						return IOCB_SUCCESS;
9904 					} else
9905 						return IOCB_BUSY;
9906 				}
9907 			}
9908 		}
9909 	} else if (piocb->iocb_flag &  LPFC_IO_FCP)
9910 		/* These IO's already have an XRI and a mapped sgl. */
9911 		sglq = NULL;
9912 	else {
9913 		/*
9914 		 * This is a continuation of a commandi,(CX) so this
9915 		 * sglq is on the active list
9916 		 */
9917 		sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
9918 		if (!sglq)
9919 			return IOCB_ERROR;
9920 	}
9921 
9922 	if (sglq) {
9923 		piocb->sli4_lxritag = sglq->sli4_lxritag;
9924 		piocb->sli4_xritag = sglq->sli4_xritag;
9925 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
9926 			return IOCB_ERROR;
9927 	}
9928 
9929 	if (lpfc_sli4_iocb2wqe(phba, piocb, &wqe))
9930 		return IOCB_ERROR;
9931 
9932 	if (lpfc_sli4_wq_put(wq, &wqe))
9933 		return IOCB_ERROR;
9934 	lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
9935 
9936 	return 0;
9937 }
9938 
9939 /**
9940  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
9941  *
9942  * This routine wraps the actual lockless version for issusing IOCB function
9943  * pointer from the lpfc_hba struct.
9944  *
9945  * Return codes:
9946  * IOCB_ERROR - Error
9947  * IOCB_SUCCESS - Success
9948  * IOCB_BUSY - Busy
9949  **/
9950 int
9951 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
9952 		struct lpfc_iocbq *piocb, uint32_t flag)
9953 {
9954 	return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
9955 }
9956 
9957 /**
9958  * lpfc_sli_api_table_setup - Set up sli api function jump table
9959  * @phba: The hba struct for which this call is being executed.
9960  * @dev_grp: The HBA PCI-Device group number.
9961  *
9962  * This routine sets up the SLI interface API function jump table in @phba
9963  * struct.
9964  * Returns: 0 - success, -ENODEV - failure.
9965  **/
9966 int
9967 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
9968 {
9969 
9970 	switch (dev_grp) {
9971 	case LPFC_PCI_DEV_LP:
9972 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
9973 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
9974 		break;
9975 	case LPFC_PCI_DEV_OC:
9976 		phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
9977 		phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
9978 		break;
9979 	default:
9980 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9981 				"1419 Invalid HBA PCI-device group: 0x%x\n",
9982 				dev_grp);
9983 		return -ENODEV;
9984 		break;
9985 	}
9986 	phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
9987 	return 0;
9988 }
9989 
9990 /**
9991  * lpfc_sli4_calc_ring - Calculates which ring to use
9992  * @phba: Pointer to HBA context object.
9993  * @piocb: Pointer to command iocb.
9994  *
9995  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
9996  * hba_wqidx, thus we need to calculate the corresponding ring.
9997  * Since ABORTS must go on the same WQ of the command they are
9998  * aborting, we use command's hba_wqidx.
9999  */
10000 struct lpfc_sli_ring *
10001 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
10002 {
10003 	if (piocb->iocb_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
10004 		if (!(phba->cfg_fof) ||
10005 		    (!(piocb->iocb_flag & LPFC_IO_FOF))) {
10006 			if (unlikely(!phba->sli4_hba.fcp_wq))
10007 				return NULL;
10008 			/*
10009 			 * for abort iocb hba_wqidx should already
10010 			 * be setup based on what work queue we used.
10011 			 */
10012 			if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
10013 				piocb->hba_wqidx =
10014 					lpfc_sli4_scmd_to_wqidx_distr(phba,
10015 							      piocb->context1);
10016 				piocb->hba_wqidx = piocb->hba_wqidx %
10017 					phba->cfg_fcp_io_channel;
10018 			}
10019 			return phba->sli4_hba.fcp_wq[piocb->hba_wqidx]->pring;
10020 		} else {
10021 			if (unlikely(!phba->sli4_hba.oas_wq))
10022 				return NULL;
10023 			piocb->hba_wqidx = 0;
10024 			return phba->sli4_hba.oas_wq->pring;
10025 		}
10026 	} else {
10027 		if (unlikely(!phba->sli4_hba.els_wq))
10028 			return NULL;
10029 		piocb->hba_wqidx = 0;
10030 		return phba->sli4_hba.els_wq->pring;
10031 	}
10032 }
10033 
10034 /**
10035  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
10036  * @phba: Pointer to HBA context object.
10037  * @pring: Pointer to driver SLI ring object.
10038  * @piocb: Pointer to command iocb.
10039  * @flag: Flag indicating if this command can be put into txq.
10040  *
10041  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
10042  * function. This function gets the hbalock and calls
10043  * __lpfc_sli_issue_iocb function and will return the error returned
10044  * by __lpfc_sli_issue_iocb function. This wrapper is used by
10045  * functions which do not hold hbalock.
10046  **/
10047 int
10048 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10049 		    struct lpfc_iocbq *piocb, uint32_t flag)
10050 {
10051 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
10052 	struct lpfc_sli_ring *pring;
10053 	struct lpfc_queue *fpeq;
10054 	struct lpfc_eqe *eqe;
10055 	unsigned long iflags;
10056 	int rc, idx;
10057 
10058 	if (phba->sli_rev == LPFC_SLI_REV4) {
10059 		pring = lpfc_sli4_calc_ring(phba, piocb);
10060 		if (unlikely(pring == NULL))
10061 			return IOCB_ERROR;
10062 
10063 		spin_lock_irqsave(&pring->ring_lock, iflags);
10064 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10065 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
10066 
10067 		if (lpfc_fcp_look_ahead && (piocb->iocb_flag &  LPFC_IO_FCP)) {
10068 			idx = piocb->hba_wqidx;
10069 			hba_eq_hdl = &phba->sli4_hba.hba_eq_hdl[idx];
10070 
10071 			if (atomic_dec_and_test(&hba_eq_hdl->hba_eq_in_use)) {
10072 
10073 				/* Get associated EQ with this index */
10074 				fpeq = phba->sli4_hba.hba_eq[idx];
10075 
10076 				/* Turn off interrupts from this EQ */
10077 				phba->sli4_hba.sli4_eq_clr_intr(fpeq);
10078 
10079 				/*
10080 				 * Process all the events on FCP EQ
10081 				 */
10082 				while ((eqe = lpfc_sli4_eq_get(fpeq))) {
10083 					lpfc_sli4_hba_handle_eqe(phba,
10084 						eqe, idx);
10085 					fpeq->EQ_processed++;
10086 				}
10087 
10088 				/* Always clear and re-arm the EQ */
10089 				phba->sli4_hba.sli4_eq_release(fpeq,
10090 					LPFC_QUEUE_REARM);
10091 			}
10092 			atomic_inc(&hba_eq_hdl->hba_eq_in_use);
10093 		}
10094 	} else {
10095 		/* For now, SLI2/3 will still use hbalock */
10096 		spin_lock_irqsave(&phba->hbalock, iflags);
10097 		rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10098 		spin_unlock_irqrestore(&phba->hbalock, iflags);
10099 	}
10100 	return rc;
10101 }
10102 
10103 /**
10104  * lpfc_extra_ring_setup - Extra ring setup function
10105  * @phba: Pointer to HBA context object.
10106  *
10107  * This function is called while driver attaches with the
10108  * HBA to setup the extra ring. The extra ring is used
10109  * only when driver needs to support target mode functionality
10110  * or IP over FC functionalities.
10111  *
10112  * This function is called with no lock held. SLI3 only.
10113  **/
10114 static int
10115 lpfc_extra_ring_setup( struct lpfc_hba *phba)
10116 {
10117 	struct lpfc_sli *psli;
10118 	struct lpfc_sli_ring *pring;
10119 
10120 	psli = &phba->sli;
10121 
10122 	/* Adjust cmd/rsp ring iocb entries more evenly */
10123 
10124 	/* Take some away from the FCP ring */
10125 	pring = &psli->sli3_ring[LPFC_FCP_RING];
10126 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10127 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10128 	pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10129 	pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10130 
10131 	/* and give them to the extra ring */
10132 	pring = &psli->sli3_ring[LPFC_EXTRA_RING];
10133 
10134 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10135 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10136 	pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10137 	pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10138 
10139 	/* Setup default profile for this ring */
10140 	pring->iotag_max = 4096;
10141 	pring->num_mask = 1;
10142 	pring->prt[0].profile = 0;      /* Mask 0 */
10143 	pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
10144 	pring->prt[0].type = phba->cfg_multi_ring_type;
10145 	pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
10146 	return 0;
10147 }
10148 
10149 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
10150  * @phba: Pointer to HBA context object.
10151  * @iocbq: Pointer to iocb object.
10152  *
10153  * The async_event handler calls this routine when it receives
10154  * an ASYNC_STATUS_CN event from the port.  The port generates
10155  * this event when an Abort Sequence request to an rport fails
10156  * twice in succession.  The abort could be originated by the
10157  * driver or by the port.  The ABTS could have been for an ELS
10158  * or FCP IO.  The port only generates this event when an ABTS
10159  * fails to complete after one retry.
10160  */
10161 static void
10162 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
10163 			  struct lpfc_iocbq *iocbq)
10164 {
10165 	struct lpfc_nodelist *ndlp = NULL;
10166 	uint16_t rpi = 0, vpi = 0;
10167 	struct lpfc_vport *vport = NULL;
10168 
10169 	/* The rpi in the ulpContext is vport-sensitive. */
10170 	vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
10171 	rpi = iocbq->iocb.ulpContext;
10172 
10173 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10174 			"3092 Port generated ABTS async event "
10175 			"on vpi %d rpi %d status 0x%x\n",
10176 			vpi, rpi, iocbq->iocb.ulpStatus);
10177 
10178 	vport = lpfc_find_vport_by_vpid(phba, vpi);
10179 	if (!vport)
10180 		goto err_exit;
10181 	ndlp = lpfc_findnode_rpi(vport, rpi);
10182 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp))
10183 		goto err_exit;
10184 
10185 	if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
10186 		lpfc_sli_abts_recover_port(vport, ndlp);
10187 	return;
10188 
10189  err_exit:
10190 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10191 			"3095 Event Context not found, no "
10192 			"action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
10193 			iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
10194 			vpi, rpi);
10195 }
10196 
10197 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
10198  * @phba: pointer to HBA context object.
10199  * @ndlp: nodelist pointer for the impacted rport.
10200  * @axri: pointer to the wcqe containing the failed exchange.
10201  *
10202  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
10203  * port.  The port generates this event when an abort exchange request to an
10204  * rport fails twice in succession with no reply.  The abort could be originated
10205  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
10206  */
10207 void
10208 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
10209 			   struct lpfc_nodelist *ndlp,
10210 			   struct sli4_wcqe_xri_aborted *axri)
10211 {
10212 	struct lpfc_vport *vport;
10213 	uint32_t ext_status = 0;
10214 
10215 	if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)) {
10216 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10217 				"3115 Node Context not found, driver "
10218 				"ignoring abts err event\n");
10219 		return;
10220 	}
10221 
10222 	vport = ndlp->vport;
10223 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10224 			"3116 Port generated FCP XRI ABORT event on "
10225 			"vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
10226 			ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
10227 			bf_get(lpfc_wcqe_xa_xri, axri),
10228 			bf_get(lpfc_wcqe_xa_status, axri),
10229 			axri->parameter);
10230 
10231 	/*
10232 	 * Catch the ABTS protocol failure case.  Older OCe FW releases returned
10233 	 * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
10234 	 * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
10235 	 */
10236 	ext_status = axri->parameter & IOERR_PARAM_MASK;
10237 	if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
10238 	    ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
10239 		lpfc_sli_abts_recover_port(vport, ndlp);
10240 }
10241 
10242 /**
10243  * lpfc_sli_async_event_handler - ASYNC iocb handler function
10244  * @phba: Pointer to HBA context object.
10245  * @pring: Pointer to driver SLI ring object.
10246  * @iocbq: Pointer to iocb object.
10247  *
10248  * This function is called by the slow ring event handler
10249  * function when there is an ASYNC event iocb in the ring.
10250  * This function is called with no lock held.
10251  * Currently this function handles only temperature related
10252  * ASYNC events. The function decodes the temperature sensor
10253  * event message and posts events for the management applications.
10254  **/
10255 static void
10256 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
10257 	struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
10258 {
10259 	IOCB_t *icmd;
10260 	uint16_t evt_code;
10261 	struct temp_event temp_event_data;
10262 	struct Scsi_Host *shost;
10263 	uint32_t *iocb_w;
10264 
10265 	icmd = &iocbq->iocb;
10266 	evt_code = icmd->un.asyncstat.evt_code;
10267 
10268 	switch (evt_code) {
10269 	case ASYNC_TEMP_WARN:
10270 	case ASYNC_TEMP_SAFE:
10271 		temp_event_data.data = (uint32_t) icmd->ulpContext;
10272 		temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
10273 		if (evt_code == ASYNC_TEMP_WARN) {
10274 			temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
10275 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
10276 				"0347 Adapter is very hot, please take "
10277 				"corrective action. temperature : %d Celsius\n",
10278 				(uint32_t) icmd->ulpContext);
10279 		} else {
10280 			temp_event_data.event_code = LPFC_NORMAL_TEMP;
10281 			lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
10282 				"0340 Adapter temperature is OK now. "
10283 				"temperature : %d Celsius\n",
10284 				(uint32_t) icmd->ulpContext);
10285 		}
10286 
10287 		/* Send temperature change event to applications */
10288 		shost = lpfc_shost_from_vport(phba->pport);
10289 		fc_host_post_vendor_event(shost, fc_get_event_number(),
10290 			sizeof(temp_event_data), (char *) &temp_event_data,
10291 			LPFC_NL_VENDOR_ID);
10292 		break;
10293 	case ASYNC_STATUS_CN:
10294 		lpfc_sli_abts_err_handler(phba, iocbq);
10295 		break;
10296 	default:
10297 		iocb_w = (uint32_t *) icmd;
10298 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10299 			"0346 Ring %d handler: unexpected ASYNC_STATUS"
10300 			" evt_code 0x%x\n"
10301 			"W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
10302 			"W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
10303 			"W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
10304 			"W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
10305 			pring->ringno, icmd->un.asyncstat.evt_code,
10306 			iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
10307 			iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
10308 			iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
10309 			iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
10310 
10311 		break;
10312 	}
10313 }
10314 
10315 
10316 /**
10317  * lpfc_sli4_setup - SLI ring setup function
10318  * @phba: Pointer to HBA context object.
10319  *
10320  * lpfc_sli_setup sets up rings of the SLI interface with
10321  * number of iocbs per ring and iotags. This function is
10322  * called while driver attach to the HBA and before the
10323  * interrupts are enabled. So there is no need for locking.
10324  *
10325  * This function always returns 0.
10326  **/
10327 int
10328 lpfc_sli4_setup(struct lpfc_hba *phba)
10329 {
10330 	struct lpfc_sli_ring *pring;
10331 
10332 	pring = phba->sli4_hba.els_wq->pring;
10333 	pring->num_mask = LPFC_MAX_RING_MASK;
10334 	pring->prt[0].profile = 0;	/* Mask 0 */
10335 	pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10336 	pring->prt[0].type = FC_TYPE_ELS;
10337 	pring->prt[0].lpfc_sli_rcv_unsol_event =
10338 	    lpfc_els_unsol_event;
10339 	pring->prt[1].profile = 0;	/* Mask 1 */
10340 	pring->prt[1].rctl = FC_RCTL_ELS_REP;
10341 	pring->prt[1].type = FC_TYPE_ELS;
10342 	pring->prt[1].lpfc_sli_rcv_unsol_event =
10343 	    lpfc_els_unsol_event;
10344 	pring->prt[2].profile = 0;	/* Mask 2 */
10345 	/* NameServer Inquiry */
10346 	pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10347 	/* NameServer */
10348 	pring->prt[2].type = FC_TYPE_CT;
10349 	pring->prt[2].lpfc_sli_rcv_unsol_event =
10350 	    lpfc_ct_unsol_event;
10351 	pring->prt[3].profile = 0;	/* Mask 3 */
10352 	/* NameServer response */
10353 	pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10354 	/* NameServer */
10355 	pring->prt[3].type = FC_TYPE_CT;
10356 	pring->prt[3].lpfc_sli_rcv_unsol_event =
10357 	    lpfc_ct_unsol_event;
10358 	return 0;
10359 }
10360 
10361 /**
10362  * lpfc_sli_setup - SLI ring setup function
10363  * @phba: Pointer to HBA context object.
10364  *
10365  * lpfc_sli_setup sets up rings of the SLI interface with
10366  * number of iocbs per ring and iotags. This function is
10367  * called while driver attach to the HBA and before the
10368  * interrupts are enabled. So there is no need for locking.
10369  *
10370  * This function always returns 0. SLI3 only.
10371  **/
10372 int
10373 lpfc_sli_setup(struct lpfc_hba *phba)
10374 {
10375 	int i, totiocbsize = 0;
10376 	struct lpfc_sli *psli = &phba->sli;
10377 	struct lpfc_sli_ring *pring;
10378 
10379 	psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
10380 	psli->sli_flag = 0;
10381 
10382 	psli->iocbq_lookup = NULL;
10383 	psli->iocbq_lookup_len = 0;
10384 	psli->last_iotag = 0;
10385 
10386 	for (i = 0; i < psli->num_rings; i++) {
10387 		pring = &psli->sli3_ring[i];
10388 		switch (i) {
10389 		case LPFC_FCP_RING:	/* ring 0 - FCP */
10390 			/* numCiocb and numRiocb are used in config_port */
10391 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
10392 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
10393 			pring->sli.sli3.numCiocb +=
10394 				SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10395 			pring->sli.sli3.numRiocb +=
10396 				SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10397 			pring->sli.sli3.numCiocb +=
10398 				SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10399 			pring->sli.sli3.numRiocb +=
10400 				SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10401 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10402 							SLI3_IOCB_CMD_SIZE :
10403 							SLI2_IOCB_CMD_SIZE;
10404 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10405 							SLI3_IOCB_RSP_SIZE :
10406 							SLI2_IOCB_RSP_SIZE;
10407 			pring->iotag_ctr = 0;
10408 			pring->iotag_max =
10409 			    (phba->cfg_hba_queue_depth * 2);
10410 			pring->fast_iotag = pring->iotag_max;
10411 			pring->num_mask = 0;
10412 			break;
10413 		case LPFC_EXTRA_RING:	/* ring 1 - EXTRA */
10414 			/* numCiocb and numRiocb are used in config_port */
10415 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
10416 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
10417 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10418 							SLI3_IOCB_CMD_SIZE :
10419 							SLI2_IOCB_CMD_SIZE;
10420 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10421 							SLI3_IOCB_RSP_SIZE :
10422 							SLI2_IOCB_RSP_SIZE;
10423 			pring->iotag_max = phba->cfg_hba_queue_depth;
10424 			pring->num_mask = 0;
10425 			break;
10426 		case LPFC_ELS_RING:	/* ring 2 - ELS / CT */
10427 			/* numCiocb and numRiocb are used in config_port */
10428 			pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
10429 			pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
10430 			pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10431 							SLI3_IOCB_CMD_SIZE :
10432 							SLI2_IOCB_CMD_SIZE;
10433 			pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10434 							SLI3_IOCB_RSP_SIZE :
10435 							SLI2_IOCB_RSP_SIZE;
10436 			pring->fast_iotag = 0;
10437 			pring->iotag_ctr = 0;
10438 			pring->iotag_max = 4096;
10439 			pring->lpfc_sli_rcv_async_status =
10440 				lpfc_sli_async_event_handler;
10441 			pring->num_mask = LPFC_MAX_RING_MASK;
10442 			pring->prt[0].profile = 0;	/* Mask 0 */
10443 			pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10444 			pring->prt[0].type = FC_TYPE_ELS;
10445 			pring->prt[0].lpfc_sli_rcv_unsol_event =
10446 			    lpfc_els_unsol_event;
10447 			pring->prt[1].profile = 0;	/* Mask 1 */
10448 			pring->prt[1].rctl = FC_RCTL_ELS_REP;
10449 			pring->prt[1].type = FC_TYPE_ELS;
10450 			pring->prt[1].lpfc_sli_rcv_unsol_event =
10451 			    lpfc_els_unsol_event;
10452 			pring->prt[2].profile = 0;	/* Mask 2 */
10453 			/* NameServer Inquiry */
10454 			pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10455 			/* NameServer */
10456 			pring->prt[2].type = FC_TYPE_CT;
10457 			pring->prt[2].lpfc_sli_rcv_unsol_event =
10458 			    lpfc_ct_unsol_event;
10459 			pring->prt[3].profile = 0;	/* Mask 3 */
10460 			/* NameServer response */
10461 			pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10462 			/* NameServer */
10463 			pring->prt[3].type = FC_TYPE_CT;
10464 			pring->prt[3].lpfc_sli_rcv_unsol_event =
10465 			    lpfc_ct_unsol_event;
10466 			break;
10467 		}
10468 		totiocbsize += (pring->sli.sli3.numCiocb *
10469 			pring->sli.sli3.sizeCiocb) +
10470 			(pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
10471 	}
10472 	if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
10473 		/* Too many cmd / rsp ring entries in SLI2 SLIM */
10474 		printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
10475 		       "SLI2 SLIM Data: x%x x%lx\n",
10476 		       phba->brd_no, totiocbsize,
10477 		       (unsigned long) MAX_SLIM_IOCB_SIZE);
10478 	}
10479 	if (phba->cfg_multi_ring_support == 2)
10480 		lpfc_extra_ring_setup(phba);
10481 
10482 	return 0;
10483 }
10484 
10485 /**
10486  * lpfc_sli4_queue_init - Queue initialization function
10487  * @phba: Pointer to HBA context object.
10488  *
10489  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
10490  * ring. This function also initializes ring indices of each ring.
10491  * This function is called during the initialization of the SLI
10492  * interface of an HBA.
10493  * This function is called with no lock held and always returns
10494  * 1.
10495  **/
10496 void
10497 lpfc_sli4_queue_init(struct lpfc_hba *phba)
10498 {
10499 	struct lpfc_sli *psli;
10500 	struct lpfc_sli_ring *pring;
10501 	int i;
10502 
10503 	psli = &phba->sli;
10504 	spin_lock_irq(&phba->hbalock);
10505 	INIT_LIST_HEAD(&psli->mboxq);
10506 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
10507 	/* Initialize list headers for txq and txcmplq as double linked lists */
10508 	for (i = 0; i < phba->cfg_fcp_io_channel; i++) {
10509 		pring = phba->sli4_hba.fcp_wq[i]->pring;
10510 		pring->flag = 0;
10511 		pring->ringno = LPFC_FCP_RING;
10512 		INIT_LIST_HEAD(&pring->txq);
10513 		INIT_LIST_HEAD(&pring->txcmplq);
10514 		INIT_LIST_HEAD(&pring->iocb_continueq);
10515 		spin_lock_init(&pring->ring_lock);
10516 	}
10517 	for (i = 0; i < phba->cfg_nvme_io_channel; i++) {
10518 		pring = phba->sli4_hba.nvme_wq[i]->pring;
10519 		pring->flag = 0;
10520 		pring->ringno = LPFC_FCP_RING;
10521 		INIT_LIST_HEAD(&pring->txq);
10522 		INIT_LIST_HEAD(&pring->txcmplq);
10523 		INIT_LIST_HEAD(&pring->iocb_continueq);
10524 		spin_lock_init(&pring->ring_lock);
10525 	}
10526 	pring = phba->sli4_hba.els_wq->pring;
10527 	pring->flag = 0;
10528 	pring->ringno = LPFC_ELS_RING;
10529 	INIT_LIST_HEAD(&pring->txq);
10530 	INIT_LIST_HEAD(&pring->txcmplq);
10531 	INIT_LIST_HEAD(&pring->iocb_continueq);
10532 	spin_lock_init(&pring->ring_lock);
10533 
10534 	if (phba->cfg_nvme_io_channel) {
10535 		pring = phba->sli4_hba.nvmels_wq->pring;
10536 		pring->flag = 0;
10537 		pring->ringno = LPFC_ELS_RING;
10538 		INIT_LIST_HEAD(&pring->txq);
10539 		INIT_LIST_HEAD(&pring->txcmplq);
10540 		INIT_LIST_HEAD(&pring->iocb_continueq);
10541 		spin_lock_init(&pring->ring_lock);
10542 	}
10543 
10544 	if (phba->cfg_fof) {
10545 		pring = phba->sli4_hba.oas_wq->pring;
10546 		pring->flag = 0;
10547 		pring->ringno = LPFC_FCP_RING;
10548 		INIT_LIST_HEAD(&pring->txq);
10549 		INIT_LIST_HEAD(&pring->txcmplq);
10550 		INIT_LIST_HEAD(&pring->iocb_continueq);
10551 		spin_lock_init(&pring->ring_lock);
10552 	}
10553 
10554 	spin_unlock_irq(&phba->hbalock);
10555 }
10556 
10557 /**
10558  * lpfc_sli_queue_init - Queue initialization function
10559  * @phba: Pointer to HBA context object.
10560  *
10561  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
10562  * ring. This function also initializes ring indices of each ring.
10563  * This function is called during the initialization of the SLI
10564  * interface of an HBA.
10565  * This function is called with no lock held and always returns
10566  * 1.
10567  **/
10568 void
10569 lpfc_sli_queue_init(struct lpfc_hba *phba)
10570 {
10571 	struct lpfc_sli *psli;
10572 	struct lpfc_sli_ring *pring;
10573 	int i;
10574 
10575 	psli = &phba->sli;
10576 	spin_lock_irq(&phba->hbalock);
10577 	INIT_LIST_HEAD(&psli->mboxq);
10578 	INIT_LIST_HEAD(&psli->mboxq_cmpl);
10579 	/* Initialize list headers for txq and txcmplq as double linked lists */
10580 	for (i = 0; i < psli->num_rings; i++) {
10581 		pring = &psli->sli3_ring[i];
10582 		pring->ringno = i;
10583 		pring->sli.sli3.next_cmdidx  = 0;
10584 		pring->sli.sli3.local_getidx = 0;
10585 		pring->sli.sli3.cmdidx = 0;
10586 		INIT_LIST_HEAD(&pring->iocb_continueq);
10587 		INIT_LIST_HEAD(&pring->iocb_continue_saveq);
10588 		INIT_LIST_HEAD(&pring->postbufq);
10589 		pring->flag = 0;
10590 		INIT_LIST_HEAD(&pring->txq);
10591 		INIT_LIST_HEAD(&pring->txcmplq);
10592 		spin_lock_init(&pring->ring_lock);
10593 	}
10594 	spin_unlock_irq(&phba->hbalock);
10595 }
10596 
10597 /**
10598  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
10599  * @phba: Pointer to HBA context object.
10600  *
10601  * This routine flushes the mailbox command subsystem. It will unconditionally
10602  * flush all the mailbox commands in the three possible stages in the mailbox
10603  * command sub-system: pending mailbox command queue; the outstanding mailbox
10604  * command; and completed mailbox command queue. It is caller's responsibility
10605  * to make sure that the driver is in the proper state to flush the mailbox
10606  * command sub-system. Namely, the posting of mailbox commands into the
10607  * pending mailbox command queue from the various clients must be stopped;
10608  * either the HBA is in a state that it will never works on the outstanding
10609  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
10610  * mailbox command has been completed.
10611  **/
10612 static void
10613 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
10614 {
10615 	LIST_HEAD(completions);
10616 	struct lpfc_sli *psli = &phba->sli;
10617 	LPFC_MBOXQ_t *pmb;
10618 	unsigned long iflag;
10619 
10620 	/* Disable softirqs, including timers from obtaining phba->hbalock */
10621 	local_bh_disable();
10622 
10623 	/* Flush all the mailbox commands in the mbox system */
10624 	spin_lock_irqsave(&phba->hbalock, iflag);
10625 
10626 	/* The pending mailbox command queue */
10627 	list_splice_init(&phba->sli.mboxq, &completions);
10628 	/* The outstanding active mailbox command */
10629 	if (psli->mbox_active) {
10630 		list_add_tail(&psli->mbox_active->list, &completions);
10631 		psli->mbox_active = NULL;
10632 		psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10633 	}
10634 	/* The completed mailbox command queue */
10635 	list_splice_init(&phba->sli.mboxq_cmpl, &completions);
10636 	spin_unlock_irqrestore(&phba->hbalock, iflag);
10637 
10638 	/* Enable softirqs again, done with phba->hbalock */
10639 	local_bh_enable();
10640 
10641 	/* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
10642 	while (!list_empty(&completions)) {
10643 		list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
10644 		pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
10645 		if (pmb->mbox_cmpl)
10646 			pmb->mbox_cmpl(phba, pmb);
10647 	}
10648 }
10649 
10650 /**
10651  * lpfc_sli_host_down - Vport cleanup function
10652  * @vport: Pointer to virtual port object.
10653  *
10654  * lpfc_sli_host_down is called to clean up the resources
10655  * associated with a vport before destroying virtual
10656  * port data structures.
10657  * This function does following operations:
10658  * - Free discovery resources associated with this virtual
10659  *   port.
10660  * - Free iocbs associated with this virtual port in
10661  *   the txq.
10662  * - Send abort for all iocb commands associated with this
10663  *   vport in txcmplq.
10664  *
10665  * This function is called with no lock held and always returns 1.
10666  **/
10667 int
10668 lpfc_sli_host_down(struct lpfc_vport *vport)
10669 {
10670 	LIST_HEAD(completions);
10671 	struct lpfc_hba *phba = vport->phba;
10672 	struct lpfc_sli *psli = &phba->sli;
10673 	struct lpfc_queue *qp = NULL;
10674 	struct lpfc_sli_ring *pring;
10675 	struct lpfc_iocbq *iocb, *next_iocb;
10676 	int i;
10677 	unsigned long flags = 0;
10678 	uint16_t prev_pring_flag;
10679 
10680 	lpfc_cleanup_discovery_resources(vport);
10681 
10682 	spin_lock_irqsave(&phba->hbalock, flags);
10683 
10684 	/*
10685 	 * Error everything on the txq since these iocbs
10686 	 * have not been given to the FW yet.
10687 	 * Also issue ABTS for everything on the txcmplq
10688 	 */
10689 	if (phba->sli_rev != LPFC_SLI_REV4) {
10690 		for (i = 0; i < psli->num_rings; i++) {
10691 			pring = &psli->sli3_ring[i];
10692 			prev_pring_flag = pring->flag;
10693 			/* Only slow rings */
10694 			if (pring->ringno == LPFC_ELS_RING) {
10695 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10696 				/* Set the lpfc data pending flag */
10697 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10698 			}
10699 			list_for_each_entry_safe(iocb, next_iocb,
10700 						 &pring->txq, list) {
10701 				if (iocb->vport != vport)
10702 					continue;
10703 				list_move_tail(&iocb->list, &completions);
10704 			}
10705 			list_for_each_entry_safe(iocb, next_iocb,
10706 						 &pring->txcmplq, list) {
10707 				if (iocb->vport != vport)
10708 					continue;
10709 				lpfc_sli_issue_abort_iotag(phba, pring, iocb);
10710 			}
10711 			pring->flag = prev_pring_flag;
10712 		}
10713 	} else {
10714 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
10715 			pring = qp->pring;
10716 			if (!pring)
10717 				continue;
10718 			if (pring == phba->sli4_hba.els_wq->pring) {
10719 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10720 				/* Set the lpfc data pending flag */
10721 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10722 			}
10723 			prev_pring_flag = pring->flag;
10724 			spin_lock_irq(&pring->ring_lock);
10725 			list_for_each_entry_safe(iocb, next_iocb,
10726 						 &pring->txq, list) {
10727 				if (iocb->vport != vport)
10728 					continue;
10729 				list_move_tail(&iocb->list, &completions);
10730 			}
10731 			spin_unlock_irq(&pring->ring_lock);
10732 			list_for_each_entry_safe(iocb, next_iocb,
10733 						 &pring->txcmplq, list) {
10734 				if (iocb->vport != vport)
10735 					continue;
10736 				lpfc_sli_issue_abort_iotag(phba, pring, iocb);
10737 			}
10738 			pring->flag = prev_pring_flag;
10739 		}
10740 	}
10741 	spin_unlock_irqrestore(&phba->hbalock, flags);
10742 
10743 	/* Cancel all the IOCBs from the completions list */
10744 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
10745 			      IOERR_SLI_DOWN);
10746 	return 1;
10747 }
10748 
10749 /**
10750  * lpfc_sli_hba_down - Resource cleanup function for the HBA
10751  * @phba: Pointer to HBA context object.
10752  *
10753  * This function cleans up all iocb, buffers, mailbox commands
10754  * while shutting down the HBA. This function is called with no
10755  * lock held and always returns 1.
10756  * This function does the following to cleanup driver resources:
10757  * - Free discovery resources for each virtual port
10758  * - Cleanup any pending fabric iocbs
10759  * - Iterate through the iocb txq and free each entry
10760  *   in the list.
10761  * - Free up any buffer posted to the HBA
10762  * - Free mailbox commands in the mailbox queue.
10763  **/
10764 int
10765 lpfc_sli_hba_down(struct lpfc_hba *phba)
10766 {
10767 	LIST_HEAD(completions);
10768 	struct lpfc_sli *psli = &phba->sli;
10769 	struct lpfc_queue *qp = NULL;
10770 	struct lpfc_sli_ring *pring;
10771 	struct lpfc_dmabuf *buf_ptr;
10772 	unsigned long flags = 0;
10773 	int i;
10774 
10775 	/* Shutdown the mailbox command sub-system */
10776 	lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
10777 
10778 	lpfc_hba_down_prep(phba);
10779 
10780 	/* Disable softirqs, including timers from obtaining phba->hbalock */
10781 	local_bh_disable();
10782 
10783 	lpfc_fabric_abort_hba(phba);
10784 
10785 	spin_lock_irqsave(&phba->hbalock, flags);
10786 
10787 	/*
10788 	 * Error everything on the txq since these iocbs
10789 	 * have not been given to the FW yet.
10790 	 */
10791 	if (phba->sli_rev != LPFC_SLI_REV4) {
10792 		for (i = 0; i < psli->num_rings; i++) {
10793 			pring = &psli->sli3_ring[i];
10794 			/* Only slow rings */
10795 			if (pring->ringno == LPFC_ELS_RING) {
10796 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10797 				/* Set the lpfc data pending flag */
10798 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10799 			}
10800 			list_splice_init(&pring->txq, &completions);
10801 		}
10802 	} else {
10803 		list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
10804 			pring = qp->pring;
10805 			if (!pring)
10806 				continue;
10807 			spin_lock_irq(&pring->ring_lock);
10808 			list_splice_init(&pring->txq, &completions);
10809 			spin_unlock_irq(&pring->ring_lock);
10810 			if (pring == phba->sli4_hba.els_wq->pring) {
10811 				pring->flag |= LPFC_DEFERRED_RING_EVENT;
10812 				/* Set the lpfc data pending flag */
10813 				set_bit(LPFC_DATA_READY, &phba->data_flags);
10814 			}
10815 		}
10816 	}
10817 	spin_unlock_irqrestore(&phba->hbalock, flags);
10818 
10819 	/* Cancel all the IOCBs from the completions list */
10820 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
10821 			      IOERR_SLI_DOWN);
10822 
10823 	spin_lock_irqsave(&phba->hbalock, flags);
10824 	list_splice_init(&phba->elsbuf, &completions);
10825 	phba->elsbuf_cnt = 0;
10826 	phba->elsbuf_prev_cnt = 0;
10827 	spin_unlock_irqrestore(&phba->hbalock, flags);
10828 
10829 	while (!list_empty(&completions)) {
10830 		list_remove_head(&completions, buf_ptr,
10831 			struct lpfc_dmabuf, list);
10832 		lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
10833 		kfree(buf_ptr);
10834 	}
10835 
10836 	/* Enable softirqs again, done with phba->hbalock */
10837 	local_bh_enable();
10838 
10839 	/* Return any active mbox cmds */
10840 	del_timer_sync(&psli->mbox_tmo);
10841 
10842 	spin_lock_irqsave(&phba->pport->work_port_lock, flags);
10843 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
10844 	spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
10845 
10846 	return 1;
10847 }
10848 
10849 /**
10850  * lpfc_sli_pcimem_bcopy - SLI memory copy function
10851  * @srcp: Source memory pointer.
10852  * @destp: Destination memory pointer.
10853  * @cnt: Number of words required to be copied.
10854  *
10855  * This function is used for copying data between driver memory
10856  * and the SLI memory. This function also changes the endianness
10857  * of each word if native endianness is different from SLI
10858  * endianness. This function can be called with or without
10859  * lock.
10860  **/
10861 void
10862 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
10863 {
10864 	uint32_t *src = srcp;
10865 	uint32_t *dest = destp;
10866 	uint32_t ldata;
10867 	int i;
10868 
10869 	for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
10870 		ldata = *src;
10871 		ldata = le32_to_cpu(ldata);
10872 		*dest = ldata;
10873 		src++;
10874 		dest++;
10875 	}
10876 }
10877 
10878 
10879 /**
10880  * lpfc_sli_bemem_bcopy - SLI memory copy function
10881  * @srcp: Source memory pointer.
10882  * @destp: Destination memory pointer.
10883  * @cnt: Number of words required to be copied.
10884  *
10885  * This function is used for copying data between a data structure
10886  * with big endian representation to local endianness.
10887  * This function can be called with or without lock.
10888  **/
10889 void
10890 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
10891 {
10892 	uint32_t *src = srcp;
10893 	uint32_t *dest = destp;
10894 	uint32_t ldata;
10895 	int i;
10896 
10897 	for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
10898 		ldata = *src;
10899 		ldata = be32_to_cpu(ldata);
10900 		*dest = ldata;
10901 		src++;
10902 		dest++;
10903 	}
10904 }
10905 
10906 /**
10907  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
10908  * @phba: Pointer to HBA context object.
10909  * @pring: Pointer to driver SLI ring object.
10910  * @mp: Pointer to driver buffer object.
10911  *
10912  * This function is called with no lock held.
10913  * It always return zero after adding the buffer to the postbufq
10914  * buffer list.
10915  **/
10916 int
10917 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10918 			 struct lpfc_dmabuf *mp)
10919 {
10920 	/* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
10921 	   later */
10922 	spin_lock_irq(&phba->hbalock);
10923 	list_add_tail(&mp->list, &pring->postbufq);
10924 	pring->postbufq_cnt++;
10925 	spin_unlock_irq(&phba->hbalock);
10926 	return 0;
10927 }
10928 
10929 /**
10930  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
10931  * @phba: Pointer to HBA context object.
10932  *
10933  * When HBQ is enabled, buffers are searched based on tags. This function
10934  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
10935  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
10936  * does not conflict with tags of buffer posted for unsolicited events.
10937  * The function returns the allocated tag. The function is called with
10938  * no locks held.
10939  **/
10940 uint32_t
10941 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
10942 {
10943 	spin_lock_irq(&phba->hbalock);
10944 	phba->buffer_tag_count++;
10945 	/*
10946 	 * Always set the QUE_BUFTAG_BIT to distiguish between
10947 	 * a tag assigned by HBQ.
10948 	 */
10949 	phba->buffer_tag_count |= QUE_BUFTAG_BIT;
10950 	spin_unlock_irq(&phba->hbalock);
10951 	return phba->buffer_tag_count;
10952 }
10953 
10954 /**
10955  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
10956  * @phba: Pointer to HBA context object.
10957  * @pring: Pointer to driver SLI ring object.
10958  * @tag: Buffer tag.
10959  *
10960  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
10961  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
10962  * iocb is posted to the response ring with the tag of the buffer.
10963  * This function searches the pring->postbufq list using the tag
10964  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
10965  * iocb. If the buffer is found then lpfc_dmabuf object of the
10966  * buffer is returned to the caller else NULL is returned.
10967  * This function is called with no lock held.
10968  **/
10969 struct lpfc_dmabuf *
10970 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10971 			uint32_t tag)
10972 {
10973 	struct lpfc_dmabuf *mp, *next_mp;
10974 	struct list_head *slp = &pring->postbufq;
10975 
10976 	/* Search postbufq, from the beginning, looking for a match on tag */
10977 	spin_lock_irq(&phba->hbalock);
10978 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
10979 		if (mp->buffer_tag == tag) {
10980 			list_del_init(&mp->list);
10981 			pring->postbufq_cnt--;
10982 			spin_unlock_irq(&phba->hbalock);
10983 			return mp;
10984 		}
10985 	}
10986 
10987 	spin_unlock_irq(&phba->hbalock);
10988 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10989 			"0402 Cannot find virtual addr for buffer tag on "
10990 			"ring %d Data x%lx x%p x%p x%x\n",
10991 			pring->ringno, (unsigned long) tag,
10992 			slp->next, slp->prev, pring->postbufq_cnt);
10993 
10994 	return NULL;
10995 }
10996 
10997 /**
10998  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
10999  * @phba: Pointer to HBA context object.
11000  * @pring: Pointer to driver SLI ring object.
11001  * @phys: DMA address of the buffer.
11002  *
11003  * This function searches the buffer list using the dma_address
11004  * of unsolicited event to find the driver's lpfc_dmabuf object
11005  * corresponding to the dma_address. The function returns the
11006  * lpfc_dmabuf object if a buffer is found else it returns NULL.
11007  * This function is called by the ct and els unsolicited event
11008  * handlers to get the buffer associated with the unsolicited
11009  * event.
11010  *
11011  * This function is called with no lock held.
11012  **/
11013 struct lpfc_dmabuf *
11014 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11015 			 dma_addr_t phys)
11016 {
11017 	struct lpfc_dmabuf *mp, *next_mp;
11018 	struct list_head *slp = &pring->postbufq;
11019 
11020 	/* Search postbufq, from the beginning, looking for a match on phys */
11021 	spin_lock_irq(&phba->hbalock);
11022 	list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11023 		if (mp->phys == phys) {
11024 			list_del_init(&mp->list);
11025 			pring->postbufq_cnt--;
11026 			spin_unlock_irq(&phba->hbalock);
11027 			return mp;
11028 		}
11029 	}
11030 
11031 	spin_unlock_irq(&phba->hbalock);
11032 	lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11033 			"0410 Cannot find virtual addr for mapped buf on "
11034 			"ring %d Data x%llx x%p x%p x%x\n",
11035 			pring->ringno, (unsigned long long)phys,
11036 			slp->next, slp->prev, pring->postbufq_cnt);
11037 	return NULL;
11038 }
11039 
11040 /**
11041  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
11042  * @phba: Pointer to HBA context object.
11043  * @cmdiocb: Pointer to driver command iocb object.
11044  * @rspiocb: Pointer to driver response iocb object.
11045  *
11046  * This function is the completion handler for the abort iocbs for
11047  * ELS commands. This function is called from the ELS ring event
11048  * handler with no lock held. This function frees memory resources
11049  * associated with the abort iocb.
11050  **/
11051 static void
11052 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11053 			struct lpfc_iocbq *rspiocb)
11054 {
11055 	IOCB_t *irsp = &rspiocb->iocb;
11056 	uint16_t abort_iotag, abort_context;
11057 	struct lpfc_iocbq *abort_iocb = NULL;
11058 
11059 	if (irsp->ulpStatus) {
11060 
11061 		/*
11062 		 * Assume that the port already completed and returned, or
11063 		 * will return the iocb. Just Log the message.
11064 		 */
11065 		abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
11066 		abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
11067 
11068 		spin_lock_irq(&phba->hbalock);
11069 		if (phba->sli_rev < LPFC_SLI_REV4) {
11070 			if (irsp->ulpCommand == CMD_ABORT_XRI_CX &&
11071 			    irsp->ulpStatus == IOSTAT_LOCAL_REJECT &&
11072 			    irsp->un.ulpWord[4] == IOERR_ABORT_REQUESTED) {
11073 				spin_unlock_irq(&phba->hbalock);
11074 				goto release_iocb;
11075 			}
11076 			if (abort_iotag != 0 &&
11077 				abort_iotag <= phba->sli.last_iotag)
11078 				abort_iocb =
11079 					phba->sli.iocbq_lookup[abort_iotag];
11080 		} else
11081 			/* For sli4 the abort_tag is the XRI,
11082 			 * so the abort routine puts the iotag  of the iocb
11083 			 * being aborted in the context field of the abort
11084 			 * IOCB.
11085 			 */
11086 			abort_iocb = phba->sli.iocbq_lookup[abort_context];
11087 
11088 		lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
11089 				"0327 Cannot abort els iocb %p "
11090 				"with tag %x context %x, abort status %x, "
11091 				"abort code %x\n",
11092 				abort_iocb, abort_iotag, abort_context,
11093 				irsp->ulpStatus, irsp->un.ulpWord[4]);
11094 
11095 		spin_unlock_irq(&phba->hbalock);
11096 	}
11097 release_iocb:
11098 	lpfc_sli_release_iocbq(phba, cmdiocb);
11099 	return;
11100 }
11101 
11102 /**
11103  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
11104  * @phba: Pointer to HBA context object.
11105  * @cmdiocb: Pointer to driver command iocb object.
11106  * @rspiocb: Pointer to driver response iocb object.
11107  *
11108  * The function is called from SLI ring event handler with no
11109  * lock held. This function is the completion handler for ELS commands
11110  * which are aborted. The function frees memory resources used for
11111  * the aborted ELS commands.
11112  **/
11113 static void
11114 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11115 		     struct lpfc_iocbq *rspiocb)
11116 {
11117 	IOCB_t *irsp = &rspiocb->iocb;
11118 
11119 	/* ELS cmd tag <ulpIoTag> completes */
11120 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
11121 			"0139 Ignoring ELS cmd tag x%x completion Data: "
11122 			"x%x x%x x%x\n",
11123 			irsp->ulpIoTag, irsp->ulpStatus,
11124 			irsp->un.ulpWord[4], irsp->ulpTimeout);
11125 	if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
11126 		lpfc_ct_free_iocb(phba, cmdiocb);
11127 	else
11128 		lpfc_els_free_iocb(phba, cmdiocb);
11129 	return;
11130 }
11131 
11132 /**
11133  * lpfc_sli_abort_iotag_issue - Issue abort for a command iocb
11134  * @phba: Pointer to HBA context object.
11135  * @pring: Pointer to driver SLI ring object.
11136  * @cmdiocb: Pointer to driver command iocb object.
11137  *
11138  * This function issues an abort iocb for the provided command iocb down to
11139  * the port. Other than the case the outstanding command iocb is an abort
11140  * request, this function issues abort out unconditionally. This function is
11141  * called with hbalock held. The function returns 0 when it fails due to
11142  * memory allocation failure or when the command iocb is an abort request.
11143  **/
11144 static int
11145 lpfc_sli_abort_iotag_issue(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11146 			   struct lpfc_iocbq *cmdiocb)
11147 {
11148 	struct lpfc_vport *vport = cmdiocb->vport;
11149 	struct lpfc_iocbq *abtsiocbp;
11150 	IOCB_t *icmd = NULL;
11151 	IOCB_t *iabt = NULL;
11152 	int retval;
11153 	unsigned long iflags;
11154 	struct lpfc_nodelist *ndlp;
11155 
11156 	lockdep_assert_held(&phba->hbalock);
11157 
11158 	/*
11159 	 * There are certain command types we don't want to abort.  And we
11160 	 * don't want to abort commands that are already in the process of
11161 	 * being aborted.
11162 	 */
11163 	icmd = &cmdiocb->iocb;
11164 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11165 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
11166 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
11167 		return 0;
11168 
11169 	/* issue ABTS for this IOCB based on iotag */
11170 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
11171 	if (abtsiocbp == NULL)
11172 		return 0;
11173 
11174 	/* This signals the response to set the correct status
11175 	 * before calling the completion handler
11176 	 */
11177 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
11178 
11179 	iabt = &abtsiocbp->iocb;
11180 	iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
11181 	iabt->un.acxri.abortContextTag = icmd->ulpContext;
11182 	if (phba->sli_rev == LPFC_SLI_REV4) {
11183 		iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
11184 		iabt->un.acxri.abortContextTag = cmdiocb->iotag;
11185 	} else {
11186 		iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
11187 		if (pring->ringno == LPFC_ELS_RING) {
11188 			ndlp = (struct lpfc_nodelist *)(cmdiocb->context1);
11189 			iabt->un.acxri.abortContextTag = ndlp->nlp_rpi;
11190 		}
11191 	}
11192 	iabt->ulpLe = 1;
11193 	iabt->ulpClass = icmd->ulpClass;
11194 
11195 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11196 	abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
11197 	if (cmdiocb->iocb_flag & LPFC_IO_FCP)
11198 		abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
11199 	if (cmdiocb->iocb_flag & LPFC_IO_FOF)
11200 		abtsiocbp->iocb_flag |= LPFC_IO_FOF;
11201 
11202 	if (phba->link_state >= LPFC_LINK_UP)
11203 		iabt->ulpCommand = CMD_ABORT_XRI_CN;
11204 	else
11205 		iabt->ulpCommand = CMD_CLOSE_XRI_CN;
11206 
11207 	abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
11208 	abtsiocbp->vport = vport;
11209 
11210 	lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
11211 			 "0339 Abort xri x%x, original iotag x%x, "
11212 			 "abort cmd iotag x%x\n",
11213 			 iabt->un.acxri.abortIoTag,
11214 			 iabt->un.acxri.abortContextTag,
11215 			 abtsiocbp->iotag);
11216 
11217 	if (phba->sli_rev == LPFC_SLI_REV4) {
11218 		pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
11219 		if (unlikely(pring == NULL))
11220 			return 0;
11221 		/* Note: both hbalock and ring_lock need to be set here */
11222 		spin_lock_irqsave(&pring->ring_lock, iflags);
11223 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11224 			abtsiocbp, 0);
11225 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
11226 	} else {
11227 		retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11228 			abtsiocbp, 0);
11229 	}
11230 
11231 	if (retval)
11232 		__lpfc_sli_release_iocbq(phba, abtsiocbp);
11233 
11234 	/*
11235 	 * Caller to this routine should check for IOCB_ERROR
11236 	 * and handle it properly.  This routine no longer removes
11237 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
11238 	 */
11239 	return retval;
11240 }
11241 
11242 /**
11243  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
11244  * @phba: Pointer to HBA context object.
11245  * @pring: Pointer to driver SLI ring object.
11246  * @cmdiocb: Pointer to driver command iocb object.
11247  *
11248  * This function issues an abort iocb for the provided command iocb. In case
11249  * of unloading, the abort iocb will not be issued to commands on the ELS
11250  * ring. Instead, the callback function shall be changed to those commands
11251  * so that nothing happens when them finishes. This function is called with
11252  * hbalock held. The function returns 0 when the command iocb is an abort
11253  * request.
11254  **/
11255 int
11256 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11257 			   struct lpfc_iocbq *cmdiocb)
11258 {
11259 	struct lpfc_vport *vport = cmdiocb->vport;
11260 	int retval = IOCB_ERROR;
11261 	IOCB_t *icmd = NULL;
11262 
11263 	lockdep_assert_held(&phba->hbalock);
11264 
11265 	/*
11266 	 * There are certain command types we don't want to abort.  And we
11267 	 * don't want to abort commands that are already in the process of
11268 	 * being aborted.
11269 	 */
11270 	icmd = &cmdiocb->iocb;
11271 	if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11272 	    icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
11273 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
11274 		return 0;
11275 
11276 	if (!pring) {
11277 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11278 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11279 		else
11280 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11281 		goto abort_iotag_exit;
11282 	}
11283 
11284 	/*
11285 	 * If we're unloading, don't abort iocb on the ELS ring, but change
11286 	 * the callback so that nothing happens when it finishes.
11287 	 */
11288 	if ((vport->load_flag & FC_UNLOADING) &&
11289 	    (pring->ringno == LPFC_ELS_RING)) {
11290 		if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11291 			cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11292 		else
11293 			cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11294 		goto abort_iotag_exit;
11295 	}
11296 
11297 	/* Now, we try to issue the abort to the cmdiocb out */
11298 	retval = lpfc_sli_abort_iotag_issue(phba, pring, cmdiocb);
11299 
11300 abort_iotag_exit:
11301 	/*
11302 	 * Caller to this routine should check for IOCB_ERROR
11303 	 * and handle it properly.  This routine no longer removes
11304 	 * iocb off txcmplq and call compl in case of IOCB_ERROR.
11305 	 */
11306 	return retval;
11307 }
11308 
11309 /**
11310  * lpfc_sli4_abort_nvme_io - Issue abort for a command iocb
11311  * @phba: Pointer to HBA context object.
11312  * @pring: Pointer to driver SLI ring object.
11313  * @cmdiocb: Pointer to driver command iocb object.
11314  *
11315  * This function issues an abort iocb for the provided command iocb down to
11316  * the port. Other than the case the outstanding command iocb is an abort
11317  * request, this function issues abort out unconditionally. This function is
11318  * called with hbalock held. The function returns 0 when it fails due to
11319  * memory allocation failure or when the command iocb is an abort request.
11320  **/
11321 static int
11322 lpfc_sli4_abort_nvme_io(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11323 			struct lpfc_iocbq *cmdiocb)
11324 {
11325 	struct lpfc_vport *vport = cmdiocb->vport;
11326 	struct lpfc_iocbq *abtsiocbp;
11327 	union lpfc_wqe128 *abts_wqe;
11328 	int retval;
11329 
11330 	/*
11331 	 * There are certain command types we don't want to abort.  And we
11332 	 * don't want to abort commands that are already in the process of
11333 	 * being aborted.
11334 	 */
11335 	if (cmdiocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
11336 	    cmdiocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN ||
11337 	    (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
11338 		return 0;
11339 
11340 	/* issue ABTS for this io based on iotag */
11341 	abtsiocbp = __lpfc_sli_get_iocbq(phba);
11342 	if (abtsiocbp == NULL)
11343 		return 0;
11344 
11345 	/* This signals the response to set the correct status
11346 	 * before calling the completion handler
11347 	 */
11348 	cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
11349 
11350 	/* Complete prepping the abort wqe and issue to the FW. */
11351 	abts_wqe = &abtsiocbp->wqe;
11352 
11353 	/* Clear any stale WQE contents */
11354 	memset(abts_wqe, 0, sizeof(union lpfc_wqe));
11355 	bf_set(abort_cmd_criteria, &abts_wqe->abort_cmd, T_XRI_TAG);
11356 
11357 	/* word 7 */
11358 	bf_set(wqe_cmnd, &abts_wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
11359 	bf_set(wqe_class, &abts_wqe->abort_cmd.wqe_com,
11360 	       cmdiocb->iocb.ulpClass);
11361 
11362 	/* word 8 - tell the FW to abort the IO associated with this
11363 	 * outstanding exchange ID.
11364 	 */
11365 	abts_wqe->abort_cmd.wqe_com.abort_tag = cmdiocb->sli4_xritag;
11366 
11367 	/* word 9 - this is the iotag for the abts_wqe completion. */
11368 	bf_set(wqe_reqtag, &abts_wqe->abort_cmd.wqe_com,
11369 	       abtsiocbp->iotag);
11370 
11371 	/* word 10 */
11372 	bf_set(wqe_qosd, &abts_wqe->abort_cmd.wqe_com, 1);
11373 	bf_set(wqe_lenloc, &abts_wqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
11374 
11375 	/* word 11 */
11376 	bf_set(wqe_cmd_type, &abts_wqe->abort_cmd.wqe_com, OTHER_COMMAND);
11377 	bf_set(wqe_wqec, &abts_wqe->abort_cmd.wqe_com, 1);
11378 	bf_set(wqe_cqid, &abts_wqe->abort_cmd.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
11379 
11380 	/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11381 	abtsiocbp->iocb_flag |= LPFC_IO_NVME;
11382 	abtsiocbp->vport = vport;
11383 	abtsiocbp->wqe_cmpl = lpfc_nvme_abort_fcreq_cmpl;
11384 	retval = lpfc_sli4_issue_wqe(phba, LPFC_FCP_RING, abtsiocbp);
11385 	if (retval) {
11386 		lpfc_printf_vlog(vport, KERN_ERR, LOG_NVME,
11387 				 "6147 Failed abts issue_wqe with status x%x "
11388 				 "for oxid x%x\n",
11389 				 retval, cmdiocb->sli4_xritag);
11390 		lpfc_sli_release_iocbq(phba, abtsiocbp);
11391 		return retval;
11392 	}
11393 
11394 	lpfc_printf_vlog(vport, KERN_ERR, LOG_NVME,
11395 			 "6148 Drv Abort NVME Request Issued for "
11396 			 "ox_id x%x on reqtag x%x\n",
11397 			 cmdiocb->sli4_xritag,
11398 			 abtsiocbp->iotag);
11399 
11400 	return retval;
11401 }
11402 
11403 /**
11404  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
11405  * @phba: pointer to lpfc HBA data structure.
11406  *
11407  * This routine will abort all pending and outstanding iocbs to an HBA.
11408  **/
11409 void
11410 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
11411 {
11412 	struct lpfc_sli *psli = &phba->sli;
11413 	struct lpfc_sli_ring *pring;
11414 	struct lpfc_queue *qp = NULL;
11415 	int i;
11416 
11417 	if (phba->sli_rev != LPFC_SLI_REV4) {
11418 		for (i = 0; i < psli->num_rings; i++) {
11419 			pring = &psli->sli3_ring[i];
11420 			lpfc_sli_abort_iocb_ring(phba, pring);
11421 		}
11422 		return;
11423 	}
11424 	list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11425 		pring = qp->pring;
11426 		if (!pring)
11427 			continue;
11428 		lpfc_sli_abort_iocb_ring(phba, pring);
11429 	}
11430 }
11431 
11432 /**
11433  * lpfc_sli_validate_fcp_iocb - find commands associated with a vport or LUN
11434  * @iocbq: Pointer to driver iocb object.
11435  * @vport: Pointer to driver virtual port object.
11436  * @tgt_id: SCSI ID of the target.
11437  * @lun_id: LUN ID of the scsi device.
11438  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
11439  *
11440  * This function acts as an iocb filter for functions which abort or count
11441  * all FCP iocbs pending on a lun/SCSI target/SCSI host. It will return
11442  * 0 if the filtering criteria is met for the given iocb and will return
11443  * 1 if the filtering criteria is not met.
11444  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
11445  * given iocb is for the SCSI device specified by vport, tgt_id and
11446  * lun_id parameter.
11447  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
11448  * given iocb is for the SCSI target specified by vport and tgt_id
11449  * parameters.
11450  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
11451  * given iocb is for the SCSI host associated with the given vport.
11452  * This function is called with no locks held.
11453  **/
11454 static int
11455 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
11456 			   uint16_t tgt_id, uint64_t lun_id,
11457 			   lpfc_ctx_cmd ctx_cmd)
11458 {
11459 	struct lpfc_scsi_buf *lpfc_cmd;
11460 	int rc = 1;
11461 
11462 	if (iocbq->vport != vport)
11463 		return rc;
11464 
11465 	if (!(iocbq->iocb_flag &  LPFC_IO_FCP) ||
11466 	    !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ))
11467 		return rc;
11468 
11469 	lpfc_cmd = container_of(iocbq, struct lpfc_scsi_buf, cur_iocbq);
11470 
11471 	if (lpfc_cmd->pCmd == NULL)
11472 		return rc;
11473 
11474 	switch (ctx_cmd) {
11475 	case LPFC_CTX_LUN:
11476 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11477 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
11478 		    (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
11479 			rc = 0;
11480 		break;
11481 	case LPFC_CTX_TGT:
11482 		if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11483 		    (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
11484 			rc = 0;
11485 		break;
11486 	case LPFC_CTX_HOST:
11487 		rc = 0;
11488 		break;
11489 	default:
11490 		printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
11491 			__func__, ctx_cmd);
11492 		break;
11493 	}
11494 
11495 	return rc;
11496 }
11497 
11498 /**
11499  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
11500  * @vport: Pointer to virtual port.
11501  * @tgt_id: SCSI ID of the target.
11502  * @lun_id: LUN ID of the scsi device.
11503  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11504  *
11505  * This function returns number of FCP commands pending for the vport.
11506  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
11507  * commands pending on the vport associated with SCSI device specified
11508  * by tgt_id and lun_id parameters.
11509  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
11510  * commands pending on the vport associated with SCSI target specified
11511  * by tgt_id parameter.
11512  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
11513  * commands pending on the vport.
11514  * This function returns the number of iocbs which satisfy the filter.
11515  * This function is called without any lock held.
11516  **/
11517 int
11518 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
11519 		  lpfc_ctx_cmd ctx_cmd)
11520 {
11521 	struct lpfc_hba *phba = vport->phba;
11522 	struct lpfc_iocbq *iocbq;
11523 	int sum, i;
11524 
11525 	spin_lock_irq(&phba->hbalock);
11526 	for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
11527 		iocbq = phba->sli.iocbq_lookup[i];
11528 
11529 		if (lpfc_sli_validate_fcp_iocb (iocbq, vport, tgt_id, lun_id,
11530 						ctx_cmd) == 0)
11531 			sum++;
11532 	}
11533 	spin_unlock_irq(&phba->hbalock);
11534 
11535 	return sum;
11536 }
11537 
11538 /**
11539  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
11540  * @phba: Pointer to HBA context object
11541  * @cmdiocb: Pointer to command iocb object.
11542  * @rspiocb: Pointer to response iocb object.
11543  *
11544  * This function is called when an aborted FCP iocb completes. This
11545  * function is called by the ring event handler with no lock held.
11546  * This function frees the iocb.
11547  **/
11548 void
11549 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11550 			struct lpfc_iocbq *rspiocb)
11551 {
11552 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11553 			"3096 ABORT_XRI_CN completing on rpi x%x "
11554 			"original iotag x%x, abort cmd iotag x%x "
11555 			"status 0x%x, reason 0x%x\n",
11556 			cmdiocb->iocb.un.acxri.abortContextTag,
11557 			cmdiocb->iocb.un.acxri.abortIoTag,
11558 			cmdiocb->iotag, rspiocb->iocb.ulpStatus,
11559 			rspiocb->iocb.un.ulpWord[4]);
11560 	lpfc_sli_release_iocbq(phba, cmdiocb);
11561 	return;
11562 }
11563 
11564 /**
11565  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
11566  * @vport: Pointer to virtual port.
11567  * @pring: Pointer to driver SLI ring object.
11568  * @tgt_id: SCSI ID of the target.
11569  * @lun_id: LUN ID of the scsi device.
11570  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11571  *
11572  * This function sends an abort command for every SCSI command
11573  * associated with the given virtual port pending on the ring
11574  * filtered by lpfc_sli_validate_fcp_iocb function.
11575  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
11576  * FCP iocbs associated with lun specified by tgt_id and lun_id
11577  * parameters
11578  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
11579  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
11580  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
11581  * FCP iocbs associated with virtual port.
11582  * This function returns number of iocbs it failed to abort.
11583  * This function is called with no locks held.
11584  **/
11585 int
11586 lpfc_sli_abort_iocb(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
11587 		    uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd abort_cmd)
11588 {
11589 	struct lpfc_hba *phba = vport->phba;
11590 	struct lpfc_iocbq *iocbq;
11591 	struct lpfc_iocbq *abtsiocb;
11592 	struct lpfc_sli_ring *pring_s4;
11593 	IOCB_t *cmd = NULL;
11594 	int errcnt = 0, ret_val = 0;
11595 	int i;
11596 
11597 	/* all I/Os are in process of being flushed */
11598 	if (phba->hba_flag & HBA_FCP_IOQ_FLUSH)
11599 		return errcnt;
11600 
11601 	for (i = 1; i <= phba->sli.last_iotag; i++) {
11602 		iocbq = phba->sli.iocbq_lookup[i];
11603 
11604 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
11605 					       abort_cmd) != 0)
11606 			continue;
11607 
11608 		/*
11609 		 * If the iocbq is already being aborted, don't take a second
11610 		 * action, but do count it.
11611 		 */
11612 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
11613 			continue;
11614 
11615 		/* issue ABTS for this IOCB based on iotag */
11616 		abtsiocb = lpfc_sli_get_iocbq(phba);
11617 		if (abtsiocb == NULL) {
11618 			errcnt++;
11619 			continue;
11620 		}
11621 
11622 		/* indicate the IO is being aborted by the driver. */
11623 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
11624 
11625 		cmd = &iocbq->iocb;
11626 		abtsiocb->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
11627 		abtsiocb->iocb.un.acxri.abortContextTag = cmd->ulpContext;
11628 		if (phba->sli_rev == LPFC_SLI_REV4)
11629 			abtsiocb->iocb.un.acxri.abortIoTag = iocbq->sli4_xritag;
11630 		else
11631 			abtsiocb->iocb.un.acxri.abortIoTag = cmd->ulpIoTag;
11632 		abtsiocb->iocb.ulpLe = 1;
11633 		abtsiocb->iocb.ulpClass = cmd->ulpClass;
11634 		abtsiocb->vport = vport;
11635 
11636 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11637 		abtsiocb->hba_wqidx = iocbq->hba_wqidx;
11638 		if (iocbq->iocb_flag & LPFC_IO_FCP)
11639 			abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
11640 		if (iocbq->iocb_flag & LPFC_IO_FOF)
11641 			abtsiocb->iocb_flag |= LPFC_IO_FOF;
11642 
11643 		if (lpfc_is_link_up(phba))
11644 			abtsiocb->iocb.ulpCommand = CMD_ABORT_XRI_CN;
11645 		else
11646 			abtsiocb->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
11647 
11648 		/* Setup callback routine and issue the command. */
11649 		abtsiocb->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
11650 		if (phba->sli_rev == LPFC_SLI_REV4) {
11651 			pring_s4 = lpfc_sli4_calc_ring(phba, iocbq);
11652 			if (!pring_s4)
11653 				continue;
11654 			ret_val = lpfc_sli_issue_iocb(phba, pring_s4->ringno,
11655 						      abtsiocb, 0);
11656 		} else
11657 			ret_val = lpfc_sli_issue_iocb(phba, pring->ringno,
11658 						      abtsiocb, 0);
11659 		if (ret_val == IOCB_ERROR) {
11660 			lpfc_sli_release_iocbq(phba, abtsiocb);
11661 			errcnt++;
11662 			continue;
11663 		}
11664 	}
11665 
11666 	return errcnt;
11667 }
11668 
11669 /**
11670  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
11671  * @vport: Pointer to virtual port.
11672  * @pring: Pointer to driver SLI ring object.
11673  * @tgt_id: SCSI ID of the target.
11674  * @lun_id: LUN ID of the scsi device.
11675  * @taskmgmt_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11676  *
11677  * This function sends an abort command for every SCSI command
11678  * associated with the given virtual port pending on the ring
11679  * filtered by lpfc_sli_validate_fcp_iocb function.
11680  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
11681  * FCP iocbs associated with lun specified by tgt_id and lun_id
11682  * parameters
11683  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
11684  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
11685  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
11686  * FCP iocbs associated with virtual port.
11687  * This function returns number of iocbs it aborted .
11688  * This function is called with no locks held right after a taskmgmt
11689  * command is sent.
11690  **/
11691 int
11692 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
11693 			uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
11694 {
11695 	struct lpfc_hba *phba = vport->phba;
11696 	struct lpfc_scsi_buf *lpfc_cmd;
11697 	struct lpfc_iocbq *abtsiocbq;
11698 	struct lpfc_nodelist *ndlp;
11699 	struct lpfc_iocbq *iocbq;
11700 	IOCB_t *icmd;
11701 	int sum, i, ret_val;
11702 	unsigned long iflags;
11703 	struct lpfc_sli_ring *pring_s4;
11704 
11705 	spin_lock_irqsave(&phba->hbalock, iflags);
11706 
11707 	/* all I/Os are in process of being flushed */
11708 	if (phba->hba_flag & HBA_FCP_IOQ_FLUSH) {
11709 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11710 		return 0;
11711 	}
11712 	sum = 0;
11713 
11714 	for (i = 1; i <= phba->sli.last_iotag; i++) {
11715 		iocbq = phba->sli.iocbq_lookup[i];
11716 
11717 		if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
11718 					       cmd) != 0)
11719 			continue;
11720 
11721 		/*
11722 		 * If the iocbq is already being aborted, don't take a second
11723 		 * action, but do count it.
11724 		 */
11725 		if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
11726 			continue;
11727 
11728 		/* issue ABTS for this IOCB based on iotag */
11729 		abtsiocbq = __lpfc_sli_get_iocbq(phba);
11730 		if (abtsiocbq == NULL)
11731 			continue;
11732 
11733 		icmd = &iocbq->iocb;
11734 		abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
11735 		abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
11736 		if (phba->sli_rev == LPFC_SLI_REV4)
11737 			abtsiocbq->iocb.un.acxri.abortIoTag =
11738 							 iocbq->sli4_xritag;
11739 		else
11740 			abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
11741 		abtsiocbq->iocb.ulpLe = 1;
11742 		abtsiocbq->iocb.ulpClass = icmd->ulpClass;
11743 		abtsiocbq->vport = vport;
11744 
11745 		/* ABTS WQE must go to the same WQ as the WQE to be aborted */
11746 		abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
11747 		if (iocbq->iocb_flag & LPFC_IO_FCP)
11748 			abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
11749 		if (iocbq->iocb_flag & LPFC_IO_FOF)
11750 			abtsiocbq->iocb_flag |= LPFC_IO_FOF;
11751 
11752 		lpfc_cmd = container_of(iocbq, struct lpfc_scsi_buf, cur_iocbq);
11753 		ndlp = lpfc_cmd->rdata->pnode;
11754 
11755 		if (lpfc_is_link_up(phba) &&
11756 		    (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
11757 			abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
11758 		else
11759 			abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
11760 
11761 		/* Setup callback routine and issue the command. */
11762 		abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
11763 
11764 		/*
11765 		 * Indicate the IO is being aborted by the driver and set
11766 		 * the caller's flag into the aborted IO.
11767 		 */
11768 		iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
11769 
11770 		if (phba->sli_rev == LPFC_SLI_REV4) {
11771 			pring_s4 = lpfc_sli4_calc_ring(phba, abtsiocbq);
11772 			if (!pring_s4)
11773 				continue;
11774 			/* Note: both hbalock and ring_lock must be set here */
11775 			spin_lock(&pring_s4->ring_lock);
11776 			ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
11777 							abtsiocbq, 0);
11778 			spin_unlock(&pring_s4->ring_lock);
11779 		} else {
11780 			ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
11781 							abtsiocbq, 0);
11782 		}
11783 
11784 
11785 		if (ret_val == IOCB_ERROR)
11786 			__lpfc_sli_release_iocbq(phba, abtsiocbq);
11787 		else
11788 			sum++;
11789 	}
11790 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11791 	return sum;
11792 }
11793 
11794 /**
11795  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
11796  * @phba: Pointer to HBA context object.
11797  * @cmdiocbq: Pointer to command iocb.
11798  * @rspiocbq: Pointer to response iocb.
11799  *
11800  * This function is the completion handler for iocbs issued using
11801  * lpfc_sli_issue_iocb_wait function. This function is called by the
11802  * ring event handler function without any lock held. This function
11803  * can be called from both worker thread context and interrupt
11804  * context. This function also can be called from other thread which
11805  * cleans up the SLI layer objects.
11806  * This function copy the contents of the response iocb to the
11807  * response iocb memory object provided by the caller of
11808  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
11809  * sleeps for the iocb completion.
11810  **/
11811 static void
11812 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
11813 			struct lpfc_iocbq *cmdiocbq,
11814 			struct lpfc_iocbq *rspiocbq)
11815 {
11816 	wait_queue_head_t *pdone_q;
11817 	unsigned long iflags;
11818 	struct lpfc_scsi_buf *lpfc_cmd;
11819 
11820 	spin_lock_irqsave(&phba->hbalock, iflags);
11821 	if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
11822 
11823 		/*
11824 		 * A time out has occurred for the iocb.  If a time out
11825 		 * completion handler has been supplied, call it.  Otherwise,
11826 		 * just free the iocbq.
11827 		 */
11828 
11829 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11830 		cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
11831 		cmdiocbq->wait_iocb_cmpl = NULL;
11832 		if (cmdiocbq->iocb_cmpl)
11833 			(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
11834 		else
11835 			lpfc_sli_release_iocbq(phba, cmdiocbq);
11836 		return;
11837 	}
11838 
11839 	cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
11840 	if (cmdiocbq->context2 && rspiocbq)
11841 		memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
11842 		       &rspiocbq->iocb, sizeof(IOCB_t));
11843 
11844 	/* Set the exchange busy flag for task management commands */
11845 	if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
11846 		!(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
11847 		lpfc_cmd = container_of(cmdiocbq, struct lpfc_scsi_buf,
11848 			cur_iocbq);
11849 		lpfc_cmd->exch_busy = rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY;
11850 	}
11851 
11852 	pdone_q = cmdiocbq->context_un.wait_queue;
11853 	if (pdone_q)
11854 		wake_up(pdone_q);
11855 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11856 	return;
11857 }
11858 
11859 /**
11860  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
11861  * @phba: Pointer to HBA context object..
11862  * @piocbq: Pointer to command iocb.
11863  * @flag: Flag to test.
11864  *
11865  * This routine grabs the hbalock and then test the iocb_flag to
11866  * see if the passed in flag is set.
11867  * Returns:
11868  * 1 if flag is set.
11869  * 0 if flag is not set.
11870  **/
11871 static int
11872 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
11873 		 struct lpfc_iocbq *piocbq, uint32_t flag)
11874 {
11875 	unsigned long iflags;
11876 	int ret;
11877 
11878 	spin_lock_irqsave(&phba->hbalock, iflags);
11879 	ret = piocbq->iocb_flag & flag;
11880 	spin_unlock_irqrestore(&phba->hbalock, iflags);
11881 	return ret;
11882 
11883 }
11884 
11885 /**
11886  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
11887  * @phba: Pointer to HBA context object..
11888  * @pring: Pointer to sli ring.
11889  * @piocb: Pointer to command iocb.
11890  * @prspiocbq: Pointer to response iocb.
11891  * @timeout: Timeout in number of seconds.
11892  *
11893  * This function issues the iocb to firmware and waits for the
11894  * iocb to complete. The iocb_cmpl field of the shall be used
11895  * to handle iocbs which time out. If the field is NULL, the
11896  * function shall free the iocbq structure.  If more clean up is
11897  * needed, the caller is expected to provide a completion function
11898  * that will provide the needed clean up.  If the iocb command is
11899  * not completed within timeout seconds, the function will either
11900  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
11901  * completion function set in the iocb_cmpl field and then return
11902  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
11903  * resources if this function returns IOCB_TIMEDOUT.
11904  * The function waits for the iocb completion using an
11905  * non-interruptible wait.
11906  * This function will sleep while waiting for iocb completion.
11907  * So, this function should not be called from any context which
11908  * does not allow sleeping. Due to the same reason, this function
11909  * cannot be called with interrupt disabled.
11910  * This function assumes that the iocb completions occur while
11911  * this function sleep. So, this function cannot be called from
11912  * the thread which process iocb completion for this ring.
11913  * This function clears the iocb_flag of the iocb object before
11914  * issuing the iocb and the iocb completion handler sets this
11915  * flag and wakes this thread when the iocb completes.
11916  * The contents of the response iocb will be copied to prspiocbq
11917  * by the completion handler when the command completes.
11918  * This function returns IOCB_SUCCESS when success.
11919  * This function is called with no lock held.
11920  **/
11921 int
11922 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
11923 			 uint32_t ring_number,
11924 			 struct lpfc_iocbq *piocb,
11925 			 struct lpfc_iocbq *prspiocbq,
11926 			 uint32_t timeout)
11927 {
11928 	DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
11929 	long timeleft, timeout_req = 0;
11930 	int retval = IOCB_SUCCESS;
11931 	uint32_t creg_val;
11932 	struct lpfc_iocbq *iocb;
11933 	int txq_cnt = 0;
11934 	int txcmplq_cnt = 0;
11935 	struct lpfc_sli_ring *pring;
11936 	unsigned long iflags;
11937 	bool iocb_completed = true;
11938 
11939 	if (phba->sli_rev >= LPFC_SLI_REV4)
11940 		pring = lpfc_sli4_calc_ring(phba, piocb);
11941 	else
11942 		pring = &phba->sli.sli3_ring[ring_number];
11943 	/*
11944 	 * If the caller has provided a response iocbq buffer, then context2
11945 	 * is NULL or its an error.
11946 	 */
11947 	if (prspiocbq) {
11948 		if (piocb->context2)
11949 			return IOCB_ERROR;
11950 		piocb->context2 = prspiocbq;
11951 	}
11952 
11953 	piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
11954 	piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
11955 	piocb->context_un.wait_queue = &done_q;
11956 	piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
11957 
11958 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
11959 		if (lpfc_readl(phba->HCregaddr, &creg_val))
11960 			return IOCB_ERROR;
11961 		creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
11962 		writel(creg_val, phba->HCregaddr);
11963 		readl(phba->HCregaddr); /* flush */
11964 	}
11965 
11966 	retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
11967 				     SLI_IOCB_RET_IOCB);
11968 	if (retval == IOCB_SUCCESS) {
11969 		timeout_req = msecs_to_jiffies(timeout * 1000);
11970 		timeleft = wait_event_timeout(done_q,
11971 				lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
11972 				timeout_req);
11973 		spin_lock_irqsave(&phba->hbalock, iflags);
11974 		if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
11975 
11976 			/*
11977 			 * IOCB timed out.  Inform the wake iocb wait
11978 			 * completion function and set local status
11979 			 */
11980 
11981 			iocb_completed = false;
11982 			piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
11983 		}
11984 		spin_unlock_irqrestore(&phba->hbalock, iflags);
11985 		if (iocb_completed) {
11986 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11987 					"0331 IOCB wake signaled\n");
11988 			/* Note: we are not indicating if the IOCB has a success
11989 			 * status or not - that's for the caller to check.
11990 			 * IOCB_SUCCESS means just that the command was sent and
11991 			 * completed. Not that it completed successfully.
11992 			 * */
11993 		} else if (timeleft == 0) {
11994 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11995 					"0338 IOCB wait timeout error - no "
11996 					"wake response Data x%x\n", timeout);
11997 			retval = IOCB_TIMEDOUT;
11998 		} else {
11999 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
12000 					"0330 IOCB wake NOT set, "
12001 					"Data x%x x%lx\n",
12002 					timeout, (timeleft / jiffies));
12003 			retval = IOCB_TIMEDOUT;
12004 		}
12005 	} else if (retval == IOCB_BUSY) {
12006 		if (phba->cfg_log_verbose & LOG_SLI) {
12007 			list_for_each_entry(iocb, &pring->txq, list) {
12008 				txq_cnt++;
12009 			}
12010 			list_for_each_entry(iocb, &pring->txcmplq, list) {
12011 				txcmplq_cnt++;
12012 			}
12013 			lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12014 				"2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
12015 				phba->iocb_cnt, txq_cnt, txcmplq_cnt);
12016 		}
12017 		return retval;
12018 	} else {
12019 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12020 				"0332 IOCB wait issue failed, Data x%x\n",
12021 				retval);
12022 		retval = IOCB_ERROR;
12023 	}
12024 
12025 	if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
12026 		if (lpfc_readl(phba->HCregaddr, &creg_val))
12027 			return IOCB_ERROR;
12028 		creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
12029 		writel(creg_val, phba->HCregaddr);
12030 		readl(phba->HCregaddr); /* flush */
12031 	}
12032 
12033 	if (prspiocbq)
12034 		piocb->context2 = NULL;
12035 
12036 	piocb->context_un.wait_queue = NULL;
12037 	piocb->iocb_cmpl = NULL;
12038 	return retval;
12039 }
12040 
12041 /**
12042  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
12043  * @phba: Pointer to HBA context object.
12044  * @pmboxq: Pointer to driver mailbox object.
12045  * @timeout: Timeout in number of seconds.
12046  *
12047  * This function issues the mailbox to firmware and waits for the
12048  * mailbox command to complete. If the mailbox command is not
12049  * completed within timeout seconds, it returns MBX_TIMEOUT.
12050  * The function waits for the mailbox completion using an
12051  * interruptible wait. If the thread is woken up due to a
12052  * signal, MBX_TIMEOUT error is returned to the caller. Caller
12053  * should not free the mailbox resources, if this function returns
12054  * MBX_TIMEOUT.
12055  * This function will sleep while waiting for mailbox completion.
12056  * So, this function should not be called from any context which
12057  * does not allow sleeping. Due to the same reason, this function
12058  * cannot be called with interrupt disabled.
12059  * This function assumes that the mailbox completion occurs while
12060  * this function sleep. So, this function cannot be called from
12061  * the worker thread which processes mailbox completion.
12062  * This function is called in the context of HBA management
12063  * applications.
12064  * This function returns MBX_SUCCESS when successful.
12065  * This function is called with no lock held.
12066  **/
12067 int
12068 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
12069 			 uint32_t timeout)
12070 {
12071 	struct completion mbox_done;
12072 	int retval;
12073 	unsigned long flag;
12074 
12075 	pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
12076 	/* setup wake call as IOCB callback */
12077 	pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
12078 
12079 	/* setup context3 field to pass wait_queue pointer to wake function  */
12080 	init_completion(&mbox_done);
12081 	pmboxq->context3 = &mbox_done;
12082 	/* now issue the command */
12083 	retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
12084 	if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
12085 		wait_for_completion_timeout(&mbox_done,
12086 					    msecs_to_jiffies(timeout * 1000));
12087 
12088 		spin_lock_irqsave(&phba->hbalock, flag);
12089 		pmboxq->context3 = NULL;
12090 		/*
12091 		 * if LPFC_MBX_WAKE flag is set the mailbox is completed
12092 		 * else do not free the resources.
12093 		 */
12094 		if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
12095 			retval = MBX_SUCCESS;
12096 		} else {
12097 			retval = MBX_TIMEOUT;
12098 			pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
12099 		}
12100 		spin_unlock_irqrestore(&phba->hbalock, flag);
12101 	}
12102 	return retval;
12103 }
12104 
12105 /**
12106  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
12107  * @phba: Pointer to HBA context.
12108  *
12109  * This function is called to shutdown the driver's mailbox sub-system.
12110  * It first marks the mailbox sub-system is in a block state to prevent
12111  * the asynchronous mailbox command from issued off the pending mailbox
12112  * command queue. If the mailbox command sub-system shutdown is due to
12113  * HBA error conditions such as EEH or ERATT, this routine shall invoke
12114  * the mailbox sub-system flush routine to forcefully bring down the
12115  * mailbox sub-system. Otherwise, if it is due to normal condition (such
12116  * as with offline or HBA function reset), this routine will wait for the
12117  * outstanding mailbox command to complete before invoking the mailbox
12118  * sub-system flush routine to gracefully bring down mailbox sub-system.
12119  **/
12120 void
12121 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
12122 {
12123 	struct lpfc_sli *psli = &phba->sli;
12124 	unsigned long timeout;
12125 
12126 	if (mbx_action == LPFC_MBX_NO_WAIT) {
12127 		/* delay 100ms for port state */
12128 		msleep(100);
12129 		lpfc_sli_mbox_sys_flush(phba);
12130 		return;
12131 	}
12132 	timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
12133 
12134 	/* Disable softirqs, including timers from obtaining phba->hbalock */
12135 	local_bh_disable();
12136 
12137 	spin_lock_irq(&phba->hbalock);
12138 	psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
12139 
12140 	if (psli->sli_flag & LPFC_SLI_ACTIVE) {
12141 		/* Determine how long we might wait for the active mailbox
12142 		 * command to be gracefully completed by firmware.
12143 		 */
12144 		if (phba->sli.mbox_active)
12145 			timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
12146 						phba->sli.mbox_active) *
12147 						1000) + jiffies;
12148 		spin_unlock_irq(&phba->hbalock);
12149 
12150 		/* Enable softirqs again, done with phba->hbalock */
12151 		local_bh_enable();
12152 
12153 		while (phba->sli.mbox_active) {
12154 			/* Check active mailbox complete status every 2ms */
12155 			msleep(2);
12156 			if (time_after(jiffies, timeout))
12157 				/* Timeout, let the mailbox flush routine to
12158 				 * forcefully release active mailbox command
12159 				 */
12160 				break;
12161 		}
12162 	} else {
12163 		spin_unlock_irq(&phba->hbalock);
12164 
12165 		/* Enable softirqs again, done with phba->hbalock */
12166 		local_bh_enable();
12167 	}
12168 
12169 	lpfc_sli_mbox_sys_flush(phba);
12170 }
12171 
12172 /**
12173  * lpfc_sli_eratt_read - read sli-3 error attention events
12174  * @phba: Pointer to HBA context.
12175  *
12176  * This function is called to read the SLI3 device error attention registers
12177  * for possible error attention events. The caller must hold the hostlock
12178  * with spin_lock_irq().
12179  *
12180  * This function returns 1 when there is Error Attention in the Host Attention
12181  * Register and returns 0 otherwise.
12182  **/
12183 static int
12184 lpfc_sli_eratt_read(struct lpfc_hba *phba)
12185 {
12186 	uint32_t ha_copy;
12187 
12188 	/* Read chip Host Attention (HA) register */
12189 	if (lpfc_readl(phba->HAregaddr, &ha_copy))
12190 		goto unplug_err;
12191 
12192 	if (ha_copy & HA_ERATT) {
12193 		/* Read host status register to retrieve error event */
12194 		if (lpfc_sli_read_hs(phba))
12195 			goto unplug_err;
12196 
12197 		/* Check if there is a deferred error condition is active */
12198 		if ((HS_FFER1 & phba->work_hs) &&
12199 		    ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12200 		      HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
12201 			phba->hba_flag |= DEFER_ERATT;
12202 			/* Clear all interrupt enable conditions */
12203 			writel(0, phba->HCregaddr);
12204 			readl(phba->HCregaddr);
12205 		}
12206 
12207 		/* Set the driver HA work bitmap */
12208 		phba->work_ha |= HA_ERATT;
12209 		/* Indicate polling handles this ERATT */
12210 		phba->hba_flag |= HBA_ERATT_HANDLED;
12211 		return 1;
12212 	}
12213 	return 0;
12214 
12215 unplug_err:
12216 	/* Set the driver HS work bitmap */
12217 	phba->work_hs |= UNPLUG_ERR;
12218 	/* Set the driver HA work bitmap */
12219 	phba->work_ha |= HA_ERATT;
12220 	/* Indicate polling handles this ERATT */
12221 	phba->hba_flag |= HBA_ERATT_HANDLED;
12222 	return 1;
12223 }
12224 
12225 /**
12226  * lpfc_sli4_eratt_read - read sli-4 error attention events
12227  * @phba: Pointer to HBA context.
12228  *
12229  * This function is called to read the SLI4 device error attention registers
12230  * for possible error attention events. The caller must hold the hostlock
12231  * with spin_lock_irq().
12232  *
12233  * This function returns 1 when there is Error Attention in the Host Attention
12234  * Register and returns 0 otherwise.
12235  **/
12236 static int
12237 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
12238 {
12239 	uint32_t uerr_sta_hi, uerr_sta_lo;
12240 	uint32_t if_type, portsmphr;
12241 	struct lpfc_register portstat_reg;
12242 
12243 	/*
12244 	 * For now, use the SLI4 device internal unrecoverable error
12245 	 * registers for error attention. This can be changed later.
12246 	 */
12247 	if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12248 	switch (if_type) {
12249 	case LPFC_SLI_INTF_IF_TYPE_0:
12250 		if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
12251 			&uerr_sta_lo) ||
12252 			lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
12253 			&uerr_sta_hi)) {
12254 			phba->work_hs |= UNPLUG_ERR;
12255 			phba->work_ha |= HA_ERATT;
12256 			phba->hba_flag |= HBA_ERATT_HANDLED;
12257 			return 1;
12258 		}
12259 		if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
12260 		    (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
12261 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12262 					"1423 HBA Unrecoverable error: "
12263 					"uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
12264 					"ue_mask_lo_reg=0x%x, "
12265 					"ue_mask_hi_reg=0x%x\n",
12266 					uerr_sta_lo, uerr_sta_hi,
12267 					phba->sli4_hba.ue_mask_lo,
12268 					phba->sli4_hba.ue_mask_hi);
12269 			phba->work_status[0] = uerr_sta_lo;
12270 			phba->work_status[1] = uerr_sta_hi;
12271 			phba->work_ha |= HA_ERATT;
12272 			phba->hba_flag |= HBA_ERATT_HANDLED;
12273 			return 1;
12274 		}
12275 		break;
12276 	case LPFC_SLI_INTF_IF_TYPE_2:
12277 	case LPFC_SLI_INTF_IF_TYPE_6:
12278 		if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
12279 			&portstat_reg.word0) ||
12280 			lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
12281 			&portsmphr)){
12282 			phba->work_hs |= UNPLUG_ERR;
12283 			phba->work_ha |= HA_ERATT;
12284 			phba->hba_flag |= HBA_ERATT_HANDLED;
12285 			return 1;
12286 		}
12287 		if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
12288 			phba->work_status[0] =
12289 				readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
12290 			phba->work_status[1] =
12291 				readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
12292 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12293 					"2885 Port Status Event: "
12294 					"port status reg 0x%x, "
12295 					"port smphr reg 0x%x, "
12296 					"error 1=0x%x, error 2=0x%x\n",
12297 					portstat_reg.word0,
12298 					portsmphr,
12299 					phba->work_status[0],
12300 					phba->work_status[1]);
12301 			phba->work_ha |= HA_ERATT;
12302 			phba->hba_flag |= HBA_ERATT_HANDLED;
12303 			return 1;
12304 		}
12305 		break;
12306 	case LPFC_SLI_INTF_IF_TYPE_1:
12307 	default:
12308 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12309 				"2886 HBA Error Attention on unsupported "
12310 				"if type %d.", if_type);
12311 		return 1;
12312 	}
12313 
12314 	return 0;
12315 }
12316 
12317 /**
12318  * lpfc_sli_check_eratt - check error attention events
12319  * @phba: Pointer to HBA context.
12320  *
12321  * This function is called from timer soft interrupt context to check HBA's
12322  * error attention register bit for error attention events.
12323  *
12324  * This function returns 1 when there is Error Attention in the Host Attention
12325  * Register and returns 0 otherwise.
12326  **/
12327 int
12328 lpfc_sli_check_eratt(struct lpfc_hba *phba)
12329 {
12330 	uint32_t ha_copy;
12331 
12332 	/* If somebody is waiting to handle an eratt, don't process it
12333 	 * here. The brdkill function will do this.
12334 	 */
12335 	if (phba->link_flag & LS_IGNORE_ERATT)
12336 		return 0;
12337 
12338 	/* Check if interrupt handler handles this ERATT */
12339 	spin_lock_irq(&phba->hbalock);
12340 	if (phba->hba_flag & HBA_ERATT_HANDLED) {
12341 		/* Interrupt handler has handled ERATT */
12342 		spin_unlock_irq(&phba->hbalock);
12343 		return 0;
12344 	}
12345 
12346 	/*
12347 	 * If there is deferred error attention, do not check for error
12348 	 * attention
12349 	 */
12350 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12351 		spin_unlock_irq(&phba->hbalock);
12352 		return 0;
12353 	}
12354 
12355 	/* If PCI channel is offline, don't process it */
12356 	if (unlikely(pci_channel_offline(phba->pcidev))) {
12357 		spin_unlock_irq(&phba->hbalock);
12358 		return 0;
12359 	}
12360 
12361 	switch (phba->sli_rev) {
12362 	case LPFC_SLI_REV2:
12363 	case LPFC_SLI_REV3:
12364 		/* Read chip Host Attention (HA) register */
12365 		ha_copy = lpfc_sli_eratt_read(phba);
12366 		break;
12367 	case LPFC_SLI_REV4:
12368 		/* Read device Uncoverable Error (UERR) registers */
12369 		ha_copy = lpfc_sli4_eratt_read(phba);
12370 		break;
12371 	default:
12372 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12373 				"0299 Invalid SLI revision (%d)\n",
12374 				phba->sli_rev);
12375 		ha_copy = 0;
12376 		break;
12377 	}
12378 	spin_unlock_irq(&phba->hbalock);
12379 
12380 	return ha_copy;
12381 }
12382 
12383 /**
12384  * lpfc_intr_state_check - Check device state for interrupt handling
12385  * @phba: Pointer to HBA context.
12386  *
12387  * This inline routine checks whether a device or its PCI slot is in a state
12388  * that the interrupt should be handled.
12389  *
12390  * This function returns 0 if the device or the PCI slot is in a state that
12391  * interrupt should be handled, otherwise -EIO.
12392  */
12393 static inline int
12394 lpfc_intr_state_check(struct lpfc_hba *phba)
12395 {
12396 	/* If the pci channel is offline, ignore all the interrupts */
12397 	if (unlikely(pci_channel_offline(phba->pcidev)))
12398 		return -EIO;
12399 
12400 	/* Update device level interrupt statistics */
12401 	phba->sli.slistat.sli_intr++;
12402 
12403 	/* Ignore all interrupts during initialization. */
12404 	if (unlikely(phba->link_state < LPFC_LINK_DOWN))
12405 		return -EIO;
12406 
12407 	return 0;
12408 }
12409 
12410 /**
12411  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
12412  * @irq: Interrupt number.
12413  * @dev_id: The device context pointer.
12414  *
12415  * This function is directly called from the PCI layer as an interrupt
12416  * service routine when device with SLI-3 interface spec is enabled with
12417  * MSI-X multi-message interrupt mode and there are slow-path events in
12418  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
12419  * interrupt mode, this function is called as part of the device-level
12420  * interrupt handler. When the PCI slot is in error recovery or the HBA
12421  * is undergoing initialization, the interrupt handler will not process
12422  * the interrupt. The link attention and ELS ring attention events are
12423  * handled by the worker thread. The interrupt handler signals the worker
12424  * thread and returns for these events. This function is called without
12425  * any lock held. It gets the hbalock to access and update SLI data
12426  * structures.
12427  *
12428  * This function returns IRQ_HANDLED when interrupt is handled else it
12429  * returns IRQ_NONE.
12430  **/
12431 irqreturn_t
12432 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
12433 {
12434 	struct lpfc_hba  *phba;
12435 	uint32_t ha_copy, hc_copy;
12436 	uint32_t work_ha_copy;
12437 	unsigned long status;
12438 	unsigned long iflag;
12439 	uint32_t control;
12440 
12441 	MAILBOX_t *mbox, *pmbox;
12442 	struct lpfc_vport *vport;
12443 	struct lpfc_nodelist *ndlp;
12444 	struct lpfc_dmabuf *mp;
12445 	LPFC_MBOXQ_t *pmb;
12446 	int rc;
12447 
12448 	/*
12449 	 * Get the driver's phba structure from the dev_id and
12450 	 * assume the HBA is not interrupting.
12451 	 */
12452 	phba = (struct lpfc_hba *)dev_id;
12453 
12454 	if (unlikely(!phba))
12455 		return IRQ_NONE;
12456 
12457 	/*
12458 	 * Stuff needs to be attented to when this function is invoked as an
12459 	 * individual interrupt handler in MSI-X multi-message interrupt mode
12460 	 */
12461 	if (phba->intr_type == MSIX) {
12462 		/* Check device state for handling interrupt */
12463 		if (lpfc_intr_state_check(phba))
12464 			return IRQ_NONE;
12465 		/* Need to read HA REG for slow-path events */
12466 		spin_lock_irqsave(&phba->hbalock, iflag);
12467 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
12468 			goto unplug_error;
12469 		/* If somebody is waiting to handle an eratt don't process it
12470 		 * here. The brdkill function will do this.
12471 		 */
12472 		if (phba->link_flag & LS_IGNORE_ERATT)
12473 			ha_copy &= ~HA_ERATT;
12474 		/* Check the need for handling ERATT in interrupt handler */
12475 		if (ha_copy & HA_ERATT) {
12476 			if (phba->hba_flag & HBA_ERATT_HANDLED)
12477 				/* ERATT polling has handled ERATT */
12478 				ha_copy &= ~HA_ERATT;
12479 			else
12480 				/* Indicate interrupt handler handles ERATT */
12481 				phba->hba_flag |= HBA_ERATT_HANDLED;
12482 		}
12483 
12484 		/*
12485 		 * If there is deferred error attention, do not check for any
12486 		 * interrupt.
12487 		 */
12488 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12489 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12490 			return IRQ_NONE;
12491 		}
12492 
12493 		/* Clear up only attention source related to slow-path */
12494 		if (lpfc_readl(phba->HCregaddr, &hc_copy))
12495 			goto unplug_error;
12496 
12497 		writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
12498 			HC_LAINT_ENA | HC_ERINT_ENA),
12499 			phba->HCregaddr);
12500 		writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
12501 			phba->HAregaddr);
12502 		writel(hc_copy, phba->HCregaddr);
12503 		readl(phba->HAregaddr); /* flush */
12504 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12505 	} else
12506 		ha_copy = phba->ha_copy;
12507 
12508 	work_ha_copy = ha_copy & phba->work_ha_mask;
12509 
12510 	if (work_ha_copy) {
12511 		if (work_ha_copy & HA_LATT) {
12512 			if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
12513 				/*
12514 				 * Turn off Link Attention interrupts
12515 				 * until CLEAR_LA done
12516 				 */
12517 				spin_lock_irqsave(&phba->hbalock, iflag);
12518 				phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
12519 				if (lpfc_readl(phba->HCregaddr, &control))
12520 					goto unplug_error;
12521 				control &= ~HC_LAINT_ENA;
12522 				writel(control, phba->HCregaddr);
12523 				readl(phba->HCregaddr); /* flush */
12524 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12525 			}
12526 			else
12527 				work_ha_copy &= ~HA_LATT;
12528 		}
12529 
12530 		if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
12531 			/*
12532 			 * Turn off Slow Rings interrupts, LPFC_ELS_RING is
12533 			 * the only slow ring.
12534 			 */
12535 			status = (work_ha_copy &
12536 				(HA_RXMASK  << (4*LPFC_ELS_RING)));
12537 			status >>= (4*LPFC_ELS_RING);
12538 			if (status & HA_RXMASK) {
12539 				spin_lock_irqsave(&phba->hbalock, iflag);
12540 				if (lpfc_readl(phba->HCregaddr, &control))
12541 					goto unplug_error;
12542 
12543 				lpfc_debugfs_slow_ring_trc(phba,
12544 				"ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
12545 				control, status,
12546 				(uint32_t)phba->sli.slistat.sli_intr);
12547 
12548 				if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
12549 					lpfc_debugfs_slow_ring_trc(phba,
12550 						"ISR Disable ring:"
12551 						"pwork:x%x hawork:x%x wait:x%x",
12552 						phba->work_ha, work_ha_copy,
12553 						(uint32_t)((unsigned long)
12554 						&phba->work_waitq));
12555 
12556 					control &=
12557 					    ~(HC_R0INT_ENA << LPFC_ELS_RING);
12558 					writel(control, phba->HCregaddr);
12559 					readl(phba->HCregaddr); /* flush */
12560 				}
12561 				else {
12562 					lpfc_debugfs_slow_ring_trc(phba,
12563 						"ISR slow ring:   pwork:"
12564 						"x%x hawork:x%x wait:x%x",
12565 						phba->work_ha, work_ha_copy,
12566 						(uint32_t)((unsigned long)
12567 						&phba->work_waitq));
12568 				}
12569 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12570 			}
12571 		}
12572 		spin_lock_irqsave(&phba->hbalock, iflag);
12573 		if (work_ha_copy & HA_ERATT) {
12574 			if (lpfc_sli_read_hs(phba))
12575 				goto unplug_error;
12576 			/*
12577 			 * Check if there is a deferred error condition
12578 			 * is active
12579 			 */
12580 			if ((HS_FFER1 & phba->work_hs) &&
12581 				((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12582 				  HS_FFER6 | HS_FFER7 | HS_FFER8) &
12583 				  phba->work_hs)) {
12584 				phba->hba_flag |= DEFER_ERATT;
12585 				/* Clear all interrupt enable conditions */
12586 				writel(0, phba->HCregaddr);
12587 				readl(phba->HCregaddr);
12588 			}
12589 		}
12590 
12591 		if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
12592 			pmb = phba->sli.mbox_active;
12593 			pmbox = &pmb->u.mb;
12594 			mbox = phba->mbox;
12595 			vport = pmb->vport;
12596 
12597 			/* First check out the status word */
12598 			lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
12599 			if (pmbox->mbxOwner != OWN_HOST) {
12600 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12601 				/*
12602 				 * Stray Mailbox Interrupt, mbxCommand <cmd>
12603 				 * mbxStatus <status>
12604 				 */
12605 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
12606 						LOG_SLI,
12607 						"(%d):0304 Stray Mailbox "
12608 						"Interrupt mbxCommand x%x "
12609 						"mbxStatus x%x\n",
12610 						(vport ? vport->vpi : 0),
12611 						pmbox->mbxCommand,
12612 						pmbox->mbxStatus);
12613 				/* clear mailbox attention bit */
12614 				work_ha_copy &= ~HA_MBATT;
12615 			} else {
12616 				phba->sli.mbox_active = NULL;
12617 				spin_unlock_irqrestore(&phba->hbalock, iflag);
12618 				phba->last_completion_time = jiffies;
12619 				del_timer(&phba->sli.mbox_tmo);
12620 				if (pmb->mbox_cmpl) {
12621 					lpfc_sli_pcimem_bcopy(mbox, pmbox,
12622 							MAILBOX_CMD_SIZE);
12623 					if (pmb->out_ext_byte_len &&
12624 						pmb->ctx_buf)
12625 						lpfc_sli_pcimem_bcopy(
12626 						phba->mbox_ext,
12627 						pmb->ctx_buf,
12628 						pmb->out_ext_byte_len);
12629 				}
12630 				if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
12631 					pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
12632 
12633 					lpfc_debugfs_disc_trc(vport,
12634 						LPFC_DISC_TRC_MBOX_VPORT,
12635 						"MBOX dflt rpi: : "
12636 						"status:x%x rpi:x%x",
12637 						(uint32_t)pmbox->mbxStatus,
12638 						pmbox->un.varWords[0], 0);
12639 
12640 					if (!pmbox->mbxStatus) {
12641 						mp = (struct lpfc_dmabuf *)
12642 							(pmb->ctx_buf);
12643 						ndlp = (struct lpfc_nodelist *)
12644 							pmb->ctx_ndlp;
12645 
12646 						/* Reg_LOGIN of dflt RPI was
12647 						 * successful. new lets get
12648 						 * rid of the RPI using the
12649 						 * same mbox buffer.
12650 						 */
12651 						lpfc_unreg_login(phba,
12652 							vport->vpi,
12653 							pmbox->un.varWords[0],
12654 							pmb);
12655 						pmb->mbox_cmpl =
12656 							lpfc_mbx_cmpl_dflt_rpi;
12657 						pmb->ctx_buf = mp;
12658 						pmb->ctx_ndlp = ndlp;
12659 						pmb->vport = vport;
12660 						rc = lpfc_sli_issue_mbox(phba,
12661 								pmb,
12662 								MBX_NOWAIT);
12663 						if (rc != MBX_BUSY)
12664 							lpfc_printf_log(phba,
12665 							KERN_ERR,
12666 							LOG_MBOX | LOG_SLI,
12667 							"0350 rc should have"
12668 							"been MBX_BUSY\n");
12669 						if (rc != MBX_NOT_FINISHED)
12670 							goto send_current_mbox;
12671 					}
12672 				}
12673 				spin_lock_irqsave(
12674 						&phba->pport->work_port_lock,
12675 						iflag);
12676 				phba->pport->work_port_events &=
12677 					~WORKER_MBOX_TMO;
12678 				spin_unlock_irqrestore(
12679 						&phba->pport->work_port_lock,
12680 						iflag);
12681 				lpfc_mbox_cmpl_put(phba, pmb);
12682 			}
12683 		} else
12684 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12685 
12686 		if ((work_ha_copy & HA_MBATT) &&
12687 		    (phba->sli.mbox_active == NULL)) {
12688 send_current_mbox:
12689 			/* Process next mailbox command if there is one */
12690 			do {
12691 				rc = lpfc_sli_issue_mbox(phba, NULL,
12692 							 MBX_NOWAIT);
12693 			} while (rc == MBX_NOT_FINISHED);
12694 			if (rc != MBX_SUCCESS)
12695 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
12696 						LOG_SLI, "0349 rc should be "
12697 						"MBX_SUCCESS\n");
12698 		}
12699 
12700 		spin_lock_irqsave(&phba->hbalock, iflag);
12701 		phba->work_ha |= work_ha_copy;
12702 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12703 		lpfc_worker_wake_up(phba);
12704 	}
12705 	return IRQ_HANDLED;
12706 unplug_error:
12707 	spin_unlock_irqrestore(&phba->hbalock, iflag);
12708 	return IRQ_HANDLED;
12709 
12710 } /* lpfc_sli_sp_intr_handler */
12711 
12712 /**
12713  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
12714  * @irq: Interrupt number.
12715  * @dev_id: The device context pointer.
12716  *
12717  * This function is directly called from the PCI layer as an interrupt
12718  * service routine when device with SLI-3 interface spec is enabled with
12719  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
12720  * ring event in the HBA. However, when the device is enabled with either
12721  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
12722  * device-level interrupt handler. When the PCI slot is in error recovery
12723  * or the HBA is undergoing initialization, the interrupt handler will not
12724  * process the interrupt. The SCSI FCP fast-path ring event are handled in
12725  * the intrrupt context. This function is called without any lock held.
12726  * It gets the hbalock to access and update SLI data structures.
12727  *
12728  * This function returns IRQ_HANDLED when interrupt is handled else it
12729  * returns IRQ_NONE.
12730  **/
12731 irqreturn_t
12732 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
12733 {
12734 	struct lpfc_hba  *phba;
12735 	uint32_t ha_copy;
12736 	unsigned long status;
12737 	unsigned long iflag;
12738 	struct lpfc_sli_ring *pring;
12739 
12740 	/* Get the driver's phba structure from the dev_id and
12741 	 * assume the HBA is not interrupting.
12742 	 */
12743 	phba = (struct lpfc_hba *) dev_id;
12744 
12745 	if (unlikely(!phba))
12746 		return IRQ_NONE;
12747 
12748 	/*
12749 	 * Stuff needs to be attented to when this function is invoked as an
12750 	 * individual interrupt handler in MSI-X multi-message interrupt mode
12751 	 */
12752 	if (phba->intr_type == MSIX) {
12753 		/* Check device state for handling interrupt */
12754 		if (lpfc_intr_state_check(phba))
12755 			return IRQ_NONE;
12756 		/* Need to read HA REG for FCP ring and other ring events */
12757 		if (lpfc_readl(phba->HAregaddr, &ha_copy))
12758 			return IRQ_HANDLED;
12759 		/* Clear up only attention source related to fast-path */
12760 		spin_lock_irqsave(&phba->hbalock, iflag);
12761 		/*
12762 		 * If there is deferred error attention, do not check for
12763 		 * any interrupt.
12764 		 */
12765 		if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12766 			spin_unlock_irqrestore(&phba->hbalock, iflag);
12767 			return IRQ_NONE;
12768 		}
12769 		writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
12770 			phba->HAregaddr);
12771 		readl(phba->HAregaddr); /* flush */
12772 		spin_unlock_irqrestore(&phba->hbalock, iflag);
12773 	} else
12774 		ha_copy = phba->ha_copy;
12775 
12776 	/*
12777 	 * Process all events on FCP ring. Take the optimized path for FCP IO.
12778 	 */
12779 	ha_copy &= ~(phba->work_ha_mask);
12780 
12781 	status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
12782 	status >>= (4*LPFC_FCP_RING);
12783 	pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12784 	if (status & HA_RXMASK)
12785 		lpfc_sli_handle_fast_ring_event(phba, pring, status);
12786 
12787 	if (phba->cfg_multi_ring_support == 2) {
12788 		/*
12789 		 * Process all events on extra ring. Take the optimized path
12790 		 * for extra ring IO.
12791 		 */
12792 		status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
12793 		status >>= (4*LPFC_EXTRA_RING);
12794 		if (status & HA_RXMASK) {
12795 			lpfc_sli_handle_fast_ring_event(phba,
12796 					&phba->sli.sli3_ring[LPFC_EXTRA_RING],
12797 					status);
12798 		}
12799 	}
12800 	return IRQ_HANDLED;
12801 }  /* lpfc_sli_fp_intr_handler */
12802 
12803 /**
12804  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
12805  * @irq: Interrupt number.
12806  * @dev_id: The device context pointer.
12807  *
12808  * This function is the HBA device-level interrupt handler to device with
12809  * SLI-3 interface spec, called from the PCI layer when either MSI or
12810  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
12811  * requires driver attention. This function invokes the slow-path interrupt
12812  * attention handling function and fast-path interrupt attention handling
12813  * function in turn to process the relevant HBA attention events. This
12814  * function is called without any lock held. It gets the hbalock to access
12815  * and update SLI data structures.
12816  *
12817  * This function returns IRQ_HANDLED when interrupt is handled, else it
12818  * returns IRQ_NONE.
12819  **/
12820 irqreturn_t
12821 lpfc_sli_intr_handler(int irq, void *dev_id)
12822 {
12823 	struct lpfc_hba  *phba;
12824 	irqreturn_t sp_irq_rc, fp_irq_rc;
12825 	unsigned long status1, status2;
12826 	uint32_t hc_copy;
12827 
12828 	/*
12829 	 * Get the driver's phba structure from the dev_id and
12830 	 * assume the HBA is not interrupting.
12831 	 */
12832 	phba = (struct lpfc_hba *) dev_id;
12833 
12834 	if (unlikely(!phba))
12835 		return IRQ_NONE;
12836 
12837 	/* Check device state for handling interrupt */
12838 	if (lpfc_intr_state_check(phba))
12839 		return IRQ_NONE;
12840 
12841 	spin_lock(&phba->hbalock);
12842 	if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
12843 		spin_unlock(&phba->hbalock);
12844 		return IRQ_HANDLED;
12845 	}
12846 
12847 	if (unlikely(!phba->ha_copy)) {
12848 		spin_unlock(&phba->hbalock);
12849 		return IRQ_NONE;
12850 	} else if (phba->ha_copy & HA_ERATT) {
12851 		if (phba->hba_flag & HBA_ERATT_HANDLED)
12852 			/* ERATT polling has handled ERATT */
12853 			phba->ha_copy &= ~HA_ERATT;
12854 		else
12855 			/* Indicate interrupt handler handles ERATT */
12856 			phba->hba_flag |= HBA_ERATT_HANDLED;
12857 	}
12858 
12859 	/*
12860 	 * If there is deferred error attention, do not check for any interrupt.
12861 	 */
12862 	if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12863 		spin_unlock(&phba->hbalock);
12864 		return IRQ_NONE;
12865 	}
12866 
12867 	/* Clear attention sources except link and error attentions */
12868 	if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
12869 		spin_unlock(&phba->hbalock);
12870 		return IRQ_HANDLED;
12871 	}
12872 	writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
12873 		| HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
12874 		phba->HCregaddr);
12875 	writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
12876 	writel(hc_copy, phba->HCregaddr);
12877 	readl(phba->HAregaddr); /* flush */
12878 	spin_unlock(&phba->hbalock);
12879 
12880 	/*
12881 	 * Invokes slow-path host attention interrupt handling as appropriate.
12882 	 */
12883 
12884 	/* status of events with mailbox and link attention */
12885 	status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
12886 
12887 	/* status of events with ELS ring */
12888 	status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
12889 	status2 >>= (4*LPFC_ELS_RING);
12890 
12891 	if (status1 || (status2 & HA_RXMASK))
12892 		sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
12893 	else
12894 		sp_irq_rc = IRQ_NONE;
12895 
12896 	/*
12897 	 * Invoke fast-path host attention interrupt handling as appropriate.
12898 	 */
12899 
12900 	/* status of events with FCP ring */
12901 	status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
12902 	status1 >>= (4*LPFC_FCP_RING);
12903 
12904 	/* status of events with extra ring */
12905 	if (phba->cfg_multi_ring_support == 2) {
12906 		status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
12907 		status2 >>= (4*LPFC_EXTRA_RING);
12908 	} else
12909 		status2 = 0;
12910 
12911 	if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
12912 		fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
12913 	else
12914 		fp_irq_rc = IRQ_NONE;
12915 
12916 	/* Return device-level interrupt handling status */
12917 	return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
12918 }  /* lpfc_sli_intr_handler */
12919 
12920 /**
12921  * lpfc_sli4_fcp_xri_abort_event_proc - Process fcp xri abort event
12922  * @phba: pointer to lpfc hba data structure.
12923  *
12924  * This routine is invoked by the worker thread to process all the pending
12925  * SLI4 FCP abort XRI events.
12926  **/
12927 void lpfc_sli4_fcp_xri_abort_event_proc(struct lpfc_hba *phba)
12928 {
12929 	struct lpfc_cq_event *cq_event;
12930 
12931 	/* First, declare the fcp xri abort event has been handled */
12932 	spin_lock_irq(&phba->hbalock);
12933 	phba->hba_flag &= ~FCP_XRI_ABORT_EVENT;
12934 	spin_unlock_irq(&phba->hbalock);
12935 	/* Now, handle all the fcp xri abort events */
12936 	while (!list_empty(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue)) {
12937 		/* Get the first event from the head of the event queue */
12938 		spin_lock_irq(&phba->hbalock);
12939 		list_remove_head(&phba->sli4_hba.sp_fcp_xri_aborted_work_queue,
12940 				 cq_event, struct lpfc_cq_event, list);
12941 		spin_unlock_irq(&phba->hbalock);
12942 		/* Notify aborted XRI for FCP work queue */
12943 		lpfc_sli4_fcp_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
12944 		/* Free the event processed back to the free pool */
12945 		lpfc_sli4_cq_event_release(phba, cq_event);
12946 	}
12947 }
12948 
12949 /**
12950  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
12951  * @phba: pointer to lpfc hba data structure.
12952  *
12953  * This routine is invoked by the worker thread to process all the pending
12954  * SLI4 els abort xri events.
12955  **/
12956 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
12957 {
12958 	struct lpfc_cq_event *cq_event;
12959 
12960 	/* First, declare the els xri abort event has been handled */
12961 	spin_lock_irq(&phba->hbalock);
12962 	phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
12963 	spin_unlock_irq(&phba->hbalock);
12964 	/* Now, handle all the els xri abort events */
12965 	while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
12966 		/* Get the first event from the head of the event queue */
12967 		spin_lock_irq(&phba->hbalock);
12968 		list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
12969 				 cq_event, struct lpfc_cq_event, list);
12970 		spin_unlock_irq(&phba->hbalock);
12971 		/* Notify aborted XRI for ELS work queue */
12972 		lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
12973 		/* Free the event processed back to the free pool */
12974 		lpfc_sli4_cq_event_release(phba, cq_event);
12975 	}
12976 }
12977 
12978 /**
12979  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
12980  * @phba: pointer to lpfc hba data structure
12981  * @pIocbIn: pointer to the rspiocbq
12982  * @pIocbOut: pointer to the cmdiocbq
12983  * @wcqe: pointer to the complete wcqe
12984  *
12985  * This routine transfers the fields of a command iocbq to a response iocbq
12986  * by copying all the IOCB fields from command iocbq and transferring the
12987  * completion status information from the complete wcqe.
12988  **/
12989 static void
12990 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
12991 			      struct lpfc_iocbq *pIocbIn,
12992 			      struct lpfc_iocbq *pIocbOut,
12993 			      struct lpfc_wcqe_complete *wcqe)
12994 {
12995 	int numBdes, i;
12996 	unsigned long iflags;
12997 	uint32_t status, max_response;
12998 	struct lpfc_dmabuf *dmabuf;
12999 	struct ulp_bde64 *bpl, bde;
13000 	size_t offset = offsetof(struct lpfc_iocbq, iocb);
13001 
13002 	memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
13003 	       sizeof(struct lpfc_iocbq) - offset);
13004 	/* Map WCQE parameters into irspiocb parameters */
13005 	status = bf_get(lpfc_wcqe_c_status, wcqe);
13006 	pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
13007 	if (pIocbOut->iocb_flag & LPFC_IO_FCP)
13008 		if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
13009 			pIocbIn->iocb.un.fcpi.fcpi_parm =
13010 					pIocbOut->iocb.un.fcpi.fcpi_parm -
13011 					wcqe->total_data_placed;
13012 		else
13013 			pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
13014 	else {
13015 		pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
13016 		switch (pIocbOut->iocb.ulpCommand) {
13017 		case CMD_ELS_REQUEST64_CR:
13018 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
13019 			bpl  = (struct ulp_bde64 *)dmabuf->virt;
13020 			bde.tus.w = le32_to_cpu(bpl[1].tus.w);
13021 			max_response = bde.tus.f.bdeSize;
13022 			break;
13023 		case CMD_GEN_REQUEST64_CR:
13024 			max_response = 0;
13025 			if (!pIocbOut->context3)
13026 				break;
13027 			numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
13028 					sizeof(struct ulp_bde64);
13029 			dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
13030 			bpl = (struct ulp_bde64 *)dmabuf->virt;
13031 			for (i = 0; i < numBdes; i++) {
13032 				bde.tus.w = le32_to_cpu(bpl[i].tus.w);
13033 				if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
13034 					max_response += bde.tus.f.bdeSize;
13035 			}
13036 			break;
13037 		default:
13038 			max_response = wcqe->total_data_placed;
13039 			break;
13040 		}
13041 		if (max_response < wcqe->total_data_placed)
13042 			pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
13043 		else
13044 			pIocbIn->iocb.un.genreq64.bdl.bdeSize =
13045 				wcqe->total_data_placed;
13046 	}
13047 
13048 	/* Convert BG errors for completion status */
13049 	if (status == CQE_STATUS_DI_ERROR) {
13050 		pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
13051 
13052 		if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
13053 			pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
13054 		else
13055 			pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
13056 
13057 		pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
13058 		if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
13059 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13060 				BGS_GUARD_ERR_MASK;
13061 		if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
13062 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13063 				BGS_APPTAG_ERR_MASK;
13064 		if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
13065 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13066 				BGS_REFTAG_ERR_MASK;
13067 
13068 		/* Check to see if there was any good data before the error */
13069 		if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
13070 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13071 				BGS_HI_WATER_MARK_PRESENT_MASK;
13072 			pIocbIn->iocb.unsli3.sli3_bg.bghm =
13073 				wcqe->total_data_placed;
13074 		}
13075 
13076 		/*
13077 		* Set ALL the error bits to indicate we don't know what
13078 		* type of error it is.
13079 		*/
13080 		if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
13081 			pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13082 				(BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
13083 				BGS_GUARD_ERR_MASK);
13084 	}
13085 
13086 	/* Pick up HBA exchange busy condition */
13087 	if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
13088 		spin_lock_irqsave(&phba->hbalock, iflags);
13089 		pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
13090 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13091 	}
13092 }
13093 
13094 /**
13095  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
13096  * @phba: Pointer to HBA context object.
13097  * @wcqe: Pointer to work-queue completion queue entry.
13098  *
13099  * This routine handles an ELS work-queue completion event and construct
13100  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
13101  * discovery engine to handle.
13102  *
13103  * Return: Pointer to the receive IOCBQ, NULL otherwise.
13104  **/
13105 static struct lpfc_iocbq *
13106 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
13107 			       struct lpfc_iocbq *irspiocbq)
13108 {
13109 	struct lpfc_sli_ring *pring;
13110 	struct lpfc_iocbq *cmdiocbq;
13111 	struct lpfc_wcqe_complete *wcqe;
13112 	unsigned long iflags;
13113 
13114 	pring = lpfc_phba_elsring(phba);
13115 	if (unlikely(!pring))
13116 		return NULL;
13117 
13118 	wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
13119 	spin_lock_irqsave(&pring->ring_lock, iflags);
13120 	pring->stats.iocb_event++;
13121 	/* Look up the ELS command IOCB and create pseudo response IOCB */
13122 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
13123 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13124 	if (unlikely(!cmdiocbq)) {
13125 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
13126 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13127 				"0386 ELS complete with no corresponding "
13128 				"cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
13129 				wcqe->word0, wcqe->total_data_placed,
13130 				wcqe->parameter, wcqe->word3);
13131 		lpfc_sli_release_iocbq(phba, irspiocbq);
13132 		return NULL;
13133 	}
13134 
13135 	/* Put the iocb back on the txcmplq */
13136 	lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
13137 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
13138 
13139 	/* Fake the irspiocbq and copy necessary response information */
13140 	lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
13141 
13142 	return irspiocbq;
13143 }
13144 
13145 inline struct lpfc_cq_event *
13146 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
13147 {
13148 	struct lpfc_cq_event *cq_event;
13149 
13150 	/* Allocate a new internal CQ_EVENT entry */
13151 	cq_event = lpfc_sli4_cq_event_alloc(phba);
13152 	if (!cq_event) {
13153 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13154 				"0602 Failed to alloc CQ_EVENT entry\n");
13155 		return NULL;
13156 	}
13157 
13158 	/* Move the CQE into the event */
13159 	memcpy(&cq_event->cqe, entry, size);
13160 	return cq_event;
13161 }
13162 
13163 /**
13164  * lpfc_sli4_sp_handle_async_event - Handle an asynchroous event
13165  * @phba: Pointer to HBA context object.
13166  * @cqe: Pointer to mailbox completion queue entry.
13167  *
13168  * This routine process a mailbox completion queue entry with asynchrous
13169  * event.
13170  *
13171  * Return: true if work posted to worker thread, otherwise false.
13172  **/
13173 static bool
13174 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13175 {
13176 	struct lpfc_cq_event *cq_event;
13177 	unsigned long iflags;
13178 
13179 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13180 			"0392 Async Event: word0:x%x, word1:x%x, "
13181 			"word2:x%x, word3:x%x\n", mcqe->word0,
13182 			mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
13183 
13184 	cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
13185 	if (!cq_event)
13186 		return false;
13187 	spin_lock_irqsave(&phba->hbalock, iflags);
13188 	list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
13189 	/* Set the async event flag */
13190 	phba->hba_flag |= ASYNC_EVENT;
13191 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13192 
13193 	return true;
13194 }
13195 
13196 /**
13197  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
13198  * @phba: Pointer to HBA context object.
13199  * @cqe: Pointer to mailbox completion queue entry.
13200  *
13201  * This routine process a mailbox completion queue entry with mailbox
13202  * completion event.
13203  *
13204  * Return: true if work posted to worker thread, otherwise false.
13205  **/
13206 static bool
13207 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13208 {
13209 	uint32_t mcqe_status;
13210 	MAILBOX_t *mbox, *pmbox;
13211 	struct lpfc_mqe *mqe;
13212 	struct lpfc_vport *vport;
13213 	struct lpfc_nodelist *ndlp;
13214 	struct lpfc_dmabuf *mp;
13215 	unsigned long iflags;
13216 	LPFC_MBOXQ_t *pmb;
13217 	bool workposted = false;
13218 	int rc;
13219 
13220 	/* If not a mailbox complete MCQE, out by checking mailbox consume */
13221 	if (!bf_get(lpfc_trailer_completed, mcqe))
13222 		goto out_no_mqe_complete;
13223 
13224 	/* Get the reference to the active mbox command */
13225 	spin_lock_irqsave(&phba->hbalock, iflags);
13226 	pmb = phba->sli.mbox_active;
13227 	if (unlikely(!pmb)) {
13228 		lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
13229 				"1832 No pending MBOX command to handle\n");
13230 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13231 		goto out_no_mqe_complete;
13232 	}
13233 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13234 	mqe = &pmb->u.mqe;
13235 	pmbox = (MAILBOX_t *)&pmb->u.mqe;
13236 	mbox = phba->mbox;
13237 	vport = pmb->vport;
13238 
13239 	/* Reset heartbeat timer */
13240 	phba->last_completion_time = jiffies;
13241 	del_timer(&phba->sli.mbox_tmo);
13242 
13243 	/* Move mbox data to caller's mailbox region, do endian swapping */
13244 	if (pmb->mbox_cmpl && mbox)
13245 		lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
13246 
13247 	/*
13248 	 * For mcqe errors, conditionally move a modified error code to
13249 	 * the mbox so that the error will not be missed.
13250 	 */
13251 	mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
13252 	if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
13253 		if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
13254 			bf_set(lpfc_mqe_status, mqe,
13255 			       (LPFC_MBX_ERROR_RANGE | mcqe_status));
13256 	}
13257 	if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13258 		pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13259 		lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
13260 				      "MBOX dflt rpi: status:x%x rpi:x%x",
13261 				      mcqe_status,
13262 				      pmbox->un.varWords[0], 0);
13263 		if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
13264 			mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
13265 			ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
13266 			/* Reg_LOGIN of dflt RPI was successful. Now lets get
13267 			 * RID of the PPI using the same mbox buffer.
13268 			 */
13269 			lpfc_unreg_login(phba, vport->vpi,
13270 					 pmbox->un.varWords[0], pmb);
13271 			pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
13272 			pmb->ctx_buf = mp;
13273 			pmb->ctx_ndlp = ndlp;
13274 			pmb->vport = vport;
13275 			rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
13276 			if (rc != MBX_BUSY)
13277 				lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
13278 						LOG_SLI, "0385 rc should "
13279 						"have been MBX_BUSY\n");
13280 			if (rc != MBX_NOT_FINISHED)
13281 				goto send_current_mbox;
13282 		}
13283 	}
13284 	spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
13285 	phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
13286 	spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
13287 
13288 	/* There is mailbox completion work to do */
13289 	spin_lock_irqsave(&phba->hbalock, iflags);
13290 	__lpfc_mbox_cmpl_put(phba, pmb);
13291 	phba->work_ha |= HA_MBATT;
13292 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13293 	workposted = true;
13294 
13295 send_current_mbox:
13296 	spin_lock_irqsave(&phba->hbalock, iflags);
13297 	/* Release the mailbox command posting token */
13298 	phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13299 	/* Setting active mailbox pointer need to be in sync to flag clear */
13300 	phba->sli.mbox_active = NULL;
13301 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13302 	/* Wake up worker thread to post the next pending mailbox command */
13303 	lpfc_worker_wake_up(phba);
13304 out_no_mqe_complete:
13305 	if (bf_get(lpfc_trailer_consumed, mcqe))
13306 		lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13307 	return workposted;
13308 }
13309 
13310 /**
13311  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
13312  * @phba: Pointer to HBA context object.
13313  * @cqe: Pointer to mailbox completion queue entry.
13314  *
13315  * This routine process a mailbox completion queue entry, it invokes the
13316  * proper mailbox complete handling or asynchrous event handling routine
13317  * according to the MCQE's async bit.
13318  *
13319  * Return: true if work posted to worker thread, otherwise false.
13320  **/
13321 static bool
13322 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_cqe *cqe)
13323 {
13324 	struct lpfc_mcqe mcqe;
13325 	bool workposted;
13326 
13327 	/* Copy the mailbox MCQE and convert endian order as needed */
13328 	lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
13329 
13330 	/* Invoke the proper event handling routine */
13331 	if (!bf_get(lpfc_trailer_async, &mcqe))
13332 		workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
13333 	else
13334 		workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
13335 	return workposted;
13336 }
13337 
13338 /**
13339  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
13340  * @phba: Pointer to HBA context object.
13341  * @cq: Pointer to associated CQ
13342  * @wcqe: Pointer to work-queue completion queue entry.
13343  *
13344  * This routine handles an ELS work-queue completion event.
13345  *
13346  * Return: true if work posted to worker thread, otherwise false.
13347  **/
13348 static bool
13349 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13350 			     struct lpfc_wcqe_complete *wcqe)
13351 {
13352 	struct lpfc_iocbq *irspiocbq;
13353 	unsigned long iflags;
13354 	struct lpfc_sli_ring *pring = cq->pring;
13355 	int txq_cnt = 0;
13356 	int txcmplq_cnt = 0;
13357 	int fcp_txcmplq_cnt = 0;
13358 
13359 	/* Check for response status */
13360 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
13361 		/* Log the error status */
13362 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13363 				"0357 ELS CQE error: status=x%x: "
13364 				"CQE: %08x %08x %08x %08x\n",
13365 				bf_get(lpfc_wcqe_c_status, wcqe),
13366 				wcqe->word0, wcqe->total_data_placed,
13367 				wcqe->parameter, wcqe->word3);
13368 	}
13369 
13370 	/* Get an irspiocbq for later ELS response processing use */
13371 	irspiocbq = lpfc_sli_get_iocbq(phba);
13372 	if (!irspiocbq) {
13373 		if (!list_empty(&pring->txq))
13374 			txq_cnt++;
13375 		if (!list_empty(&pring->txcmplq))
13376 			txcmplq_cnt++;
13377 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13378 			"0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
13379 			"fcp_txcmplq_cnt=%d, els_txcmplq_cnt=%d\n",
13380 			txq_cnt, phba->iocb_cnt,
13381 			fcp_txcmplq_cnt,
13382 			txcmplq_cnt);
13383 		return false;
13384 	}
13385 
13386 	/* Save off the slow-path queue event for work thread to process */
13387 	memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
13388 	spin_lock_irqsave(&phba->hbalock, iflags);
13389 	list_add_tail(&irspiocbq->cq_event.list,
13390 		      &phba->sli4_hba.sp_queue_event);
13391 	phba->hba_flag |= HBA_SP_QUEUE_EVT;
13392 	spin_unlock_irqrestore(&phba->hbalock, iflags);
13393 
13394 	return true;
13395 }
13396 
13397 /**
13398  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
13399  * @phba: Pointer to HBA context object.
13400  * @wcqe: Pointer to work-queue completion queue entry.
13401  *
13402  * This routine handles slow-path WQ entry consumed event by invoking the
13403  * proper WQ release routine to the slow-path WQ.
13404  **/
13405 static void
13406 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
13407 			     struct lpfc_wcqe_release *wcqe)
13408 {
13409 	/* sanity check on queue memory */
13410 	if (unlikely(!phba->sli4_hba.els_wq))
13411 		return;
13412 	/* Check for the slow-path ELS work queue */
13413 	if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
13414 		lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
13415 				     bf_get(lpfc_wcqe_r_wqe_index, wcqe));
13416 	else
13417 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13418 				"2579 Slow-path wqe consume event carries "
13419 				"miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
13420 				bf_get(lpfc_wcqe_r_wqe_index, wcqe),
13421 				phba->sli4_hba.els_wq->queue_id);
13422 }
13423 
13424 /**
13425  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
13426  * @phba: Pointer to HBA context object.
13427  * @cq: Pointer to a WQ completion queue.
13428  * @wcqe: Pointer to work-queue completion queue entry.
13429  *
13430  * This routine handles an XRI abort event.
13431  *
13432  * Return: true if work posted to worker thread, otherwise false.
13433  **/
13434 static bool
13435 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
13436 				   struct lpfc_queue *cq,
13437 				   struct sli4_wcqe_xri_aborted *wcqe)
13438 {
13439 	bool workposted = false;
13440 	struct lpfc_cq_event *cq_event;
13441 	unsigned long iflags;
13442 
13443 	switch (cq->subtype) {
13444 	case LPFC_FCP:
13445 		cq_event = lpfc_cq_event_setup(
13446 			phba, wcqe, sizeof(struct sli4_wcqe_xri_aborted));
13447 		if (!cq_event)
13448 			return false;
13449 		spin_lock_irqsave(&phba->hbalock, iflags);
13450 		list_add_tail(&cq_event->list,
13451 			      &phba->sli4_hba.sp_fcp_xri_aborted_work_queue);
13452 		/* Set the fcp xri abort event flag */
13453 		phba->hba_flag |= FCP_XRI_ABORT_EVENT;
13454 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13455 		workposted = true;
13456 		break;
13457 	case LPFC_NVME_LS: /* NVME LS uses ELS resources */
13458 	case LPFC_ELS:
13459 		cq_event = lpfc_cq_event_setup(
13460 			phba, wcqe, sizeof(struct sli4_wcqe_xri_aborted));
13461 		if (!cq_event)
13462 			return false;
13463 		spin_lock_irqsave(&phba->hbalock, iflags);
13464 		list_add_tail(&cq_event->list,
13465 			      &phba->sli4_hba.sp_els_xri_aborted_work_queue);
13466 		/* Set the els xri abort event flag */
13467 		phba->hba_flag |= ELS_XRI_ABORT_EVENT;
13468 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13469 		workposted = true;
13470 		break;
13471 	case LPFC_NVME:
13472 		/* Notify aborted XRI for NVME work queue */
13473 		if (phba->nvmet_support)
13474 			lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
13475 		else
13476 			lpfc_sli4_nvme_xri_aborted(phba, wcqe);
13477 
13478 		workposted = false;
13479 		break;
13480 	default:
13481 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13482 				"0603 Invalid CQ subtype %d: "
13483 				"%08x %08x %08x %08x\n",
13484 				cq->subtype, wcqe->word0, wcqe->parameter,
13485 				wcqe->word2, wcqe->word3);
13486 		workposted = false;
13487 		break;
13488 	}
13489 	return workposted;
13490 }
13491 
13492 #define FC_RCTL_MDS_DIAGS	0xF4
13493 
13494 /**
13495  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
13496  * @phba: Pointer to HBA context object.
13497  * @rcqe: Pointer to receive-queue completion queue entry.
13498  *
13499  * This routine process a receive-queue completion queue entry.
13500  *
13501  * Return: true if work posted to worker thread, otherwise false.
13502  **/
13503 static bool
13504 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
13505 {
13506 	bool workposted = false;
13507 	struct fc_frame_header *fc_hdr;
13508 	struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
13509 	struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
13510 	struct lpfc_nvmet_tgtport *tgtp;
13511 	struct hbq_dmabuf *dma_buf;
13512 	uint32_t status, rq_id;
13513 	unsigned long iflags;
13514 
13515 	/* sanity check on queue memory */
13516 	if (unlikely(!hrq) || unlikely(!drq))
13517 		return workposted;
13518 
13519 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
13520 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
13521 	else
13522 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
13523 	if (rq_id != hrq->queue_id)
13524 		goto out;
13525 
13526 	status = bf_get(lpfc_rcqe_status, rcqe);
13527 	switch (status) {
13528 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
13529 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13530 				"2537 Receive Frame Truncated!!\n");
13531 	case FC_STATUS_RQ_SUCCESS:
13532 		spin_lock_irqsave(&phba->hbalock, iflags);
13533 		lpfc_sli4_rq_release(hrq, drq);
13534 		dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
13535 		if (!dma_buf) {
13536 			hrq->RQ_no_buf_found++;
13537 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13538 			goto out;
13539 		}
13540 		hrq->RQ_rcv_buf++;
13541 		hrq->RQ_buf_posted--;
13542 		memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
13543 
13544 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
13545 
13546 		if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
13547 		    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
13548 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13549 			/* Handle MDS Loopback frames */
13550 			lpfc_sli4_handle_mds_loopback(phba->pport, dma_buf);
13551 			break;
13552 		}
13553 
13554 		/* save off the frame for the work thread to process */
13555 		list_add_tail(&dma_buf->cq_event.list,
13556 			      &phba->sli4_hba.sp_queue_event);
13557 		/* Frame received */
13558 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
13559 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13560 		workposted = true;
13561 		break;
13562 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
13563 		if (phba->nvmet_support) {
13564 			tgtp = phba->targetport->private;
13565 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_NVME,
13566 					"6402 RQE Error x%x, posted %d err_cnt "
13567 					"%d: %x %x %x\n",
13568 					status, hrq->RQ_buf_posted,
13569 					hrq->RQ_no_posted_buf,
13570 					atomic_read(&tgtp->rcv_fcp_cmd_in),
13571 					atomic_read(&tgtp->rcv_fcp_cmd_out),
13572 					atomic_read(&tgtp->xmt_fcp_release));
13573 		}
13574 		/* fallthrough */
13575 
13576 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
13577 		hrq->RQ_no_posted_buf++;
13578 		/* Post more buffers if possible */
13579 		spin_lock_irqsave(&phba->hbalock, iflags);
13580 		phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
13581 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13582 		workposted = true;
13583 		break;
13584 	}
13585 out:
13586 	return workposted;
13587 }
13588 
13589 /**
13590  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
13591  * @phba: Pointer to HBA context object.
13592  * @cq: Pointer to the completion queue.
13593  * @wcqe: Pointer to a completion queue entry.
13594  *
13595  * This routine process a slow-path work-queue or receive queue completion queue
13596  * entry.
13597  *
13598  * Return: true if work posted to worker thread, otherwise false.
13599  **/
13600 static bool
13601 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13602 			 struct lpfc_cqe *cqe)
13603 {
13604 	struct lpfc_cqe cqevt;
13605 	bool workposted = false;
13606 
13607 	/* Copy the work queue CQE and convert endian order if needed */
13608 	lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
13609 
13610 	/* Check and process for different type of WCQE and dispatch */
13611 	switch (bf_get(lpfc_cqe_code, &cqevt)) {
13612 	case CQE_CODE_COMPL_WQE:
13613 		/* Process the WQ/RQ complete event */
13614 		phba->last_completion_time = jiffies;
13615 		workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
13616 				(struct lpfc_wcqe_complete *)&cqevt);
13617 		break;
13618 	case CQE_CODE_RELEASE_WQE:
13619 		/* Process the WQ release event */
13620 		lpfc_sli4_sp_handle_rel_wcqe(phba,
13621 				(struct lpfc_wcqe_release *)&cqevt);
13622 		break;
13623 	case CQE_CODE_XRI_ABORTED:
13624 		/* Process the WQ XRI abort event */
13625 		phba->last_completion_time = jiffies;
13626 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
13627 				(struct sli4_wcqe_xri_aborted *)&cqevt);
13628 		break;
13629 	case CQE_CODE_RECEIVE:
13630 	case CQE_CODE_RECEIVE_V1:
13631 		/* Process the RQ event */
13632 		phba->last_completion_time = jiffies;
13633 		workposted = lpfc_sli4_sp_handle_rcqe(phba,
13634 				(struct lpfc_rcqe *)&cqevt);
13635 		break;
13636 	default:
13637 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13638 				"0388 Not a valid WCQE code: x%x\n",
13639 				bf_get(lpfc_cqe_code, &cqevt));
13640 		break;
13641 	}
13642 	return workposted;
13643 }
13644 
13645 /**
13646  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
13647  * @phba: Pointer to HBA context object.
13648  * @eqe: Pointer to fast-path event queue entry.
13649  *
13650  * This routine process a event queue entry from the slow-path event queue.
13651  * It will check the MajorCode and MinorCode to determine this is for a
13652  * completion event on a completion queue, if not, an error shall be logged
13653  * and just return. Otherwise, it will get to the corresponding completion
13654  * queue and process all the entries on that completion queue, rearm the
13655  * completion queue, and then return.
13656  *
13657  **/
13658 static void
13659 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
13660 	struct lpfc_queue *speq)
13661 {
13662 	struct lpfc_queue *cq = NULL, *childq;
13663 	uint16_t cqid;
13664 
13665 	/* Get the reference to the corresponding CQ */
13666 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
13667 
13668 	list_for_each_entry(childq, &speq->child_list, list) {
13669 		if (childq->queue_id == cqid) {
13670 			cq = childq;
13671 			break;
13672 		}
13673 	}
13674 	if (unlikely(!cq)) {
13675 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
13676 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13677 					"0365 Slow-path CQ identifier "
13678 					"(%d) does not exist\n", cqid);
13679 		return;
13680 	}
13681 
13682 	/* Save EQ associated with this CQ */
13683 	cq->assoc_qp = speq;
13684 
13685 	if (!queue_work(phba->wq, &cq->spwork))
13686 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13687 				"0390 Cannot schedule soft IRQ "
13688 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
13689 				cqid, cq->queue_id, smp_processor_id());
13690 }
13691 
13692 /**
13693  * lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
13694  * @phba: Pointer to HBA context object.
13695  *
13696  * This routine process a event queue entry from the slow-path event queue.
13697  * It will check the MajorCode and MinorCode to determine this is for a
13698  * completion event on a completion queue, if not, an error shall be logged
13699  * and just return. Otherwise, it will get to the corresponding completion
13700  * queue and process all the entries on that completion queue, rearm the
13701  * completion queue, and then return.
13702  *
13703  **/
13704 static void
13705 lpfc_sli4_sp_process_cq(struct work_struct *work)
13706 {
13707 	struct lpfc_queue *cq =
13708 		container_of(work, struct lpfc_queue, spwork);
13709 	struct lpfc_hba *phba = cq->phba;
13710 	struct lpfc_cqe *cqe;
13711 	bool workposted = false;
13712 	int ccount = 0;
13713 
13714 	/* Process all the entries to the CQ */
13715 	switch (cq->type) {
13716 	case LPFC_MCQ:
13717 		while ((cqe = lpfc_sli4_cq_get(cq))) {
13718 			workposted |= lpfc_sli4_sp_handle_mcqe(phba, cqe);
13719 			if (!(++ccount % cq->entry_repost))
13720 				break;
13721 			cq->CQ_mbox++;
13722 		}
13723 		break;
13724 	case LPFC_WCQ:
13725 		while ((cqe = lpfc_sli4_cq_get(cq))) {
13726 			if (cq->subtype == LPFC_FCP ||
13727 			    cq->subtype == LPFC_NVME) {
13728 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
13729 				if (phba->ktime_on)
13730 					cq->isr_timestamp = ktime_get_ns();
13731 				else
13732 					cq->isr_timestamp = 0;
13733 #endif
13734 				workposted |= lpfc_sli4_fp_handle_cqe(phba, cq,
13735 								       cqe);
13736 			} else {
13737 				workposted |= lpfc_sli4_sp_handle_cqe(phba, cq,
13738 								      cqe);
13739 			}
13740 			if (!(++ccount % cq->entry_repost))
13741 				break;
13742 		}
13743 
13744 		/* Track the max number of CQEs processed in 1 EQ */
13745 		if (ccount > cq->CQ_max_cqe)
13746 			cq->CQ_max_cqe = ccount;
13747 		break;
13748 	default:
13749 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13750 				"0370 Invalid completion queue type (%d)\n",
13751 				cq->type);
13752 		return;
13753 	}
13754 
13755 	/* Catch the no cq entry condition, log an error */
13756 	if (unlikely(ccount == 0))
13757 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13758 				"0371 No entry from the CQ: identifier "
13759 				"(x%x), type (%d)\n", cq->queue_id, cq->type);
13760 
13761 	/* In any case, flash and re-arm the RCQ */
13762 	phba->sli4_hba.sli4_cq_release(cq, LPFC_QUEUE_REARM);
13763 
13764 	/* wake up worker thread if there are works to be done */
13765 	if (workposted)
13766 		lpfc_worker_wake_up(phba);
13767 }
13768 
13769 /**
13770  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
13771  * @phba: Pointer to HBA context object.
13772  * @cq: Pointer to associated CQ
13773  * @wcqe: Pointer to work-queue completion queue entry.
13774  *
13775  * This routine process a fast-path work queue completion entry from fast-path
13776  * event queue for FCP command response completion.
13777  **/
13778 static void
13779 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13780 			     struct lpfc_wcqe_complete *wcqe)
13781 {
13782 	struct lpfc_sli_ring *pring = cq->pring;
13783 	struct lpfc_iocbq *cmdiocbq;
13784 	struct lpfc_iocbq irspiocbq;
13785 	unsigned long iflags;
13786 
13787 	/* Check for response status */
13788 	if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
13789 		/* If resource errors reported from HBA, reduce queue
13790 		 * depth of the SCSI device.
13791 		 */
13792 		if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
13793 		     IOSTAT_LOCAL_REJECT)) &&
13794 		    ((wcqe->parameter & IOERR_PARAM_MASK) ==
13795 		     IOERR_NO_RESOURCES))
13796 			phba->lpfc_rampdown_queue_depth(phba);
13797 
13798 		/* Log the error status */
13799 		lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13800 				"0373 FCP CQE error: status=x%x: "
13801 				"CQE: %08x %08x %08x %08x\n",
13802 				bf_get(lpfc_wcqe_c_status, wcqe),
13803 				wcqe->word0, wcqe->total_data_placed,
13804 				wcqe->parameter, wcqe->word3);
13805 	}
13806 
13807 	/* Look up the FCP command IOCB and create pseudo response IOCB */
13808 	spin_lock_irqsave(&pring->ring_lock, iflags);
13809 	pring->stats.iocb_event++;
13810 	cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
13811 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13812 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
13813 	if (unlikely(!cmdiocbq)) {
13814 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13815 				"0374 FCP complete with no corresponding "
13816 				"cmdiocb: iotag (%d)\n",
13817 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13818 		return;
13819 	}
13820 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
13821 	cmdiocbq->isr_timestamp = cq->isr_timestamp;
13822 #endif
13823 	if (cmdiocbq->iocb_cmpl == NULL) {
13824 		if (cmdiocbq->wqe_cmpl) {
13825 			if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
13826 				spin_lock_irqsave(&phba->hbalock, iflags);
13827 				cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
13828 				spin_unlock_irqrestore(&phba->hbalock, iflags);
13829 			}
13830 
13831 			/* Pass the cmd_iocb and the wcqe to the upper layer */
13832 			(cmdiocbq->wqe_cmpl)(phba, cmdiocbq, wcqe);
13833 			return;
13834 		}
13835 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13836 				"0375 FCP cmdiocb not callback function "
13837 				"iotag: (%d)\n",
13838 				bf_get(lpfc_wcqe_c_request_tag, wcqe));
13839 		return;
13840 	}
13841 
13842 	/* Fake the irspiocb and copy necessary response information */
13843 	lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
13844 
13845 	if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
13846 		spin_lock_irqsave(&phba->hbalock, iflags);
13847 		cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
13848 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13849 	}
13850 
13851 	/* Pass the cmd_iocb and the rsp state to the upper layer */
13852 	(cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
13853 }
13854 
13855 /**
13856  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
13857  * @phba: Pointer to HBA context object.
13858  * @cq: Pointer to completion queue.
13859  * @wcqe: Pointer to work-queue completion queue entry.
13860  *
13861  * This routine handles an fast-path WQ entry consumed event by invoking the
13862  * proper WQ release routine to the slow-path WQ.
13863  **/
13864 static void
13865 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13866 			     struct lpfc_wcqe_release *wcqe)
13867 {
13868 	struct lpfc_queue *childwq;
13869 	bool wqid_matched = false;
13870 	uint16_t hba_wqid;
13871 
13872 	/* Check for fast-path FCP work queue release */
13873 	hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
13874 	list_for_each_entry(childwq, &cq->child_list, list) {
13875 		if (childwq->queue_id == hba_wqid) {
13876 			lpfc_sli4_wq_release(childwq,
13877 					bf_get(lpfc_wcqe_r_wqe_index, wcqe));
13878 			if (childwq->q_flag & HBA_NVMET_WQFULL)
13879 				lpfc_nvmet_wqfull_process(phba, childwq);
13880 			wqid_matched = true;
13881 			break;
13882 		}
13883 	}
13884 	/* Report warning log message if no match found */
13885 	if (wqid_matched != true)
13886 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13887 				"2580 Fast-path wqe consume event carries "
13888 				"miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
13889 }
13890 
13891 /**
13892  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
13893  * @phba: Pointer to HBA context object.
13894  * @rcqe: Pointer to receive-queue completion queue entry.
13895  *
13896  * This routine process a receive-queue completion queue entry.
13897  *
13898  * Return: true if work posted to worker thread, otherwise false.
13899  **/
13900 static bool
13901 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13902 			    struct lpfc_rcqe *rcqe)
13903 {
13904 	bool workposted = false;
13905 	struct lpfc_queue *hrq;
13906 	struct lpfc_queue *drq;
13907 	struct rqb_dmabuf *dma_buf;
13908 	struct fc_frame_header *fc_hdr;
13909 	struct lpfc_nvmet_tgtport *tgtp;
13910 	uint32_t status, rq_id;
13911 	unsigned long iflags;
13912 	uint32_t fctl, idx;
13913 
13914 	if ((phba->nvmet_support == 0) ||
13915 	    (phba->sli4_hba.nvmet_cqset == NULL))
13916 		return workposted;
13917 
13918 	idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
13919 	hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
13920 	drq = phba->sli4_hba.nvmet_mrq_data[idx];
13921 
13922 	/* sanity check on queue memory */
13923 	if (unlikely(!hrq) || unlikely(!drq))
13924 		return workposted;
13925 
13926 	if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
13927 		rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
13928 	else
13929 		rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
13930 
13931 	if ((phba->nvmet_support == 0) ||
13932 	    (rq_id != hrq->queue_id))
13933 		return workposted;
13934 
13935 	status = bf_get(lpfc_rcqe_status, rcqe);
13936 	switch (status) {
13937 	case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
13938 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13939 				"6126 Receive Frame Truncated!!\n");
13940 		/* Drop thru */
13941 	case FC_STATUS_RQ_SUCCESS:
13942 		spin_lock_irqsave(&phba->hbalock, iflags);
13943 		lpfc_sli4_rq_release(hrq, drq);
13944 		dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
13945 		if (!dma_buf) {
13946 			hrq->RQ_no_buf_found++;
13947 			spin_unlock_irqrestore(&phba->hbalock, iflags);
13948 			goto out;
13949 		}
13950 		spin_unlock_irqrestore(&phba->hbalock, iflags);
13951 		hrq->RQ_rcv_buf++;
13952 		hrq->RQ_buf_posted--;
13953 		fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
13954 
13955 		/* Just some basic sanity checks on FCP Command frame */
13956 		fctl = (fc_hdr->fh_f_ctl[0] << 16 |
13957 		fc_hdr->fh_f_ctl[1] << 8 |
13958 		fc_hdr->fh_f_ctl[2]);
13959 		if (((fctl &
13960 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
13961 		    (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
13962 		    (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
13963 			goto drop;
13964 
13965 		if (fc_hdr->fh_type == FC_TYPE_FCP) {
13966 			dma_buf->bytes_recv = bf_get(lpfc_rcqe_length,  rcqe);
13967 			lpfc_nvmet_unsol_fcp_event(
13968 				phba, idx, dma_buf,
13969 				cq->isr_timestamp);
13970 			return false;
13971 		}
13972 drop:
13973 		lpfc_in_buf_free(phba, &dma_buf->dbuf);
13974 		break;
13975 	case FC_STATUS_INSUFF_BUF_FRM_DISC:
13976 		if (phba->nvmet_support) {
13977 			tgtp = phba->targetport->private;
13978 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_NVME,
13979 					"6401 RQE Error x%x, posted %d err_cnt "
13980 					"%d: %x %x %x\n",
13981 					status, hrq->RQ_buf_posted,
13982 					hrq->RQ_no_posted_buf,
13983 					atomic_read(&tgtp->rcv_fcp_cmd_in),
13984 					atomic_read(&tgtp->rcv_fcp_cmd_out),
13985 					atomic_read(&tgtp->xmt_fcp_release));
13986 		}
13987 		/* fallthrough */
13988 
13989 	case FC_STATUS_INSUFF_BUF_NEED_BUF:
13990 		hrq->RQ_no_posted_buf++;
13991 		/* Post more buffers if possible */
13992 		break;
13993 	}
13994 out:
13995 	return workposted;
13996 }
13997 
13998 /**
13999  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
14000  * @cq: Pointer to the completion queue.
14001  * @eqe: Pointer to fast-path completion queue entry.
14002  *
14003  * This routine process a fast-path work queue completion entry from fast-path
14004  * event queue for FCP command response completion.
14005  **/
14006 static int
14007 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14008 			 struct lpfc_cqe *cqe)
14009 {
14010 	struct lpfc_wcqe_release wcqe;
14011 	bool workposted = false;
14012 
14013 	/* Copy the work queue CQE and convert endian order if needed */
14014 	lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
14015 
14016 	/* Check and process for different type of WCQE and dispatch */
14017 	switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
14018 	case CQE_CODE_COMPL_WQE:
14019 	case CQE_CODE_NVME_ERSP:
14020 		cq->CQ_wq++;
14021 		/* Process the WQ complete event */
14022 		phba->last_completion_time = jiffies;
14023 		if ((cq->subtype == LPFC_FCP) || (cq->subtype == LPFC_NVME))
14024 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
14025 				(struct lpfc_wcqe_complete *)&wcqe);
14026 		if (cq->subtype == LPFC_NVME_LS)
14027 			lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
14028 				(struct lpfc_wcqe_complete *)&wcqe);
14029 		break;
14030 	case CQE_CODE_RELEASE_WQE:
14031 		cq->CQ_release_wqe++;
14032 		/* Process the WQ release event */
14033 		lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
14034 				(struct lpfc_wcqe_release *)&wcqe);
14035 		break;
14036 	case CQE_CODE_XRI_ABORTED:
14037 		cq->CQ_xri_aborted++;
14038 		/* Process the WQ XRI abort event */
14039 		phba->last_completion_time = jiffies;
14040 		workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14041 				(struct sli4_wcqe_xri_aborted *)&wcqe);
14042 		break;
14043 	case CQE_CODE_RECEIVE_V1:
14044 	case CQE_CODE_RECEIVE:
14045 		phba->last_completion_time = jiffies;
14046 		if (cq->subtype == LPFC_NVMET) {
14047 			workposted = lpfc_sli4_nvmet_handle_rcqe(
14048 				phba, cq, (struct lpfc_rcqe *)&wcqe);
14049 		}
14050 		break;
14051 	default:
14052 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14053 				"0144 Not a valid CQE code: x%x\n",
14054 				bf_get(lpfc_wcqe_c_code, &wcqe));
14055 		break;
14056 	}
14057 	return workposted;
14058 }
14059 
14060 /**
14061  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
14062  * @phba: Pointer to HBA context object.
14063  * @eqe: Pointer to fast-path event queue entry.
14064  *
14065  * This routine process a event queue entry from the fast-path event queue.
14066  * It will check the MajorCode and MinorCode to determine this is for a
14067  * completion event on a completion queue, if not, an error shall be logged
14068  * and just return. Otherwise, it will get to the corresponding completion
14069  * queue and process all the entries on the completion queue, rearm the
14070  * completion queue, and then return.
14071  **/
14072 static void
14073 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14074 			uint32_t qidx)
14075 {
14076 	struct lpfc_queue *cq = NULL;
14077 	uint16_t cqid, id;
14078 
14079 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
14080 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14081 				"0366 Not a valid completion "
14082 				"event: majorcode=x%x, minorcode=x%x\n",
14083 				bf_get_le32(lpfc_eqe_major_code, eqe),
14084 				bf_get_le32(lpfc_eqe_minor_code, eqe));
14085 		return;
14086 	}
14087 
14088 	/* Get the reference to the corresponding CQ */
14089 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14090 
14091 	if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
14092 		id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
14093 		if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
14094 			/* Process NVMET unsol rcv */
14095 			cq = phba->sli4_hba.nvmet_cqset[cqid - id];
14096 			goto  process_cq;
14097 		}
14098 	}
14099 
14100 	if (phba->sli4_hba.nvme_cq_map &&
14101 	    (cqid == phba->sli4_hba.nvme_cq_map[qidx])) {
14102 		/* Process NVME / NVMET command completion */
14103 		cq = phba->sli4_hba.nvme_cq[qidx];
14104 		goto  process_cq;
14105 	}
14106 
14107 	if (phba->sli4_hba.fcp_cq_map &&
14108 	    (cqid == phba->sli4_hba.fcp_cq_map[qidx])) {
14109 		/* Process FCP command completion */
14110 		cq = phba->sli4_hba.fcp_cq[qidx];
14111 		goto  process_cq;
14112 	}
14113 
14114 	if (phba->sli4_hba.nvmels_cq &&
14115 	    (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
14116 		/* Process NVME unsol rcv */
14117 		cq = phba->sli4_hba.nvmels_cq;
14118 	}
14119 
14120 	/* Otherwise this is a Slow path event */
14121 	if (cq == NULL) {
14122 		lpfc_sli4_sp_handle_eqe(phba, eqe, phba->sli4_hba.hba_eq[qidx]);
14123 		return;
14124 	}
14125 
14126 process_cq:
14127 	if (unlikely(cqid != cq->queue_id)) {
14128 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14129 				"0368 Miss-matched fast-path completion "
14130 				"queue identifier: eqcqid=%d, fcpcqid=%d\n",
14131 				cqid, cq->queue_id);
14132 		return;
14133 	}
14134 
14135 	/* Save EQ associated with this CQ */
14136 	cq->assoc_qp = phba->sli4_hba.hba_eq[qidx];
14137 
14138 	if (!queue_work(phba->wq, &cq->irqwork))
14139 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14140 				"0363 Cannot schedule soft IRQ "
14141 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14142 				cqid, cq->queue_id, smp_processor_id());
14143 }
14144 
14145 /**
14146  * lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
14147  * @phba: Pointer to HBA context object.
14148  * @eqe: Pointer to fast-path event queue entry.
14149  *
14150  * This routine process a event queue entry from the fast-path event queue.
14151  * It will check the MajorCode and MinorCode to determine this is for a
14152  * completion event on a completion queue, if not, an error shall be logged
14153  * and just return. Otherwise, it will get to the corresponding completion
14154  * queue and process all the entries on the completion queue, rearm the
14155  * completion queue, and then return.
14156  **/
14157 static void
14158 lpfc_sli4_hba_process_cq(struct work_struct *work)
14159 {
14160 	struct lpfc_queue *cq =
14161 		container_of(work, struct lpfc_queue, irqwork);
14162 	struct lpfc_hba *phba = cq->phba;
14163 	struct lpfc_cqe *cqe;
14164 	bool workposted = false;
14165 	int ccount = 0;
14166 
14167 	/* Process all the entries to the CQ */
14168 	while ((cqe = lpfc_sli4_cq_get(cq))) {
14169 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
14170 		if (phba->ktime_on)
14171 			cq->isr_timestamp = ktime_get_ns();
14172 		else
14173 			cq->isr_timestamp = 0;
14174 #endif
14175 		workposted |= lpfc_sli4_fp_handle_cqe(phba, cq, cqe);
14176 		if (!(++ccount % cq->entry_repost))
14177 			break;
14178 	}
14179 
14180 	/* Track the max number of CQEs processed in 1 EQ */
14181 	if (ccount > cq->CQ_max_cqe)
14182 		cq->CQ_max_cqe = ccount;
14183 	cq->assoc_qp->EQ_cqe_cnt += ccount;
14184 
14185 	/* Catch the no cq entry condition */
14186 	if (unlikely(ccount == 0))
14187 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14188 				"0369 No entry from fast-path completion "
14189 				"queue fcpcqid=%d\n", cq->queue_id);
14190 
14191 	/* In any case, flash and re-arm the CQ */
14192 	phba->sli4_hba.sli4_cq_release(cq, LPFC_QUEUE_REARM);
14193 
14194 	/* wake up worker thread if there are works to be done */
14195 	if (workposted)
14196 		lpfc_worker_wake_up(phba);
14197 }
14198 
14199 static void
14200 lpfc_sli4_eq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
14201 {
14202 	struct lpfc_eqe *eqe;
14203 
14204 	/* walk all the EQ entries and drop on the floor */
14205 	while ((eqe = lpfc_sli4_eq_get(eq)))
14206 		;
14207 
14208 	/* Clear and re-arm the EQ */
14209 	phba->sli4_hba.sli4_eq_release(eq, LPFC_QUEUE_REARM);
14210 }
14211 
14212 
14213 /**
14214  * lpfc_sli4_fof_handle_eqe - Process a Flash Optimized Fabric event queue
14215  *			     entry
14216  * @phba: Pointer to HBA context object.
14217  * @eqe: Pointer to fast-path event queue entry.
14218  *
14219  * This routine process a event queue entry from the Flash Optimized Fabric
14220  * event queue.  It will check the MajorCode and MinorCode to determine this
14221  * is for a completion event on a completion queue, if not, an error shall be
14222  * logged and just return. Otherwise, it will get to the corresponding
14223  * completion queue and process all the entries on the completion queue, rearm
14224  * the completion queue, and then return.
14225  **/
14226 static void
14227 lpfc_sli4_fof_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe)
14228 {
14229 	struct lpfc_queue *cq;
14230 	uint16_t cqid;
14231 
14232 	if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
14233 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14234 				"9147 Not a valid completion "
14235 				"event: majorcode=x%x, minorcode=x%x\n",
14236 				bf_get_le32(lpfc_eqe_major_code, eqe),
14237 				bf_get_le32(lpfc_eqe_minor_code, eqe));
14238 		return;
14239 	}
14240 
14241 	/* Get the reference to the corresponding CQ */
14242 	cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14243 
14244 	/* Next check for OAS */
14245 	cq = phba->sli4_hba.oas_cq;
14246 	if (unlikely(!cq)) {
14247 		if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14248 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14249 					"9148 OAS completion queue "
14250 					"does not exist\n");
14251 		return;
14252 	}
14253 
14254 	if (unlikely(cqid != cq->queue_id)) {
14255 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14256 				"9149 Miss-matched fast-path compl "
14257 				"queue id: eqcqid=%d, fcpcqid=%d\n",
14258 				cqid, cq->queue_id);
14259 		return;
14260 	}
14261 
14262 	/* Save EQ associated with this CQ */
14263 	cq->assoc_qp = phba->sli4_hba.fof_eq;
14264 
14265 	/* CQ work will be processed on CPU affinitized to this IRQ */
14266 	if (!queue_work(phba->wq, &cq->irqwork))
14267 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14268 				"0367 Cannot schedule soft IRQ "
14269 				"for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14270 				cqid, cq->queue_id, smp_processor_id());
14271 }
14272 
14273 /**
14274  * lpfc_sli4_fof_intr_handler - HBA interrupt handler to SLI-4 device
14275  * @irq: Interrupt number.
14276  * @dev_id: The device context pointer.
14277  *
14278  * This function is directly called from the PCI layer as an interrupt
14279  * service routine when device with SLI-4 interface spec is enabled with
14280  * MSI-X multi-message interrupt mode and there is a Flash Optimized Fabric
14281  * IOCB ring event in the HBA. However, when the device is enabled with either
14282  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
14283  * device-level interrupt handler. When the PCI slot is in error recovery
14284  * or the HBA is undergoing initialization, the interrupt handler will not
14285  * process the interrupt. The Flash Optimized Fabric ring event are handled in
14286  * the intrrupt context. This function is called without any lock held.
14287  * It gets the hbalock to access and update SLI data structures. Note that,
14288  * the EQ to CQ are one-to-one map such that the EQ index is
14289  * equal to that of CQ index.
14290  *
14291  * This function returns IRQ_HANDLED when interrupt is handled else it
14292  * returns IRQ_NONE.
14293  **/
14294 irqreturn_t
14295 lpfc_sli4_fof_intr_handler(int irq, void *dev_id)
14296 {
14297 	struct lpfc_hba *phba;
14298 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
14299 	struct lpfc_queue *eq;
14300 	struct lpfc_eqe *eqe;
14301 	unsigned long iflag;
14302 	int ecount = 0;
14303 
14304 	/* Get the driver's phba structure from the dev_id */
14305 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
14306 	phba = hba_eq_hdl->phba;
14307 
14308 	if (unlikely(!phba))
14309 		return IRQ_NONE;
14310 
14311 	/* Get to the EQ struct associated with this vector */
14312 	eq = phba->sli4_hba.fof_eq;
14313 	if (unlikely(!eq))
14314 		return IRQ_NONE;
14315 
14316 	/* Check device state for handling interrupt */
14317 	if (unlikely(lpfc_intr_state_check(phba))) {
14318 		/* Check again for link_state with lock held */
14319 		spin_lock_irqsave(&phba->hbalock, iflag);
14320 		if (phba->link_state < LPFC_LINK_DOWN)
14321 			/* Flush, clear interrupt, and rearm the EQ */
14322 			lpfc_sli4_eq_flush(phba, eq);
14323 		spin_unlock_irqrestore(&phba->hbalock, iflag);
14324 		return IRQ_NONE;
14325 	}
14326 
14327 	/*
14328 	 * Process all the event on FCP fast-path EQ
14329 	 */
14330 	while ((eqe = lpfc_sli4_eq_get(eq))) {
14331 		lpfc_sli4_fof_handle_eqe(phba, eqe);
14332 		if (!(++ecount % eq->entry_repost))
14333 			break;
14334 		eq->EQ_processed++;
14335 	}
14336 
14337 	/* Track the max number of EQEs processed in 1 intr */
14338 	if (ecount > eq->EQ_max_eqe)
14339 		eq->EQ_max_eqe = ecount;
14340 
14341 
14342 	if (unlikely(ecount == 0)) {
14343 		eq->EQ_no_entry++;
14344 
14345 		if (phba->intr_type == MSIX)
14346 			/* MSI-X treated interrupt served as no EQ share INT */
14347 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14348 					"9145 MSI-X interrupt with no EQE\n");
14349 		else {
14350 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14351 					"9146 ISR interrupt with no EQE\n");
14352 			/* Non MSI-X treated on interrupt as EQ share INT */
14353 			return IRQ_NONE;
14354 		}
14355 	}
14356 	/* Always clear and re-arm the fast-path EQ */
14357 	phba->sli4_hba.sli4_eq_release(eq, LPFC_QUEUE_REARM);
14358 	return IRQ_HANDLED;
14359 }
14360 
14361 /**
14362  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
14363  * @irq: Interrupt number.
14364  * @dev_id: The device context pointer.
14365  *
14366  * This function is directly called from the PCI layer as an interrupt
14367  * service routine when device with SLI-4 interface spec is enabled with
14368  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
14369  * ring event in the HBA. However, when the device is enabled with either
14370  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
14371  * device-level interrupt handler. When the PCI slot is in error recovery
14372  * or the HBA is undergoing initialization, the interrupt handler will not
14373  * process the interrupt. The SCSI FCP fast-path ring event are handled in
14374  * the intrrupt context. This function is called without any lock held.
14375  * It gets the hbalock to access and update SLI data structures. Note that,
14376  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
14377  * equal to that of FCP CQ index.
14378  *
14379  * The link attention and ELS ring attention events are handled
14380  * by the worker thread. The interrupt handler signals the worker thread
14381  * and returns for these events. This function is called without any lock
14382  * held. It gets the hbalock to access and update SLI data structures.
14383  *
14384  * This function returns IRQ_HANDLED when interrupt is handled else it
14385  * returns IRQ_NONE.
14386  **/
14387 irqreturn_t
14388 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
14389 {
14390 	struct lpfc_hba *phba;
14391 	struct lpfc_hba_eq_hdl *hba_eq_hdl;
14392 	struct lpfc_queue *fpeq;
14393 	struct lpfc_eqe *eqe;
14394 	unsigned long iflag;
14395 	int ecount = 0;
14396 	int hba_eqidx;
14397 
14398 	/* Get the driver's phba structure from the dev_id */
14399 	hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
14400 	phba = hba_eq_hdl->phba;
14401 	hba_eqidx = hba_eq_hdl->idx;
14402 
14403 	if (unlikely(!phba))
14404 		return IRQ_NONE;
14405 	if (unlikely(!phba->sli4_hba.hba_eq))
14406 		return IRQ_NONE;
14407 
14408 	/* Get to the EQ struct associated with this vector */
14409 	fpeq = phba->sli4_hba.hba_eq[hba_eqidx];
14410 	if (unlikely(!fpeq))
14411 		return IRQ_NONE;
14412 
14413 	if (lpfc_fcp_look_ahead) {
14414 		if (atomic_dec_and_test(&hba_eq_hdl->hba_eq_in_use))
14415 			phba->sli4_hba.sli4_eq_clr_intr(fpeq);
14416 		else {
14417 			atomic_inc(&hba_eq_hdl->hba_eq_in_use);
14418 			return IRQ_NONE;
14419 		}
14420 	}
14421 
14422 	/* Check device state for handling interrupt */
14423 	if (unlikely(lpfc_intr_state_check(phba))) {
14424 		/* Check again for link_state with lock held */
14425 		spin_lock_irqsave(&phba->hbalock, iflag);
14426 		if (phba->link_state < LPFC_LINK_DOWN)
14427 			/* Flush, clear interrupt, and rearm the EQ */
14428 			lpfc_sli4_eq_flush(phba, fpeq);
14429 		spin_unlock_irqrestore(&phba->hbalock, iflag);
14430 		if (lpfc_fcp_look_ahead)
14431 			atomic_inc(&hba_eq_hdl->hba_eq_in_use);
14432 		return IRQ_NONE;
14433 	}
14434 
14435 	/*
14436 	 * Process all the event on FCP fast-path EQ
14437 	 */
14438 	while ((eqe = lpfc_sli4_eq_get(fpeq))) {
14439 		lpfc_sli4_hba_handle_eqe(phba, eqe, hba_eqidx);
14440 		if (!(++ecount % fpeq->entry_repost))
14441 			break;
14442 		fpeq->EQ_processed++;
14443 	}
14444 
14445 	/* Track the max number of EQEs processed in 1 intr */
14446 	if (ecount > fpeq->EQ_max_eqe)
14447 		fpeq->EQ_max_eqe = ecount;
14448 
14449 	/* Always clear and re-arm the fast-path EQ */
14450 	phba->sli4_hba.sli4_eq_release(fpeq, LPFC_QUEUE_REARM);
14451 
14452 	if (unlikely(ecount == 0)) {
14453 		fpeq->EQ_no_entry++;
14454 
14455 		if (lpfc_fcp_look_ahead) {
14456 			atomic_inc(&hba_eq_hdl->hba_eq_in_use);
14457 			return IRQ_NONE;
14458 		}
14459 
14460 		if (phba->intr_type == MSIX)
14461 			/* MSI-X treated interrupt served as no EQ share INT */
14462 			lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14463 					"0358 MSI-X interrupt with no EQE\n");
14464 		else
14465 			/* Non MSI-X treated on interrupt as EQ share INT */
14466 			return IRQ_NONE;
14467 	}
14468 
14469 	if (lpfc_fcp_look_ahead)
14470 		atomic_inc(&hba_eq_hdl->hba_eq_in_use);
14471 
14472 	return IRQ_HANDLED;
14473 } /* lpfc_sli4_fp_intr_handler */
14474 
14475 /**
14476  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
14477  * @irq: Interrupt number.
14478  * @dev_id: The device context pointer.
14479  *
14480  * This function is the device-level interrupt handler to device with SLI-4
14481  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
14482  * interrupt mode is enabled and there is an event in the HBA which requires
14483  * driver attention. This function invokes the slow-path interrupt attention
14484  * handling function and fast-path interrupt attention handling function in
14485  * turn to process the relevant HBA attention events. This function is called
14486  * without any lock held. It gets the hbalock to access and update SLI data
14487  * structures.
14488  *
14489  * This function returns IRQ_HANDLED when interrupt is handled, else it
14490  * returns IRQ_NONE.
14491  **/
14492 irqreturn_t
14493 lpfc_sli4_intr_handler(int irq, void *dev_id)
14494 {
14495 	struct lpfc_hba  *phba;
14496 	irqreturn_t hba_irq_rc;
14497 	bool hba_handled = false;
14498 	int qidx;
14499 
14500 	/* Get the driver's phba structure from the dev_id */
14501 	phba = (struct lpfc_hba *)dev_id;
14502 
14503 	if (unlikely(!phba))
14504 		return IRQ_NONE;
14505 
14506 	/*
14507 	 * Invoke fast-path host attention interrupt handling as appropriate.
14508 	 */
14509 	for (qidx = 0; qidx < phba->io_channel_irqs; qidx++) {
14510 		hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
14511 					&phba->sli4_hba.hba_eq_hdl[qidx]);
14512 		if (hba_irq_rc == IRQ_HANDLED)
14513 			hba_handled |= true;
14514 	}
14515 
14516 	if (phba->cfg_fof) {
14517 		hba_irq_rc = lpfc_sli4_fof_intr_handler(irq,
14518 					&phba->sli4_hba.hba_eq_hdl[qidx]);
14519 		if (hba_irq_rc == IRQ_HANDLED)
14520 			hba_handled |= true;
14521 	}
14522 
14523 	return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
14524 } /* lpfc_sli4_intr_handler */
14525 
14526 /**
14527  * lpfc_sli4_queue_free - free a queue structure and associated memory
14528  * @queue: The queue structure to free.
14529  *
14530  * This function frees a queue structure and the DMAable memory used for
14531  * the host resident queue. This function must be called after destroying the
14532  * queue on the HBA.
14533  **/
14534 void
14535 lpfc_sli4_queue_free(struct lpfc_queue *queue)
14536 {
14537 	struct lpfc_dmabuf *dmabuf;
14538 
14539 	if (!queue)
14540 		return;
14541 
14542 	while (!list_empty(&queue->page_list)) {
14543 		list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
14544 				 list);
14545 		dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
14546 				  dmabuf->virt, dmabuf->phys);
14547 		kfree(dmabuf);
14548 	}
14549 	if (queue->rqbp) {
14550 		lpfc_free_rq_buffer(queue->phba, queue);
14551 		kfree(queue->rqbp);
14552 	}
14553 
14554 	if (!list_empty(&queue->wq_list))
14555 		list_del(&queue->wq_list);
14556 
14557 	kfree(queue);
14558 	return;
14559 }
14560 
14561 /**
14562  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
14563  * @phba: The HBA that this queue is being created on.
14564  * @page_size: The size of a queue page
14565  * @entry_size: The size of each queue entry for this queue.
14566  * @entry count: The number of entries that this queue will handle.
14567  *
14568  * This function allocates a queue structure and the DMAable memory used for
14569  * the host resident queue. This function must be called before creating the
14570  * queue on the HBA.
14571  **/
14572 struct lpfc_queue *
14573 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
14574 		      uint32_t entry_size, uint32_t entry_count)
14575 {
14576 	struct lpfc_queue *queue;
14577 	struct lpfc_dmabuf *dmabuf;
14578 	int x, total_qe_count;
14579 	void *dma_pointer;
14580 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
14581 
14582 	if (!phba->sli4_hba.pc_sli4_params.supported)
14583 		hw_page_size = page_size;
14584 
14585 	queue = kzalloc(sizeof(struct lpfc_queue) +
14586 			(sizeof(union sli4_qe) * entry_count), GFP_KERNEL);
14587 	if (!queue)
14588 		return NULL;
14589 	queue->page_count = (ALIGN(entry_size * entry_count,
14590 			hw_page_size))/hw_page_size;
14591 
14592 	/* If needed, Adjust page count to match the max the adapter supports */
14593 	if (phba->sli4_hba.pc_sli4_params.wqpcnt &&
14594 	    (queue->page_count > phba->sli4_hba.pc_sli4_params.wqpcnt))
14595 		queue->page_count = phba->sli4_hba.pc_sli4_params.wqpcnt;
14596 
14597 	INIT_LIST_HEAD(&queue->list);
14598 	INIT_LIST_HEAD(&queue->wq_list);
14599 	INIT_LIST_HEAD(&queue->wqfull_list);
14600 	INIT_LIST_HEAD(&queue->page_list);
14601 	INIT_LIST_HEAD(&queue->child_list);
14602 
14603 	/* Set queue parameters now.  If the system cannot provide memory
14604 	 * resources, the free routine needs to know what was allocated.
14605 	 */
14606 	queue->entry_size = entry_size;
14607 	queue->entry_count = entry_count;
14608 	queue->page_size = hw_page_size;
14609 	queue->phba = phba;
14610 
14611 	for (x = 0, total_qe_count = 0; x < queue->page_count; x++) {
14612 		dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
14613 		if (!dmabuf)
14614 			goto out_fail;
14615 		dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
14616 						  hw_page_size, &dmabuf->phys,
14617 						  GFP_KERNEL);
14618 		if (!dmabuf->virt) {
14619 			kfree(dmabuf);
14620 			goto out_fail;
14621 		}
14622 		dmabuf->buffer_tag = x;
14623 		list_add_tail(&dmabuf->list, &queue->page_list);
14624 		/* initialize queue's entry array */
14625 		dma_pointer = dmabuf->virt;
14626 		for (; total_qe_count < entry_count &&
14627 		     dma_pointer < (hw_page_size + dmabuf->virt);
14628 		     total_qe_count++, dma_pointer += entry_size) {
14629 			queue->qe[total_qe_count].address = dma_pointer;
14630 		}
14631 	}
14632 	INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
14633 	INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
14634 
14635 	/* entry_repost will be set during q creation */
14636 
14637 	return queue;
14638 out_fail:
14639 	lpfc_sli4_queue_free(queue);
14640 	return NULL;
14641 }
14642 
14643 /**
14644  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
14645  * @phba: HBA structure that indicates port to create a queue on.
14646  * @pci_barset: PCI BAR set flag.
14647  *
14648  * This function shall perform iomap of the specified PCI BAR address to host
14649  * memory address if not already done so and return it. The returned host
14650  * memory address can be NULL.
14651  */
14652 static void __iomem *
14653 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
14654 {
14655 	if (!phba->pcidev)
14656 		return NULL;
14657 
14658 	switch (pci_barset) {
14659 	case WQ_PCI_BAR_0_AND_1:
14660 		return phba->pci_bar0_memmap_p;
14661 	case WQ_PCI_BAR_2_AND_3:
14662 		return phba->pci_bar2_memmap_p;
14663 	case WQ_PCI_BAR_4_AND_5:
14664 		return phba->pci_bar4_memmap_p;
14665 	default:
14666 		break;
14667 	}
14668 	return NULL;
14669 }
14670 
14671 /**
14672  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on FCP EQs
14673  * @phba: HBA structure that indicates port to create a queue on.
14674  * @startq: The starting FCP EQ to modify
14675  *
14676  * This function sends an MODIFY_EQ_DELAY mailbox command to the HBA.
14677  * The command allows up to LPFC_MAX_EQ_DELAY_EQID_CNT EQ ID's to be
14678  * updated in one mailbox command.
14679  *
14680  * The @phba struct is used to send mailbox command to HBA. The @startq
14681  * is used to get the starting FCP EQ to change.
14682  * This function is asynchronous and will wait for the mailbox
14683  * command to finish before continuing.
14684  *
14685  * On success this function will return a zero. If unable to allocate enough
14686  * memory this function will return -ENOMEM. If the queue create mailbox command
14687  * fails this function will return -ENXIO.
14688  **/
14689 int
14690 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
14691 			 uint32_t numq, uint32_t imax)
14692 {
14693 	struct lpfc_mbx_modify_eq_delay *eq_delay;
14694 	LPFC_MBOXQ_t *mbox;
14695 	struct lpfc_queue *eq;
14696 	int cnt, rc, length, status = 0;
14697 	uint32_t shdr_status, shdr_add_status;
14698 	uint32_t result, val;
14699 	int qidx;
14700 	union lpfc_sli4_cfg_shdr *shdr;
14701 	uint16_t dmult;
14702 
14703 	if (startq >= phba->io_channel_irqs)
14704 		return 0;
14705 
14706 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14707 	if (!mbox)
14708 		return -ENOMEM;
14709 	length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
14710 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14711 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14712 			 LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
14713 			 length, LPFC_SLI4_MBX_EMBED);
14714 	eq_delay = &mbox->u.mqe.un.eq_delay;
14715 
14716 	/* Calculate delay multiper from maximum interrupt per second */
14717 	result = imax / phba->io_channel_irqs;
14718 	if (result > LPFC_DMULT_CONST || result == 0)
14719 		dmult = 0;
14720 	else
14721 		dmult = LPFC_DMULT_CONST/result - 1;
14722 	if (dmult > LPFC_DMULT_MAX)
14723 		dmult = LPFC_DMULT_MAX;
14724 
14725 	cnt = 0;
14726 	for (qidx = startq; qidx < phba->io_channel_irqs; qidx++) {
14727 		eq = phba->sli4_hba.hba_eq[qidx];
14728 		if (!eq)
14729 			continue;
14730 		eq->q_mode = imax;
14731 		eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
14732 		eq_delay->u.request.eq[cnt].phase = 0;
14733 		eq_delay->u.request.eq[cnt].delay_multi = dmult;
14734 		cnt++;
14735 
14736 		/* q_mode is only used for auto_imax */
14737 		if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
14738 			/* Use EQ Delay Register method for q_mode */
14739 
14740 			/* Convert for EQ Delay register */
14741 			val =  phba->cfg_fcp_imax;
14742 			if (val) {
14743 				/* First, interrupts per sec per EQ */
14744 				val = phba->cfg_fcp_imax /
14745 					phba->io_channel_irqs;
14746 
14747 				/* us delay between each interrupt */
14748 				val = LPFC_SEC_TO_USEC / val;
14749 			}
14750 			eq->q_mode = val;
14751 		} else {
14752 			eq->q_mode = imax;
14753 		}
14754 
14755 		if (cnt >= numq)
14756 			break;
14757 	}
14758 	eq_delay->u.request.num_eq = cnt;
14759 
14760 	mbox->vport = phba->pport;
14761 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14762 	mbox->ctx_buf = NULL;
14763 	mbox->ctx_ndlp = NULL;
14764 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14765 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
14766 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14767 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14768 	if (shdr_status || shdr_add_status || rc) {
14769 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14770 				"2512 MODIFY_EQ_DELAY mailbox failed with "
14771 				"status x%x add_status x%x, mbx status x%x\n",
14772 				shdr_status, shdr_add_status, rc);
14773 		status = -ENXIO;
14774 	}
14775 	mempool_free(mbox, phba->mbox_mem_pool);
14776 	return status;
14777 }
14778 
14779 /**
14780  * lpfc_eq_create - Create an Event Queue on the HBA
14781  * @phba: HBA structure that indicates port to create a queue on.
14782  * @eq: The queue structure to use to create the event queue.
14783  * @imax: The maximum interrupt per second limit.
14784  *
14785  * This function creates an event queue, as detailed in @eq, on a port,
14786  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
14787  *
14788  * The @phba struct is used to send mailbox command to HBA. The @eq struct
14789  * is used to get the entry count and entry size that are necessary to
14790  * determine the number of pages to allocate and use for this queue. This
14791  * function will send the EQ_CREATE mailbox command to the HBA to setup the
14792  * event queue. This function is asynchronous and will wait for the mailbox
14793  * command to finish before continuing.
14794  *
14795  * On success this function will return a zero. If unable to allocate enough
14796  * memory this function will return -ENOMEM. If the queue create mailbox command
14797  * fails this function will return -ENXIO.
14798  **/
14799 int
14800 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
14801 {
14802 	struct lpfc_mbx_eq_create *eq_create;
14803 	LPFC_MBOXQ_t *mbox;
14804 	int rc, length, status = 0;
14805 	struct lpfc_dmabuf *dmabuf;
14806 	uint32_t shdr_status, shdr_add_status;
14807 	union lpfc_sli4_cfg_shdr *shdr;
14808 	uint16_t dmult;
14809 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
14810 
14811 	/* sanity check on queue memory */
14812 	if (!eq)
14813 		return -ENODEV;
14814 	if (!phba->sli4_hba.pc_sli4_params.supported)
14815 		hw_page_size = SLI4_PAGE_SIZE;
14816 
14817 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14818 	if (!mbox)
14819 		return -ENOMEM;
14820 	length = (sizeof(struct lpfc_mbx_eq_create) -
14821 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14822 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14823 			 LPFC_MBOX_OPCODE_EQ_CREATE,
14824 			 length, LPFC_SLI4_MBX_EMBED);
14825 	eq_create = &mbox->u.mqe.un.eq_create;
14826 	shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
14827 	bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
14828 	       eq->page_count);
14829 	bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
14830 	       LPFC_EQE_SIZE);
14831 	bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
14832 
14833 	/* Use version 2 of CREATE_EQ if eqav is set */
14834 	if (phba->sli4_hba.pc_sli4_params.eqav) {
14835 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
14836 		       LPFC_Q_CREATE_VERSION_2);
14837 		bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
14838 		       phba->sli4_hba.pc_sli4_params.eqav);
14839 	}
14840 
14841 	/* don't setup delay multiplier using EQ_CREATE */
14842 	dmult = 0;
14843 	bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
14844 	       dmult);
14845 	switch (eq->entry_count) {
14846 	default:
14847 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14848 				"0360 Unsupported EQ count. (%d)\n",
14849 				eq->entry_count);
14850 		if (eq->entry_count < 256)
14851 			return -EINVAL;
14852 		/* otherwise default to smallest count (drop through) */
14853 	case 256:
14854 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14855 		       LPFC_EQ_CNT_256);
14856 		break;
14857 	case 512:
14858 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14859 		       LPFC_EQ_CNT_512);
14860 		break;
14861 	case 1024:
14862 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14863 		       LPFC_EQ_CNT_1024);
14864 		break;
14865 	case 2048:
14866 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14867 		       LPFC_EQ_CNT_2048);
14868 		break;
14869 	case 4096:
14870 		bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14871 		       LPFC_EQ_CNT_4096);
14872 		break;
14873 	}
14874 	list_for_each_entry(dmabuf, &eq->page_list, list) {
14875 		memset(dmabuf->virt, 0, hw_page_size);
14876 		eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
14877 					putPaddrLow(dmabuf->phys);
14878 		eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
14879 					putPaddrHigh(dmabuf->phys);
14880 	}
14881 	mbox->vport = phba->pport;
14882 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14883 	mbox->ctx_buf = NULL;
14884 	mbox->ctx_ndlp = NULL;
14885 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14886 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14887 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14888 	if (shdr_status || shdr_add_status || rc) {
14889 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14890 				"2500 EQ_CREATE mailbox failed with "
14891 				"status x%x add_status x%x, mbx status x%x\n",
14892 				shdr_status, shdr_add_status, rc);
14893 		status = -ENXIO;
14894 	}
14895 	eq->type = LPFC_EQ;
14896 	eq->subtype = LPFC_NONE;
14897 	eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
14898 	if (eq->queue_id == 0xFFFF)
14899 		status = -ENXIO;
14900 	eq->host_index = 0;
14901 	eq->hba_index = 0;
14902 	eq->entry_repost = LPFC_EQ_REPOST;
14903 
14904 	mempool_free(mbox, phba->mbox_mem_pool);
14905 	return status;
14906 }
14907 
14908 /**
14909  * lpfc_cq_create - Create a Completion Queue on the HBA
14910  * @phba: HBA structure that indicates port to create a queue on.
14911  * @cq: The queue structure to use to create the completion queue.
14912  * @eq: The event queue to bind this completion queue to.
14913  *
14914  * This function creates a completion queue, as detailed in @wq, on a port,
14915  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
14916  *
14917  * The @phba struct is used to send mailbox command to HBA. The @cq struct
14918  * is used to get the entry count and entry size that are necessary to
14919  * determine the number of pages to allocate and use for this queue. The @eq
14920  * is used to indicate which event queue to bind this completion queue to. This
14921  * function will send the CQ_CREATE mailbox command to the HBA to setup the
14922  * completion queue. This function is asynchronous and will wait for the mailbox
14923  * command to finish before continuing.
14924  *
14925  * On success this function will return a zero. If unable to allocate enough
14926  * memory this function will return -ENOMEM. If the queue create mailbox command
14927  * fails this function will return -ENXIO.
14928  **/
14929 int
14930 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
14931 	       struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
14932 {
14933 	struct lpfc_mbx_cq_create *cq_create;
14934 	struct lpfc_dmabuf *dmabuf;
14935 	LPFC_MBOXQ_t *mbox;
14936 	int rc, length, status = 0;
14937 	uint32_t shdr_status, shdr_add_status;
14938 	union lpfc_sli4_cfg_shdr *shdr;
14939 
14940 	/* sanity check on queue memory */
14941 	if (!cq || !eq)
14942 		return -ENODEV;
14943 
14944 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14945 	if (!mbox)
14946 		return -ENOMEM;
14947 	length = (sizeof(struct lpfc_mbx_cq_create) -
14948 		  sizeof(struct lpfc_sli4_cfg_mhdr));
14949 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14950 			 LPFC_MBOX_OPCODE_CQ_CREATE,
14951 			 length, LPFC_SLI4_MBX_EMBED);
14952 	cq_create = &mbox->u.mqe.un.cq_create;
14953 	shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
14954 	bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
14955 		    cq->page_count);
14956 	bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
14957 	bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
14958 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
14959 	       phba->sli4_hba.pc_sli4_params.cqv);
14960 	if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
14961 		bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
14962 		       (cq->page_size / SLI4_PAGE_SIZE));
14963 		bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
14964 		       eq->queue_id);
14965 		bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
14966 		       phba->sli4_hba.pc_sli4_params.cqav);
14967 	} else {
14968 		bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
14969 		       eq->queue_id);
14970 	}
14971 	switch (cq->entry_count) {
14972 	case 2048:
14973 	case 4096:
14974 		if (phba->sli4_hba.pc_sli4_params.cqv ==
14975 		    LPFC_Q_CREATE_VERSION_2) {
14976 			cq_create->u.request.context.lpfc_cq_context_count =
14977 				cq->entry_count;
14978 			bf_set(lpfc_cq_context_count,
14979 			       &cq_create->u.request.context,
14980 			       LPFC_CQ_CNT_WORD7);
14981 			break;
14982 		}
14983 		/* Fall Thru */
14984 	default:
14985 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14986 				"0361 Unsupported CQ count: "
14987 				"entry cnt %d sz %d pg cnt %d\n",
14988 				cq->entry_count, cq->entry_size,
14989 				cq->page_count);
14990 		if (cq->entry_count < 256) {
14991 			status = -EINVAL;
14992 			goto out;
14993 		}
14994 		/* otherwise default to smallest count (drop through) */
14995 	case 256:
14996 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
14997 		       LPFC_CQ_CNT_256);
14998 		break;
14999 	case 512:
15000 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15001 		       LPFC_CQ_CNT_512);
15002 		break;
15003 	case 1024:
15004 		bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15005 		       LPFC_CQ_CNT_1024);
15006 		break;
15007 	}
15008 	list_for_each_entry(dmabuf, &cq->page_list, list) {
15009 		memset(dmabuf->virt, 0, cq->page_size);
15010 		cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15011 					putPaddrLow(dmabuf->phys);
15012 		cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15013 					putPaddrHigh(dmabuf->phys);
15014 	}
15015 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15016 
15017 	/* The IOCTL status is embedded in the mailbox subheader. */
15018 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15019 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15020 	if (shdr_status || shdr_add_status || rc) {
15021 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15022 				"2501 CQ_CREATE mailbox failed with "
15023 				"status x%x add_status x%x, mbx status x%x\n",
15024 				shdr_status, shdr_add_status, rc);
15025 		status = -ENXIO;
15026 		goto out;
15027 	}
15028 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15029 	if (cq->queue_id == 0xFFFF) {
15030 		status = -ENXIO;
15031 		goto out;
15032 	}
15033 	/* link the cq onto the parent eq child list */
15034 	list_add_tail(&cq->list, &eq->child_list);
15035 	/* Set up completion queue's type and subtype */
15036 	cq->type = type;
15037 	cq->subtype = subtype;
15038 	cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15039 	cq->assoc_qid = eq->queue_id;
15040 	cq->host_index = 0;
15041 	cq->hba_index = 0;
15042 	cq->entry_repost = LPFC_CQ_REPOST;
15043 
15044 out:
15045 	mempool_free(mbox, phba->mbox_mem_pool);
15046 	return status;
15047 }
15048 
15049 /**
15050  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
15051  * @phba: HBA structure that indicates port to create a queue on.
15052  * @cqp: The queue structure array to use to create the completion queues.
15053  * @eqp: The event queue array to bind these completion queues to.
15054  *
15055  * This function creates a set of  completion queue, s to support MRQ
15056  * as detailed in @cqp, on a port,
15057  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
15058  *
15059  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15060  * is used to get the entry count and entry size that are necessary to
15061  * determine the number of pages to allocate and use for this queue. The @eq
15062  * is used to indicate which event queue to bind this completion queue to. This
15063  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
15064  * completion queue. This function is asynchronous and will wait for the mailbox
15065  * command to finish before continuing.
15066  *
15067  * On success this function will return a zero. If unable to allocate enough
15068  * memory this function will return -ENOMEM. If the queue create mailbox command
15069  * fails this function will return -ENXIO.
15070  **/
15071 int
15072 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
15073 		   struct lpfc_queue **eqp, uint32_t type, uint32_t subtype)
15074 {
15075 	struct lpfc_queue *cq;
15076 	struct lpfc_queue *eq;
15077 	struct lpfc_mbx_cq_create_set *cq_set;
15078 	struct lpfc_dmabuf *dmabuf;
15079 	LPFC_MBOXQ_t *mbox;
15080 	int rc, length, alloclen, status = 0;
15081 	int cnt, idx, numcq, page_idx = 0;
15082 	uint32_t shdr_status, shdr_add_status;
15083 	union lpfc_sli4_cfg_shdr *shdr;
15084 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15085 
15086 	/* sanity check on queue memory */
15087 	numcq = phba->cfg_nvmet_mrq;
15088 	if (!cqp || !eqp || !numcq)
15089 		return -ENODEV;
15090 
15091 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15092 	if (!mbox)
15093 		return -ENOMEM;
15094 
15095 	length = sizeof(struct lpfc_mbx_cq_create_set);
15096 	length += ((numcq * cqp[0]->page_count) *
15097 		   sizeof(struct dma_address));
15098 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15099 			LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
15100 			LPFC_SLI4_MBX_NEMBED);
15101 	if (alloclen < length) {
15102 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15103 				"3098 Allocated DMA memory size (%d) is "
15104 				"less than the requested DMA memory size "
15105 				"(%d)\n", alloclen, length);
15106 		status = -ENOMEM;
15107 		goto out;
15108 	}
15109 	cq_set = mbox->sge_array->addr[0];
15110 	shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
15111 	bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
15112 
15113 	for (idx = 0; idx < numcq; idx++) {
15114 		cq = cqp[idx];
15115 		eq = eqp[idx];
15116 		if (!cq || !eq) {
15117 			status = -ENOMEM;
15118 			goto out;
15119 		}
15120 		if (!phba->sli4_hba.pc_sli4_params.supported)
15121 			hw_page_size = cq->page_size;
15122 
15123 		switch (idx) {
15124 		case 0:
15125 			bf_set(lpfc_mbx_cq_create_set_page_size,
15126 			       &cq_set->u.request,
15127 			       (hw_page_size / SLI4_PAGE_SIZE));
15128 			bf_set(lpfc_mbx_cq_create_set_num_pages,
15129 			       &cq_set->u.request, cq->page_count);
15130 			bf_set(lpfc_mbx_cq_create_set_evt,
15131 			       &cq_set->u.request, 1);
15132 			bf_set(lpfc_mbx_cq_create_set_valid,
15133 			       &cq_set->u.request, 1);
15134 			bf_set(lpfc_mbx_cq_create_set_cqe_size,
15135 			       &cq_set->u.request, 0);
15136 			bf_set(lpfc_mbx_cq_create_set_num_cq,
15137 			       &cq_set->u.request, numcq);
15138 			bf_set(lpfc_mbx_cq_create_set_autovalid,
15139 			       &cq_set->u.request,
15140 			       phba->sli4_hba.pc_sli4_params.cqav);
15141 			switch (cq->entry_count) {
15142 			case 2048:
15143 			case 4096:
15144 				if (phba->sli4_hba.pc_sli4_params.cqv ==
15145 				    LPFC_Q_CREATE_VERSION_2) {
15146 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15147 					       &cq_set->u.request,
15148 						cq->entry_count);
15149 					bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15150 					       &cq_set->u.request,
15151 					       LPFC_CQ_CNT_WORD7);
15152 					break;
15153 				}
15154 				/* Fall Thru */
15155 			default:
15156 				lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15157 						"3118 Bad CQ count. (%d)\n",
15158 						cq->entry_count);
15159 				if (cq->entry_count < 256) {
15160 					status = -EINVAL;
15161 					goto out;
15162 				}
15163 				/* otherwise default to smallest (drop thru) */
15164 			case 256:
15165 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15166 				       &cq_set->u.request, LPFC_CQ_CNT_256);
15167 				break;
15168 			case 512:
15169 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15170 				       &cq_set->u.request, LPFC_CQ_CNT_512);
15171 				break;
15172 			case 1024:
15173 				bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15174 				       &cq_set->u.request, LPFC_CQ_CNT_1024);
15175 				break;
15176 			}
15177 			bf_set(lpfc_mbx_cq_create_set_eq_id0,
15178 			       &cq_set->u.request, eq->queue_id);
15179 			break;
15180 		case 1:
15181 			bf_set(lpfc_mbx_cq_create_set_eq_id1,
15182 			       &cq_set->u.request, eq->queue_id);
15183 			break;
15184 		case 2:
15185 			bf_set(lpfc_mbx_cq_create_set_eq_id2,
15186 			       &cq_set->u.request, eq->queue_id);
15187 			break;
15188 		case 3:
15189 			bf_set(lpfc_mbx_cq_create_set_eq_id3,
15190 			       &cq_set->u.request, eq->queue_id);
15191 			break;
15192 		case 4:
15193 			bf_set(lpfc_mbx_cq_create_set_eq_id4,
15194 			       &cq_set->u.request, eq->queue_id);
15195 			break;
15196 		case 5:
15197 			bf_set(lpfc_mbx_cq_create_set_eq_id5,
15198 			       &cq_set->u.request, eq->queue_id);
15199 			break;
15200 		case 6:
15201 			bf_set(lpfc_mbx_cq_create_set_eq_id6,
15202 			       &cq_set->u.request, eq->queue_id);
15203 			break;
15204 		case 7:
15205 			bf_set(lpfc_mbx_cq_create_set_eq_id7,
15206 			       &cq_set->u.request, eq->queue_id);
15207 			break;
15208 		case 8:
15209 			bf_set(lpfc_mbx_cq_create_set_eq_id8,
15210 			       &cq_set->u.request, eq->queue_id);
15211 			break;
15212 		case 9:
15213 			bf_set(lpfc_mbx_cq_create_set_eq_id9,
15214 			       &cq_set->u.request, eq->queue_id);
15215 			break;
15216 		case 10:
15217 			bf_set(lpfc_mbx_cq_create_set_eq_id10,
15218 			       &cq_set->u.request, eq->queue_id);
15219 			break;
15220 		case 11:
15221 			bf_set(lpfc_mbx_cq_create_set_eq_id11,
15222 			       &cq_set->u.request, eq->queue_id);
15223 			break;
15224 		case 12:
15225 			bf_set(lpfc_mbx_cq_create_set_eq_id12,
15226 			       &cq_set->u.request, eq->queue_id);
15227 			break;
15228 		case 13:
15229 			bf_set(lpfc_mbx_cq_create_set_eq_id13,
15230 			       &cq_set->u.request, eq->queue_id);
15231 			break;
15232 		case 14:
15233 			bf_set(lpfc_mbx_cq_create_set_eq_id14,
15234 			       &cq_set->u.request, eq->queue_id);
15235 			break;
15236 		case 15:
15237 			bf_set(lpfc_mbx_cq_create_set_eq_id15,
15238 			       &cq_set->u.request, eq->queue_id);
15239 			break;
15240 		}
15241 
15242 		/* link the cq onto the parent eq child list */
15243 		list_add_tail(&cq->list, &eq->child_list);
15244 		/* Set up completion queue's type and subtype */
15245 		cq->type = type;
15246 		cq->subtype = subtype;
15247 		cq->assoc_qid = eq->queue_id;
15248 		cq->host_index = 0;
15249 		cq->hba_index = 0;
15250 		cq->entry_repost = LPFC_CQ_REPOST;
15251 		cq->chann = idx;
15252 
15253 		rc = 0;
15254 		list_for_each_entry(dmabuf, &cq->page_list, list) {
15255 			memset(dmabuf->virt, 0, hw_page_size);
15256 			cnt = page_idx + dmabuf->buffer_tag;
15257 			cq_set->u.request.page[cnt].addr_lo =
15258 					putPaddrLow(dmabuf->phys);
15259 			cq_set->u.request.page[cnt].addr_hi =
15260 					putPaddrHigh(dmabuf->phys);
15261 			rc++;
15262 		}
15263 		page_idx += rc;
15264 	}
15265 
15266 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15267 
15268 	/* The IOCTL status is embedded in the mailbox subheader. */
15269 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15270 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15271 	if (shdr_status || shdr_add_status || rc) {
15272 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15273 				"3119 CQ_CREATE_SET mailbox failed with "
15274 				"status x%x add_status x%x, mbx status x%x\n",
15275 				shdr_status, shdr_add_status, rc);
15276 		status = -ENXIO;
15277 		goto out;
15278 	}
15279 	rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
15280 	if (rc == 0xFFFF) {
15281 		status = -ENXIO;
15282 		goto out;
15283 	}
15284 
15285 	for (idx = 0; idx < numcq; idx++) {
15286 		cq = cqp[idx];
15287 		cq->queue_id = rc + idx;
15288 	}
15289 
15290 out:
15291 	lpfc_sli4_mbox_cmd_free(phba, mbox);
15292 	return status;
15293 }
15294 
15295 /**
15296  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
15297  * @phba: HBA structure that indicates port to create a queue on.
15298  * @mq: The queue structure to use to create the mailbox queue.
15299  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
15300  * @cq: The completion queue to associate with this cq.
15301  *
15302  * This function provides failback (fb) functionality when the
15303  * mq_create_ext fails on older FW generations.  It's purpose is identical
15304  * to mq_create_ext otherwise.
15305  *
15306  * This routine cannot fail as all attributes were previously accessed and
15307  * initialized in mq_create_ext.
15308  **/
15309 static void
15310 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
15311 		       LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
15312 {
15313 	struct lpfc_mbx_mq_create *mq_create;
15314 	struct lpfc_dmabuf *dmabuf;
15315 	int length;
15316 
15317 	length = (sizeof(struct lpfc_mbx_mq_create) -
15318 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15319 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15320 			 LPFC_MBOX_OPCODE_MQ_CREATE,
15321 			 length, LPFC_SLI4_MBX_EMBED);
15322 	mq_create = &mbox->u.mqe.un.mq_create;
15323 	bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
15324 	       mq->page_count);
15325 	bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
15326 	       cq->queue_id);
15327 	bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
15328 	switch (mq->entry_count) {
15329 	case 16:
15330 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15331 		       LPFC_MQ_RING_SIZE_16);
15332 		break;
15333 	case 32:
15334 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15335 		       LPFC_MQ_RING_SIZE_32);
15336 		break;
15337 	case 64:
15338 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15339 		       LPFC_MQ_RING_SIZE_64);
15340 		break;
15341 	case 128:
15342 		bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15343 		       LPFC_MQ_RING_SIZE_128);
15344 		break;
15345 	}
15346 	list_for_each_entry(dmabuf, &mq->page_list, list) {
15347 		mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15348 			putPaddrLow(dmabuf->phys);
15349 		mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15350 			putPaddrHigh(dmabuf->phys);
15351 	}
15352 }
15353 
15354 /**
15355  * lpfc_mq_create - Create a mailbox Queue on the HBA
15356  * @phba: HBA structure that indicates port to create a queue on.
15357  * @mq: The queue structure to use to create the mailbox queue.
15358  * @cq: The completion queue to associate with this cq.
15359  * @subtype: The queue's subtype.
15360  *
15361  * This function creates a mailbox queue, as detailed in @mq, on a port,
15362  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
15363  *
15364  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15365  * is used to get the entry count and entry size that are necessary to
15366  * determine the number of pages to allocate and use for this queue. This
15367  * function will send the MQ_CREATE mailbox command to the HBA to setup the
15368  * mailbox queue. This function is asynchronous and will wait for the mailbox
15369  * command to finish before continuing.
15370  *
15371  * On success this function will return a zero. If unable to allocate enough
15372  * memory this function will return -ENOMEM. If the queue create mailbox command
15373  * fails this function will return -ENXIO.
15374  **/
15375 int32_t
15376 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
15377 	       struct lpfc_queue *cq, uint32_t subtype)
15378 {
15379 	struct lpfc_mbx_mq_create *mq_create;
15380 	struct lpfc_mbx_mq_create_ext *mq_create_ext;
15381 	struct lpfc_dmabuf *dmabuf;
15382 	LPFC_MBOXQ_t *mbox;
15383 	int rc, length, status = 0;
15384 	uint32_t shdr_status, shdr_add_status;
15385 	union lpfc_sli4_cfg_shdr *shdr;
15386 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15387 
15388 	/* sanity check on queue memory */
15389 	if (!mq || !cq)
15390 		return -ENODEV;
15391 	if (!phba->sli4_hba.pc_sli4_params.supported)
15392 		hw_page_size = SLI4_PAGE_SIZE;
15393 
15394 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15395 	if (!mbox)
15396 		return -ENOMEM;
15397 	length = (sizeof(struct lpfc_mbx_mq_create_ext) -
15398 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15399 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15400 			 LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
15401 			 length, LPFC_SLI4_MBX_EMBED);
15402 
15403 	mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
15404 	shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
15405 	bf_set(lpfc_mbx_mq_create_ext_num_pages,
15406 	       &mq_create_ext->u.request, mq->page_count);
15407 	bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
15408 	       &mq_create_ext->u.request, 1);
15409 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
15410 	       &mq_create_ext->u.request, 1);
15411 	bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
15412 	       &mq_create_ext->u.request, 1);
15413 	bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
15414 	       &mq_create_ext->u.request, 1);
15415 	bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
15416 	       &mq_create_ext->u.request, 1);
15417 	bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
15418 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15419 	       phba->sli4_hba.pc_sli4_params.mqv);
15420 	if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
15421 		bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
15422 		       cq->queue_id);
15423 	else
15424 		bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
15425 		       cq->queue_id);
15426 	switch (mq->entry_count) {
15427 	default:
15428 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15429 				"0362 Unsupported MQ count. (%d)\n",
15430 				mq->entry_count);
15431 		if (mq->entry_count < 16) {
15432 			status = -EINVAL;
15433 			goto out;
15434 		}
15435 		/* otherwise default to smallest count (drop through) */
15436 	case 16:
15437 		bf_set(lpfc_mq_context_ring_size,
15438 		       &mq_create_ext->u.request.context,
15439 		       LPFC_MQ_RING_SIZE_16);
15440 		break;
15441 	case 32:
15442 		bf_set(lpfc_mq_context_ring_size,
15443 		       &mq_create_ext->u.request.context,
15444 		       LPFC_MQ_RING_SIZE_32);
15445 		break;
15446 	case 64:
15447 		bf_set(lpfc_mq_context_ring_size,
15448 		       &mq_create_ext->u.request.context,
15449 		       LPFC_MQ_RING_SIZE_64);
15450 		break;
15451 	case 128:
15452 		bf_set(lpfc_mq_context_ring_size,
15453 		       &mq_create_ext->u.request.context,
15454 		       LPFC_MQ_RING_SIZE_128);
15455 		break;
15456 	}
15457 	list_for_each_entry(dmabuf, &mq->page_list, list) {
15458 		memset(dmabuf->virt, 0, hw_page_size);
15459 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
15460 					putPaddrLow(dmabuf->phys);
15461 		mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
15462 					putPaddrHigh(dmabuf->phys);
15463 	}
15464 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15465 	mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
15466 			      &mq_create_ext->u.response);
15467 	if (rc != MBX_SUCCESS) {
15468 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15469 				"2795 MQ_CREATE_EXT failed with "
15470 				"status x%x. Failback to MQ_CREATE.\n",
15471 				rc);
15472 		lpfc_mq_create_fb_init(phba, mq, mbox, cq);
15473 		mq_create = &mbox->u.mqe.un.mq_create;
15474 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15475 		shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
15476 		mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
15477 				      &mq_create->u.response);
15478 	}
15479 
15480 	/* The IOCTL status is embedded in the mailbox subheader. */
15481 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15482 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15483 	if (shdr_status || shdr_add_status || rc) {
15484 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15485 				"2502 MQ_CREATE mailbox failed with "
15486 				"status x%x add_status x%x, mbx status x%x\n",
15487 				shdr_status, shdr_add_status, rc);
15488 		status = -ENXIO;
15489 		goto out;
15490 	}
15491 	if (mq->queue_id == 0xFFFF) {
15492 		status = -ENXIO;
15493 		goto out;
15494 	}
15495 	mq->type = LPFC_MQ;
15496 	mq->assoc_qid = cq->queue_id;
15497 	mq->subtype = subtype;
15498 	mq->host_index = 0;
15499 	mq->hba_index = 0;
15500 	mq->entry_repost = LPFC_MQ_REPOST;
15501 
15502 	/* link the mq onto the parent cq child list */
15503 	list_add_tail(&mq->list, &cq->child_list);
15504 out:
15505 	mempool_free(mbox, phba->mbox_mem_pool);
15506 	return status;
15507 }
15508 
15509 /**
15510  * lpfc_wq_create - Create a Work Queue on the HBA
15511  * @phba: HBA structure that indicates port to create a queue on.
15512  * @wq: The queue structure to use to create the work queue.
15513  * @cq: The completion queue to bind this work queue to.
15514  * @subtype: The subtype of the work queue indicating its functionality.
15515  *
15516  * This function creates a work queue, as detailed in @wq, on a port, described
15517  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
15518  *
15519  * The @phba struct is used to send mailbox command to HBA. The @wq struct
15520  * is used to get the entry count and entry size that are necessary to
15521  * determine the number of pages to allocate and use for this queue. The @cq
15522  * is used to indicate which completion queue to bind this work queue to. This
15523  * function will send the WQ_CREATE mailbox command to the HBA to setup the
15524  * work queue. This function is asynchronous and will wait for the mailbox
15525  * command to finish before continuing.
15526  *
15527  * On success this function will return a zero. If unable to allocate enough
15528  * memory this function will return -ENOMEM. If the queue create mailbox command
15529  * fails this function will return -ENXIO.
15530  **/
15531 int
15532 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
15533 	       struct lpfc_queue *cq, uint32_t subtype)
15534 {
15535 	struct lpfc_mbx_wq_create *wq_create;
15536 	struct lpfc_dmabuf *dmabuf;
15537 	LPFC_MBOXQ_t *mbox;
15538 	int rc, length, status = 0;
15539 	uint32_t shdr_status, shdr_add_status;
15540 	union lpfc_sli4_cfg_shdr *shdr;
15541 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15542 	struct dma_address *page;
15543 	void __iomem *bar_memmap_p;
15544 	uint32_t db_offset;
15545 	uint16_t pci_barset;
15546 	uint8_t dpp_barset;
15547 	uint32_t dpp_offset;
15548 	unsigned long pg_addr;
15549 	uint8_t wq_create_version;
15550 
15551 	/* sanity check on queue memory */
15552 	if (!wq || !cq)
15553 		return -ENODEV;
15554 	if (!phba->sli4_hba.pc_sli4_params.supported)
15555 		hw_page_size = wq->page_size;
15556 
15557 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15558 	if (!mbox)
15559 		return -ENOMEM;
15560 	length = (sizeof(struct lpfc_mbx_wq_create) -
15561 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15562 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15563 			 LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
15564 			 length, LPFC_SLI4_MBX_EMBED);
15565 	wq_create = &mbox->u.mqe.un.wq_create;
15566 	shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
15567 	bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
15568 		    wq->page_count);
15569 	bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
15570 		    cq->queue_id);
15571 
15572 	/* wqv is the earliest version supported, NOT the latest */
15573 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15574 	       phba->sli4_hba.pc_sli4_params.wqv);
15575 
15576 	if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
15577 	    (wq->page_size > SLI4_PAGE_SIZE))
15578 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
15579 	else
15580 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
15581 
15582 
15583 	if (phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT)
15584 		wq_create_version = LPFC_Q_CREATE_VERSION_1;
15585 	else
15586 		wq_create_version = LPFC_Q_CREATE_VERSION_0;
15587 
15588 	switch (wq_create_version) {
15589 	case LPFC_Q_CREATE_VERSION_1:
15590 		bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
15591 		       wq->entry_count);
15592 		bf_set(lpfc_mbox_hdr_version, &shdr->request,
15593 		       LPFC_Q_CREATE_VERSION_1);
15594 
15595 		switch (wq->entry_size) {
15596 		default:
15597 		case 64:
15598 			bf_set(lpfc_mbx_wq_create_wqe_size,
15599 			       &wq_create->u.request_1,
15600 			       LPFC_WQ_WQE_SIZE_64);
15601 			break;
15602 		case 128:
15603 			bf_set(lpfc_mbx_wq_create_wqe_size,
15604 			       &wq_create->u.request_1,
15605 			       LPFC_WQ_WQE_SIZE_128);
15606 			break;
15607 		}
15608 		/* Request DPP by default */
15609 		bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
15610 		bf_set(lpfc_mbx_wq_create_page_size,
15611 		       &wq_create->u.request_1,
15612 		       (wq->page_size / SLI4_PAGE_SIZE));
15613 		page = wq_create->u.request_1.page;
15614 		break;
15615 	default:
15616 		page = wq_create->u.request.page;
15617 		break;
15618 	}
15619 
15620 	list_for_each_entry(dmabuf, &wq->page_list, list) {
15621 		memset(dmabuf->virt, 0, hw_page_size);
15622 		page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
15623 		page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
15624 	}
15625 
15626 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
15627 		bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
15628 
15629 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15630 	/* The IOCTL status is embedded in the mailbox subheader. */
15631 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15632 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15633 	if (shdr_status || shdr_add_status || rc) {
15634 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15635 				"2503 WQ_CREATE mailbox failed with "
15636 				"status x%x add_status x%x, mbx status x%x\n",
15637 				shdr_status, shdr_add_status, rc);
15638 		status = -ENXIO;
15639 		goto out;
15640 	}
15641 
15642 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
15643 		wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
15644 					&wq_create->u.response);
15645 	else
15646 		wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
15647 					&wq_create->u.response_1);
15648 
15649 	if (wq->queue_id == 0xFFFF) {
15650 		status = -ENXIO;
15651 		goto out;
15652 	}
15653 
15654 	wq->db_format = LPFC_DB_LIST_FORMAT;
15655 	if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
15656 		if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
15657 			wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
15658 					       &wq_create->u.response);
15659 			if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
15660 			    (wq->db_format != LPFC_DB_RING_FORMAT)) {
15661 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15662 						"3265 WQ[%d] doorbell format "
15663 						"not supported: x%x\n",
15664 						wq->queue_id, wq->db_format);
15665 				status = -EINVAL;
15666 				goto out;
15667 			}
15668 			pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
15669 					    &wq_create->u.response);
15670 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15671 								   pci_barset);
15672 			if (!bar_memmap_p) {
15673 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15674 						"3263 WQ[%d] failed to memmap "
15675 						"pci barset:x%x\n",
15676 						wq->queue_id, pci_barset);
15677 				status = -ENOMEM;
15678 				goto out;
15679 			}
15680 			db_offset = wq_create->u.response.doorbell_offset;
15681 			if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
15682 			    (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
15683 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15684 						"3252 WQ[%d] doorbell offset "
15685 						"not supported: x%x\n",
15686 						wq->queue_id, db_offset);
15687 				status = -EINVAL;
15688 				goto out;
15689 			}
15690 			wq->db_regaddr = bar_memmap_p + db_offset;
15691 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15692 					"3264 WQ[%d]: barset:x%x, offset:x%x, "
15693 					"format:x%x\n", wq->queue_id,
15694 					pci_barset, db_offset, wq->db_format);
15695 		} else
15696 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
15697 	} else {
15698 		/* Check if DPP was honored by the firmware */
15699 		wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
15700 				    &wq_create->u.response_1);
15701 		if (wq->dpp_enable) {
15702 			pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
15703 					    &wq_create->u.response_1);
15704 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15705 								   pci_barset);
15706 			if (!bar_memmap_p) {
15707 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15708 						"3267 WQ[%d] failed to memmap "
15709 						"pci barset:x%x\n",
15710 						wq->queue_id, pci_barset);
15711 				status = -ENOMEM;
15712 				goto out;
15713 			}
15714 			db_offset = wq_create->u.response_1.doorbell_offset;
15715 			wq->db_regaddr = bar_memmap_p + db_offset;
15716 			wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
15717 					    &wq_create->u.response_1);
15718 			dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
15719 					    &wq_create->u.response_1);
15720 			bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15721 								   dpp_barset);
15722 			if (!bar_memmap_p) {
15723 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15724 						"3268 WQ[%d] failed to memmap "
15725 						"pci barset:x%x\n",
15726 						wq->queue_id, dpp_barset);
15727 				status = -ENOMEM;
15728 				goto out;
15729 			}
15730 			dpp_offset = wq_create->u.response_1.dpp_offset;
15731 			wq->dpp_regaddr = bar_memmap_p + dpp_offset;
15732 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15733 					"3271 WQ[%d]: barset:x%x, offset:x%x, "
15734 					"dpp_id:x%x dpp_barset:x%x "
15735 					"dpp_offset:x%x\n",
15736 					wq->queue_id, pci_barset, db_offset,
15737 					wq->dpp_id, dpp_barset, dpp_offset);
15738 
15739 			/* Enable combined writes for DPP aperture */
15740 			pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
15741 #ifdef CONFIG_X86
15742 			rc = set_memory_wc(pg_addr, 1);
15743 			if (rc) {
15744 				lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15745 					"3272 Cannot setup Combined "
15746 					"Write on WQ[%d] - disable DPP\n",
15747 					wq->queue_id);
15748 				phba->cfg_enable_dpp = 0;
15749 			}
15750 #else
15751 			phba->cfg_enable_dpp = 0;
15752 #endif
15753 		} else
15754 			wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
15755 	}
15756 	wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
15757 	if (wq->pring == NULL) {
15758 		status = -ENOMEM;
15759 		goto out;
15760 	}
15761 	wq->type = LPFC_WQ;
15762 	wq->assoc_qid = cq->queue_id;
15763 	wq->subtype = subtype;
15764 	wq->host_index = 0;
15765 	wq->hba_index = 0;
15766 	wq->entry_repost = LPFC_RELEASE_NOTIFICATION_INTERVAL;
15767 
15768 	/* link the wq onto the parent cq child list */
15769 	list_add_tail(&wq->list, &cq->child_list);
15770 out:
15771 	mempool_free(mbox, phba->mbox_mem_pool);
15772 	return status;
15773 }
15774 
15775 /**
15776  * lpfc_rq_create - Create a Receive Queue on the HBA
15777  * @phba: HBA structure that indicates port to create a queue on.
15778  * @hrq: The queue structure to use to create the header receive queue.
15779  * @drq: The queue structure to use to create the data receive queue.
15780  * @cq: The completion queue to bind this work queue to.
15781  *
15782  * This function creates a receive buffer queue pair , as detailed in @hrq and
15783  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
15784  * to the HBA.
15785  *
15786  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
15787  * struct is used to get the entry count that is necessary to determine the
15788  * number of pages to use for this queue. The @cq is used to indicate which
15789  * completion queue to bind received buffers that are posted to these queues to.
15790  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
15791  * receive queue pair. This function is asynchronous and will wait for the
15792  * mailbox command to finish before continuing.
15793  *
15794  * On success this function will return a zero. If unable to allocate enough
15795  * memory this function will return -ENOMEM. If the queue create mailbox command
15796  * fails this function will return -ENXIO.
15797  **/
15798 int
15799 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
15800 	       struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
15801 {
15802 	struct lpfc_mbx_rq_create *rq_create;
15803 	struct lpfc_dmabuf *dmabuf;
15804 	LPFC_MBOXQ_t *mbox;
15805 	int rc, length, status = 0;
15806 	uint32_t shdr_status, shdr_add_status;
15807 	union lpfc_sli4_cfg_shdr *shdr;
15808 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15809 	void __iomem *bar_memmap_p;
15810 	uint32_t db_offset;
15811 	uint16_t pci_barset;
15812 
15813 	/* sanity check on queue memory */
15814 	if (!hrq || !drq || !cq)
15815 		return -ENODEV;
15816 	if (!phba->sli4_hba.pc_sli4_params.supported)
15817 		hw_page_size = SLI4_PAGE_SIZE;
15818 
15819 	if (hrq->entry_count != drq->entry_count)
15820 		return -EINVAL;
15821 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15822 	if (!mbox)
15823 		return -ENOMEM;
15824 	length = (sizeof(struct lpfc_mbx_rq_create) -
15825 		  sizeof(struct lpfc_sli4_cfg_mhdr));
15826 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15827 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
15828 			 length, LPFC_SLI4_MBX_EMBED);
15829 	rq_create = &mbox->u.mqe.un.rq_create;
15830 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
15831 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15832 	       phba->sli4_hba.pc_sli4_params.rqv);
15833 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
15834 		bf_set(lpfc_rq_context_rqe_count_1,
15835 		       &rq_create->u.request.context,
15836 		       hrq->entry_count);
15837 		rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
15838 		bf_set(lpfc_rq_context_rqe_size,
15839 		       &rq_create->u.request.context,
15840 		       LPFC_RQE_SIZE_8);
15841 		bf_set(lpfc_rq_context_page_size,
15842 		       &rq_create->u.request.context,
15843 		       LPFC_RQ_PAGE_SIZE_4096);
15844 	} else {
15845 		switch (hrq->entry_count) {
15846 		default:
15847 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15848 					"2535 Unsupported RQ count. (%d)\n",
15849 					hrq->entry_count);
15850 			if (hrq->entry_count < 512) {
15851 				status = -EINVAL;
15852 				goto out;
15853 			}
15854 			/* otherwise default to smallest count (drop through) */
15855 		case 512:
15856 			bf_set(lpfc_rq_context_rqe_count,
15857 			       &rq_create->u.request.context,
15858 			       LPFC_RQ_RING_SIZE_512);
15859 			break;
15860 		case 1024:
15861 			bf_set(lpfc_rq_context_rqe_count,
15862 			       &rq_create->u.request.context,
15863 			       LPFC_RQ_RING_SIZE_1024);
15864 			break;
15865 		case 2048:
15866 			bf_set(lpfc_rq_context_rqe_count,
15867 			       &rq_create->u.request.context,
15868 			       LPFC_RQ_RING_SIZE_2048);
15869 			break;
15870 		case 4096:
15871 			bf_set(lpfc_rq_context_rqe_count,
15872 			       &rq_create->u.request.context,
15873 			       LPFC_RQ_RING_SIZE_4096);
15874 			break;
15875 		}
15876 		bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
15877 		       LPFC_HDR_BUF_SIZE);
15878 	}
15879 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
15880 	       cq->queue_id);
15881 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
15882 	       hrq->page_count);
15883 	list_for_each_entry(dmabuf, &hrq->page_list, list) {
15884 		memset(dmabuf->virt, 0, hw_page_size);
15885 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15886 					putPaddrLow(dmabuf->phys);
15887 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15888 					putPaddrHigh(dmabuf->phys);
15889 	}
15890 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
15891 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
15892 
15893 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15894 	/* The IOCTL status is embedded in the mailbox subheader. */
15895 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15896 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15897 	if (shdr_status || shdr_add_status || rc) {
15898 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15899 				"2504 RQ_CREATE mailbox failed with "
15900 				"status x%x add_status x%x, mbx status x%x\n",
15901 				shdr_status, shdr_add_status, rc);
15902 		status = -ENXIO;
15903 		goto out;
15904 	}
15905 	hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
15906 	if (hrq->queue_id == 0xFFFF) {
15907 		status = -ENXIO;
15908 		goto out;
15909 	}
15910 
15911 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
15912 		hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
15913 					&rq_create->u.response);
15914 		if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
15915 		    (hrq->db_format != LPFC_DB_RING_FORMAT)) {
15916 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15917 					"3262 RQ [%d] doorbell format not "
15918 					"supported: x%x\n", hrq->queue_id,
15919 					hrq->db_format);
15920 			status = -EINVAL;
15921 			goto out;
15922 		}
15923 
15924 		pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
15925 				    &rq_create->u.response);
15926 		bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
15927 		if (!bar_memmap_p) {
15928 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15929 					"3269 RQ[%d] failed to memmap pci "
15930 					"barset:x%x\n", hrq->queue_id,
15931 					pci_barset);
15932 			status = -ENOMEM;
15933 			goto out;
15934 		}
15935 
15936 		db_offset = rq_create->u.response.doorbell_offset;
15937 		if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
15938 		    (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
15939 			lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15940 					"3270 RQ[%d] doorbell offset not "
15941 					"supported: x%x\n", hrq->queue_id,
15942 					db_offset);
15943 			status = -EINVAL;
15944 			goto out;
15945 		}
15946 		hrq->db_regaddr = bar_memmap_p + db_offset;
15947 		lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15948 				"3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
15949 				"format:x%x\n", hrq->queue_id, pci_barset,
15950 				db_offset, hrq->db_format);
15951 	} else {
15952 		hrq->db_format = LPFC_DB_RING_FORMAT;
15953 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
15954 	}
15955 	hrq->type = LPFC_HRQ;
15956 	hrq->assoc_qid = cq->queue_id;
15957 	hrq->subtype = subtype;
15958 	hrq->host_index = 0;
15959 	hrq->hba_index = 0;
15960 	hrq->entry_repost = LPFC_RQ_REPOST;
15961 
15962 	/* now create the data queue */
15963 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15964 			 LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
15965 			 length, LPFC_SLI4_MBX_EMBED);
15966 	bf_set(lpfc_mbox_hdr_version, &shdr->request,
15967 	       phba->sli4_hba.pc_sli4_params.rqv);
15968 	if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
15969 		bf_set(lpfc_rq_context_rqe_count_1,
15970 		       &rq_create->u.request.context, hrq->entry_count);
15971 		if (subtype == LPFC_NVMET)
15972 			rq_create->u.request.context.buffer_size =
15973 				LPFC_NVMET_DATA_BUF_SIZE;
15974 		else
15975 			rq_create->u.request.context.buffer_size =
15976 				LPFC_DATA_BUF_SIZE;
15977 		bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
15978 		       LPFC_RQE_SIZE_8);
15979 		bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
15980 		       (PAGE_SIZE/SLI4_PAGE_SIZE));
15981 	} else {
15982 		switch (drq->entry_count) {
15983 		default:
15984 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15985 					"2536 Unsupported RQ count. (%d)\n",
15986 					drq->entry_count);
15987 			if (drq->entry_count < 512) {
15988 				status = -EINVAL;
15989 				goto out;
15990 			}
15991 			/* otherwise default to smallest count (drop through) */
15992 		case 512:
15993 			bf_set(lpfc_rq_context_rqe_count,
15994 			       &rq_create->u.request.context,
15995 			       LPFC_RQ_RING_SIZE_512);
15996 			break;
15997 		case 1024:
15998 			bf_set(lpfc_rq_context_rqe_count,
15999 			       &rq_create->u.request.context,
16000 			       LPFC_RQ_RING_SIZE_1024);
16001 			break;
16002 		case 2048:
16003 			bf_set(lpfc_rq_context_rqe_count,
16004 			       &rq_create->u.request.context,
16005 			       LPFC_RQ_RING_SIZE_2048);
16006 			break;
16007 		case 4096:
16008 			bf_set(lpfc_rq_context_rqe_count,
16009 			       &rq_create->u.request.context,
16010 			       LPFC_RQ_RING_SIZE_4096);
16011 			break;
16012 		}
16013 		if (subtype == LPFC_NVMET)
16014 			bf_set(lpfc_rq_context_buf_size,
16015 			       &rq_create->u.request.context,
16016 			       LPFC_NVMET_DATA_BUF_SIZE);
16017 		else
16018 			bf_set(lpfc_rq_context_buf_size,
16019 			       &rq_create->u.request.context,
16020 			       LPFC_DATA_BUF_SIZE);
16021 	}
16022 	bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
16023 	       cq->queue_id);
16024 	bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
16025 	       drq->page_count);
16026 	list_for_each_entry(dmabuf, &drq->page_list, list) {
16027 		rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16028 					putPaddrLow(dmabuf->phys);
16029 		rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16030 					putPaddrHigh(dmabuf->phys);
16031 	}
16032 	if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16033 		bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
16034 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16035 	/* The IOCTL status is embedded in the mailbox subheader. */
16036 	shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
16037 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16038 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16039 	if (shdr_status || shdr_add_status || rc) {
16040 		status = -ENXIO;
16041 		goto out;
16042 	}
16043 	drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16044 	if (drq->queue_id == 0xFFFF) {
16045 		status = -ENXIO;
16046 		goto out;
16047 	}
16048 	drq->type = LPFC_DRQ;
16049 	drq->assoc_qid = cq->queue_id;
16050 	drq->subtype = subtype;
16051 	drq->host_index = 0;
16052 	drq->hba_index = 0;
16053 	drq->entry_repost = LPFC_RQ_REPOST;
16054 
16055 	/* link the header and data RQs onto the parent cq child list */
16056 	list_add_tail(&hrq->list, &cq->child_list);
16057 	list_add_tail(&drq->list, &cq->child_list);
16058 
16059 out:
16060 	mempool_free(mbox, phba->mbox_mem_pool);
16061 	return status;
16062 }
16063 
16064 /**
16065  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
16066  * @phba: HBA structure that indicates port to create a queue on.
16067  * @hrqp: The queue structure array to use to create the header receive queues.
16068  * @drqp: The queue structure array to use to create the data receive queues.
16069  * @cqp: The completion queue array to bind these receive queues to.
16070  *
16071  * This function creates a receive buffer queue pair , as detailed in @hrq and
16072  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
16073  * to the HBA.
16074  *
16075  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
16076  * struct is used to get the entry count that is necessary to determine the
16077  * number of pages to use for this queue. The @cq is used to indicate which
16078  * completion queue to bind received buffers that are posted to these queues to.
16079  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
16080  * receive queue pair. This function is asynchronous and will wait for the
16081  * mailbox command to finish before continuing.
16082  *
16083  * On success this function will return a zero. If unable to allocate enough
16084  * memory this function will return -ENOMEM. If the queue create mailbox command
16085  * fails this function will return -ENXIO.
16086  **/
16087 int
16088 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
16089 		struct lpfc_queue **drqp, struct lpfc_queue **cqp,
16090 		uint32_t subtype)
16091 {
16092 	struct lpfc_queue *hrq, *drq, *cq;
16093 	struct lpfc_mbx_rq_create_v2 *rq_create;
16094 	struct lpfc_dmabuf *dmabuf;
16095 	LPFC_MBOXQ_t *mbox;
16096 	int rc, length, alloclen, status = 0;
16097 	int cnt, idx, numrq, page_idx = 0;
16098 	uint32_t shdr_status, shdr_add_status;
16099 	union lpfc_sli4_cfg_shdr *shdr;
16100 	uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16101 
16102 	numrq = phba->cfg_nvmet_mrq;
16103 	/* sanity check on array memory */
16104 	if (!hrqp || !drqp || !cqp || !numrq)
16105 		return -ENODEV;
16106 	if (!phba->sli4_hba.pc_sli4_params.supported)
16107 		hw_page_size = SLI4_PAGE_SIZE;
16108 
16109 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16110 	if (!mbox)
16111 		return -ENOMEM;
16112 
16113 	length = sizeof(struct lpfc_mbx_rq_create_v2);
16114 	length += ((2 * numrq * hrqp[0]->page_count) *
16115 		   sizeof(struct dma_address));
16116 
16117 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16118 				    LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
16119 				    LPFC_SLI4_MBX_NEMBED);
16120 	if (alloclen < length) {
16121 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16122 				"3099 Allocated DMA memory size (%d) is "
16123 				"less than the requested DMA memory size "
16124 				"(%d)\n", alloclen, length);
16125 		status = -ENOMEM;
16126 		goto out;
16127 	}
16128 
16129 
16130 
16131 	rq_create = mbox->sge_array->addr[0];
16132 	shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
16133 
16134 	bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
16135 	cnt = 0;
16136 
16137 	for (idx = 0; idx < numrq; idx++) {
16138 		hrq = hrqp[idx];
16139 		drq = drqp[idx];
16140 		cq  = cqp[idx];
16141 
16142 		/* sanity check on queue memory */
16143 		if (!hrq || !drq || !cq) {
16144 			status = -ENODEV;
16145 			goto out;
16146 		}
16147 
16148 		if (hrq->entry_count != drq->entry_count) {
16149 			status = -EINVAL;
16150 			goto out;
16151 		}
16152 
16153 		if (idx == 0) {
16154 			bf_set(lpfc_mbx_rq_create_num_pages,
16155 			       &rq_create->u.request,
16156 			       hrq->page_count);
16157 			bf_set(lpfc_mbx_rq_create_rq_cnt,
16158 			       &rq_create->u.request, (numrq * 2));
16159 			bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
16160 			       1);
16161 			bf_set(lpfc_rq_context_base_cq,
16162 			       &rq_create->u.request.context,
16163 			       cq->queue_id);
16164 			bf_set(lpfc_rq_context_data_size,
16165 			       &rq_create->u.request.context,
16166 			       LPFC_NVMET_DATA_BUF_SIZE);
16167 			bf_set(lpfc_rq_context_hdr_size,
16168 			       &rq_create->u.request.context,
16169 			       LPFC_HDR_BUF_SIZE);
16170 			bf_set(lpfc_rq_context_rqe_count_1,
16171 			       &rq_create->u.request.context,
16172 			       hrq->entry_count);
16173 			bf_set(lpfc_rq_context_rqe_size,
16174 			       &rq_create->u.request.context,
16175 			       LPFC_RQE_SIZE_8);
16176 			bf_set(lpfc_rq_context_page_size,
16177 			       &rq_create->u.request.context,
16178 			       (PAGE_SIZE/SLI4_PAGE_SIZE));
16179 		}
16180 		rc = 0;
16181 		list_for_each_entry(dmabuf, &hrq->page_list, list) {
16182 			memset(dmabuf->virt, 0, hw_page_size);
16183 			cnt = page_idx + dmabuf->buffer_tag;
16184 			rq_create->u.request.page[cnt].addr_lo =
16185 					putPaddrLow(dmabuf->phys);
16186 			rq_create->u.request.page[cnt].addr_hi =
16187 					putPaddrHigh(dmabuf->phys);
16188 			rc++;
16189 		}
16190 		page_idx += rc;
16191 
16192 		rc = 0;
16193 		list_for_each_entry(dmabuf, &drq->page_list, list) {
16194 			memset(dmabuf->virt, 0, hw_page_size);
16195 			cnt = page_idx + dmabuf->buffer_tag;
16196 			rq_create->u.request.page[cnt].addr_lo =
16197 					putPaddrLow(dmabuf->phys);
16198 			rq_create->u.request.page[cnt].addr_hi =
16199 					putPaddrHigh(dmabuf->phys);
16200 			rc++;
16201 		}
16202 		page_idx += rc;
16203 
16204 		hrq->db_format = LPFC_DB_RING_FORMAT;
16205 		hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16206 		hrq->type = LPFC_HRQ;
16207 		hrq->assoc_qid = cq->queue_id;
16208 		hrq->subtype = subtype;
16209 		hrq->host_index = 0;
16210 		hrq->hba_index = 0;
16211 		hrq->entry_repost = LPFC_RQ_REPOST;
16212 
16213 		drq->db_format = LPFC_DB_RING_FORMAT;
16214 		drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16215 		drq->type = LPFC_DRQ;
16216 		drq->assoc_qid = cq->queue_id;
16217 		drq->subtype = subtype;
16218 		drq->host_index = 0;
16219 		drq->hba_index = 0;
16220 		drq->entry_repost = LPFC_RQ_REPOST;
16221 
16222 		list_add_tail(&hrq->list, &cq->child_list);
16223 		list_add_tail(&drq->list, &cq->child_list);
16224 	}
16225 
16226 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16227 	/* The IOCTL status is embedded in the mailbox subheader. */
16228 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16229 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16230 	if (shdr_status || shdr_add_status || rc) {
16231 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16232 				"3120 RQ_CREATE mailbox failed with "
16233 				"status x%x add_status x%x, mbx status x%x\n",
16234 				shdr_status, shdr_add_status, rc);
16235 		status = -ENXIO;
16236 		goto out;
16237 	}
16238 	rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16239 	if (rc == 0xFFFF) {
16240 		status = -ENXIO;
16241 		goto out;
16242 	}
16243 
16244 	/* Initialize all RQs with associated queue id */
16245 	for (idx = 0; idx < numrq; idx++) {
16246 		hrq = hrqp[idx];
16247 		hrq->queue_id = rc + (2 * idx);
16248 		drq = drqp[idx];
16249 		drq->queue_id = rc + (2 * idx) + 1;
16250 	}
16251 
16252 out:
16253 	lpfc_sli4_mbox_cmd_free(phba, mbox);
16254 	return status;
16255 }
16256 
16257 /**
16258  * lpfc_eq_destroy - Destroy an event Queue on the HBA
16259  * @eq: The queue structure associated with the queue to destroy.
16260  *
16261  * This function destroys a queue, as detailed in @eq by sending an mailbox
16262  * command, specific to the type of queue, to the HBA.
16263  *
16264  * The @eq struct is used to get the queue ID of the queue to destroy.
16265  *
16266  * On success this function will return a zero. If the queue destroy mailbox
16267  * command fails this function will return -ENXIO.
16268  **/
16269 int
16270 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
16271 {
16272 	LPFC_MBOXQ_t *mbox;
16273 	int rc, length, status = 0;
16274 	uint32_t shdr_status, shdr_add_status;
16275 	union lpfc_sli4_cfg_shdr *shdr;
16276 
16277 	/* sanity check on queue memory */
16278 	if (!eq)
16279 		return -ENODEV;
16280 	mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
16281 	if (!mbox)
16282 		return -ENOMEM;
16283 	length = (sizeof(struct lpfc_mbx_eq_destroy) -
16284 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16285 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16286 			 LPFC_MBOX_OPCODE_EQ_DESTROY,
16287 			 length, LPFC_SLI4_MBX_EMBED);
16288 	bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
16289 	       eq->queue_id);
16290 	mbox->vport = eq->phba->pport;
16291 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16292 
16293 	rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
16294 	/* The IOCTL status is embedded in the mailbox subheader. */
16295 	shdr = (union lpfc_sli4_cfg_shdr *)
16296 		&mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
16297 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16298 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16299 	if (shdr_status || shdr_add_status || rc) {
16300 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16301 				"2505 EQ_DESTROY mailbox failed with "
16302 				"status x%x add_status x%x, mbx status x%x\n",
16303 				shdr_status, shdr_add_status, rc);
16304 		status = -ENXIO;
16305 	}
16306 
16307 	/* Remove eq from any list */
16308 	list_del_init(&eq->list);
16309 	mempool_free(mbox, eq->phba->mbox_mem_pool);
16310 	return status;
16311 }
16312 
16313 /**
16314  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
16315  * @cq: The queue structure associated with the queue to destroy.
16316  *
16317  * This function destroys a queue, as detailed in @cq by sending an mailbox
16318  * command, specific to the type of queue, to the HBA.
16319  *
16320  * The @cq struct is used to get the queue ID of the queue to destroy.
16321  *
16322  * On success this function will return a zero. If the queue destroy mailbox
16323  * command fails this function will return -ENXIO.
16324  **/
16325 int
16326 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
16327 {
16328 	LPFC_MBOXQ_t *mbox;
16329 	int rc, length, status = 0;
16330 	uint32_t shdr_status, shdr_add_status;
16331 	union lpfc_sli4_cfg_shdr *shdr;
16332 
16333 	/* sanity check on queue memory */
16334 	if (!cq)
16335 		return -ENODEV;
16336 	mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
16337 	if (!mbox)
16338 		return -ENOMEM;
16339 	length = (sizeof(struct lpfc_mbx_cq_destroy) -
16340 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16341 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16342 			 LPFC_MBOX_OPCODE_CQ_DESTROY,
16343 			 length, LPFC_SLI4_MBX_EMBED);
16344 	bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
16345 	       cq->queue_id);
16346 	mbox->vport = cq->phba->pport;
16347 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16348 	rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
16349 	/* The IOCTL status is embedded in the mailbox subheader. */
16350 	shdr = (union lpfc_sli4_cfg_shdr *)
16351 		&mbox->u.mqe.un.wq_create.header.cfg_shdr;
16352 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16353 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16354 	if (shdr_status || shdr_add_status || rc) {
16355 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16356 				"2506 CQ_DESTROY mailbox failed with "
16357 				"status x%x add_status x%x, mbx status x%x\n",
16358 				shdr_status, shdr_add_status, rc);
16359 		status = -ENXIO;
16360 	}
16361 	/* Remove cq from any list */
16362 	list_del_init(&cq->list);
16363 	mempool_free(mbox, cq->phba->mbox_mem_pool);
16364 	return status;
16365 }
16366 
16367 /**
16368  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
16369  * @qm: The queue structure associated with the queue to destroy.
16370  *
16371  * This function destroys a queue, as detailed in @mq by sending an mailbox
16372  * command, specific to the type of queue, to the HBA.
16373  *
16374  * The @mq struct is used to get the queue ID of the queue to destroy.
16375  *
16376  * On success this function will return a zero. If the queue destroy mailbox
16377  * command fails this function will return -ENXIO.
16378  **/
16379 int
16380 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
16381 {
16382 	LPFC_MBOXQ_t *mbox;
16383 	int rc, length, status = 0;
16384 	uint32_t shdr_status, shdr_add_status;
16385 	union lpfc_sli4_cfg_shdr *shdr;
16386 
16387 	/* sanity check on queue memory */
16388 	if (!mq)
16389 		return -ENODEV;
16390 	mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
16391 	if (!mbox)
16392 		return -ENOMEM;
16393 	length = (sizeof(struct lpfc_mbx_mq_destroy) -
16394 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16395 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16396 			 LPFC_MBOX_OPCODE_MQ_DESTROY,
16397 			 length, LPFC_SLI4_MBX_EMBED);
16398 	bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
16399 	       mq->queue_id);
16400 	mbox->vport = mq->phba->pport;
16401 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16402 	rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
16403 	/* The IOCTL status is embedded in the mailbox subheader. */
16404 	shdr = (union lpfc_sli4_cfg_shdr *)
16405 		&mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
16406 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16407 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16408 	if (shdr_status || shdr_add_status || rc) {
16409 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16410 				"2507 MQ_DESTROY mailbox failed with "
16411 				"status x%x add_status x%x, mbx status x%x\n",
16412 				shdr_status, shdr_add_status, rc);
16413 		status = -ENXIO;
16414 	}
16415 	/* Remove mq from any list */
16416 	list_del_init(&mq->list);
16417 	mempool_free(mbox, mq->phba->mbox_mem_pool);
16418 	return status;
16419 }
16420 
16421 /**
16422  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
16423  * @wq: The queue structure associated with the queue to destroy.
16424  *
16425  * This function destroys a queue, as detailed in @wq by sending an mailbox
16426  * command, specific to the type of queue, to the HBA.
16427  *
16428  * The @wq struct is used to get the queue ID of the queue to destroy.
16429  *
16430  * On success this function will return a zero. If the queue destroy mailbox
16431  * command fails this function will return -ENXIO.
16432  **/
16433 int
16434 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
16435 {
16436 	LPFC_MBOXQ_t *mbox;
16437 	int rc, length, status = 0;
16438 	uint32_t shdr_status, shdr_add_status;
16439 	union lpfc_sli4_cfg_shdr *shdr;
16440 
16441 	/* sanity check on queue memory */
16442 	if (!wq)
16443 		return -ENODEV;
16444 	mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
16445 	if (!mbox)
16446 		return -ENOMEM;
16447 	length = (sizeof(struct lpfc_mbx_wq_destroy) -
16448 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16449 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16450 			 LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
16451 			 length, LPFC_SLI4_MBX_EMBED);
16452 	bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
16453 	       wq->queue_id);
16454 	mbox->vport = wq->phba->pport;
16455 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16456 	rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
16457 	shdr = (union lpfc_sli4_cfg_shdr *)
16458 		&mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
16459 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16460 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16461 	if (shdr_status || shdr_add_status || rc) {
16462 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16463 				"2508 WQ_DESTROY mailbox failed with "
16464 				"status x%x add_status x%x, mbx status x%x\n",
16465 				shdr_status, shdr_add_status, rc);
16466 		status = -ENXIO;
16467 	}
16468 	/* Remove wq from any list */
16469 	list_del_init(&wq->list);
16470 	kfree(wq->pring);
16471 	wq->pring = NULL;
16472 	mempool_free(mbox, wq->phba->mbox_mem_pool);
16473 	return status;
16474 }
16475 
16476 /**
16477  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
16478  * @rq: The queue structure associated with the queue to destroy.
16479  *
16480  * This function destroys a queue, as detailed in @rq by sending an mailbox
16481  * command, specific to the type of queue, to the HBA.
16482  *
16483  * The @rq struct is used to get the queue ID of the queue to destroy.
16484  *
16485  * On success this function will return a zero. If the queue destroy mailbox
16486  * command fails this function will return -ENXIO.
16487  **/
16488 int
16489 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
16490 		struct lpfc_queue *drq)
16491 {
16492 	LPFC_MBOXQ_t *mbox;
16493 	int rc, length, status = 0;
16494 	uint32_t shdr_status, shdr_add_status;
16495 	union lpfc_sli4_cfg_shdr *shdr;
16496 
16497 	/* sanity check on queue memory */
16498 	if (!hrq || !drq)
16499 		return -ENODEV;
16500 	mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
16501 	if (!mbox)
16502 		return -ENOMEM;
16503 	length = (sizeof(struct lpfc_mbx_rq_destroy) -
16504 		  sizeof(struct lpfc_sli4_cfg_mhdr));
16505 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16506 			 LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
16507 			 length, LPFC_SLI4_MBX_EMBED);
16508 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
16509 	       hrq->queue_id);
16510 	mbox->vport = hrq->phba->pport;
16511 	mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16512 	rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
16513 	/* The IOCTL status is embedded in the mailbox subheader. */
16514 	shdr = (union lpfc_sli4_cfg_shdr *)
16515 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
16516 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16517 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16518 	if (shdr_status || shdr_add_status || rc) {
16519 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16520 				"2509 RQ_DESTROY mailbox failed with "
16521 				"status x%x add_status x%x, mbx status x%x\n",
16522 				shdr_status, shdr_add_status, rc);
16523 		if (rc != MBX_TIMEOUT)
16524 			mempool_free(mbox, hrq->phba->mbox_mem_pool);
16525 		return -ENXIO;
16526 	}
16527 	bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
16528 	       drq->queue_id);
16529 	rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
16530 	shdr = (union lpfc_sli4_cfg_shdr *)
16531 		&mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
16532 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16533 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16534 	if (shdr_status || shdr_add_status || rc) {
16535 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16536 				"2510 RQ_DESTROY mailbox failed with "
16537 				"status x%x add_status x%x, mbx status x%x\n",
16538 				shdr_status, shdr_add_status, rc);
16539 		status = -ENXIO;
16540 	}
16541 	list_del_init(&hrq->list);
16542 	list_del_init(&drq->list);
16543 	mempool_free(mbox, hrq->phba->mbox_mem_pool);
16544 	return status;
16545 }
16546 
16547 /**
16548  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
16549  * @phba: The virtual port for which this call being executed.
16550  * @pdma_phys_addr0: Physical address of the 1st SGL page.
16551  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
16552  * @xritag: the xritag that ties this io to the SGL pages.
16553  *
16554  * This routine will post the sgl pages for the IO that has the xritag
16555  * that is in the iocbq structure. The xritag is assigned during iocbq
16556  * creation and persists for as long as the driver is loaded.
16557  * if the caller has fewer than 256 scatter gather segments to map then
16558  * pdma_phys_addr1 should be 0.
16559  * If the caller needs to map more than 256 scatter gather segment then
16560  * pdma_phys_addr1 should be a valid physical address.
16561  * physical address for SGLs must be 64 byte aligned.
16562  * If you are going to map 2 SGL's then the first one must have 256 entries
16563  * the second sgl can have between 1 and 256 entries.
16564  *
16565  * Return codes:
16566  * 	0 - Success
16567  * 	-ENXIO, -ENOMEM - Failure
16568  **/
16569 int
16570 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
16571 		dma_addr_t pdma_phys_addr0,
16572 		dma_addr_t pdma_phys_addr1,
16573 		uint16_t xritag)
16574 {
16575 	struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
16576 	LPFC_MBOXQ_t *mbox;
16577 	int rc;
16578 	uint32_t shdr_status, shdr_add_status;
16579 	uint32_t mbox_tmo;
16580 	union lpfc_sli4_cfg_shdr *shdr;
16581 
16582 	if (xritag == NO_XRI) {
16583 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16584 				"0364 Invalid param:\n");
16585 		return -EINVAL;
16586 	}
16587 
16588 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16589 	if (!mbox)
16590 		return -ENOMEM;
16591 
16592 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16593 			LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
16594 			sizeof(struct lpfc_mbx_post_sgl_pages) -
16595 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
16596 
16597 	post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
16598 				&mbox->u.mqe.un.post_sgl_pages;
16599 	bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
16600 	bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
16601 
16602 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo	=
16603 				cpu_to_le32(putPaddrLow(pdma_phys_addr0));
16604 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
16605 				cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
16606 
16607 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo	=
16608 				cpu_to_le32(putPaddrLow(pdma_phys_addr1));
16609 	post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
16610 				cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
16611 	if (!phba->sli4_hba.intr_enable)
16612 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16613 	else {
16614 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
16615 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
16616 	}
16617 	/* The IOCTL status is embedded in the mailbox subheader. */
16618 	shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
16619 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16620 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16621 	if (rc != MBX_TIMEOUT)
16622 		mempool_free(mbox, phba->mbox_mem_pool);
16623 	if (shdr_status || shdr_add_status || rc) {
16624 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16625 				"2511 POST_SGL mailbox failed with "
16626 				"status x%x add_status x%x, mbx status x%x\n",
16627 				shdr_status, shdr_add_status, rc);
16628 	}
16629 	return 0;
16630 }
16631 
16632 /**
16633  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
16634  * @phba: pointer to lpfc hba data structure.
16635  *
16636  * This routine is invoked to post rpi header templates to the
16637  * HBA consistent with the SLI-4 interface spec.  This routine
16638  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
16639  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
16640  *
16641  * Returns
16642  *	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
16643  *	LPFC_RPI_ALLOC_ERROR if no rpis are available.
16644  **/
16645 static uint16_t
16646 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
16647 {
16648 	unsigned long xri;
16649 
16650 	/*
16651 	 * Fetch the next logical xri.  Because this index is logical,
16652 	 * the driver starts at 0 each time.
16653 	 */
16654 	spin_lock_irq(&phba->hbalock);
16655 	xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
16656 				 phba->sli4_hba.max_cfg_param.max_xri, 0);
16657 	if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
16658 		spin_unlock_irq(&phba->hbalock);
16659 		return NO_XRI;
16660 	} else {
16661 		set_bit(xri, phba->sli4_hba.xri_bmask);
16662 		phba->sli4_hba.max_cfg_param.xri_used++;
16663 	}
16664 	spin_unlock_irq(&phba->hbalock);
16665 	return xri;
16666 }
16667 
16668 /**
16669  * lpfc_sli4_free_xri - Release an xri for reuse.
16670  * @phba: pointer to lpfc hba data structure.
16671  *
16672  * This routine is invoked to release an xri to the pool of
16673  * available rpis maintained by the driver.
16674  **/
16675 static void
16676 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
16677 {
16678 	if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
16679 		phba->sli4_hba.max_cfg_param.xri_used--;
16680 	}
16681 }
16682 
16683 /**
16684  * lpfc_sli4_free_xri - Release an xri for reuse.
16685  * @phba: pointer to lpfc hba data structure.
16686  *
16687  * This routine is invoked to release an xri to the pool of
16688  * available rpis maintained by the driver.
16689  **/
16690 void
16691 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
16692 {
16693 	spin_lock_irq(&phba->hbalock);
16694 	__lpfc_sli4_free_xri(phba, xri);
16695 	spin_unlock_irq(&phba->hbalock);
16696 }
16697 
16698 /**
16699  * lpfc_sli4_next_xritag - Get an xritag for the io
16700  * @phba: Pointer to HBA context object.
16701  *
16702  * This function gets an xritag for the iocb. If there is no unused xritag
16703  * it will return 0xffff.
16704  * The function returns the allocated xritag if successful, else returns zero.
16705  * Zero is not a valid xritag.
16706  * The caller is not required to hold any lock.
16707  **/
16708 uint16_t
16709 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
16710 {
16711 	uint16_t xri_index;
16712 
16713 	xri_index = lpfc_sli4_alloc_xri(phba);
16714 	if (xri_index == NO_XRI)
16715 		lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
16716 				"2004 Failed to allocate XRI.last XRITAG is %d"
16717 				" Max XRI is %d, Used XRI is %d\n",
16718 				xri_index,
16719 				phba->sli4_hba.max_cfg_param.max_xri,
16720 				phba->sli4_hba.max_cfg_param.xri_used);
16721 	return xri_index;
16722 }
16723 
16724 /**
16725  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
16726  * @phba: pointer to lpfc hba data structure.
16727  * @post_sgl_list: pointer to els sgl entry list.
16728  * @count: number of els sgl entries on the list.
16729  *
16730  * This routine is invoked to post a block of driver's sgl pages to the
16731  * HBA using non-embedded mailbox command. No Lock is held. This routine
16732  * is only called when the driver is loading and after all IO has been
16733  * stopped.
16734  **/
16735 static int
16736 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
16737 			    struct list_head *post_sgl_list,
16738 			    int post_cnt)
16739 {
16740 	struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
16741 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
16742 	struct sgl_page_pairs *sgl_pg_pairs;
16743 	void *viraddr;
16744 	LPFC_MBOXQ_t *mbox;
16745 	uint32_t reqlen, alloclen, pg_pairs;
16746 	uint32_t mbox_tmo;
16747 	uint16_t xritag_start = 0;
16748 	int rc = 0;
16749 	uint32_t shdr_status, shdr_add_status;
16750 	union lpfc_sli4_cfg_shdr *shdr;
16751 
16752 	reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
16753 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
16754 	if (reqlen > SLI4_PAGE_SIZE) {
16755 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16756 				"2559 Block sgl registration required DMA "
16757 				"size (%d) great than a page\n", reqlen);
16758 		return -ENOMEM;
16759 	}
16760 
16761 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16762 	if (!mbox)
16763 		return -ENOMEM;
16764 
16765 	/* Allocate DMA memory and set up the non-embedded mailbox command */
16766 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16767 			 LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
16768 			 LPFC_SLI4_MBX_NEMBED);
16769 
16770 	if (alloclen < reqlen) {
16771 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16772 				"0285 Allocated DMA memory size (%d) is "
16773 				"less than the requested DMA memory "
16774 				"size (%d)\n", alloclen, reqlen);
16775 		lpfc_sli4_mbox_cmd_free(phba, mbox);
16776 		return -ENOMEM;
16777 	}
16778 	/* Set up the SGL pages in the non-embedded DMA pages */
16779 	viraddr = mbox->sge_array->addr[0];
16780 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
16781 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
16782 
16783 	pg_pairs = 0;
16784 	list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
16785 		/* Set up the sge entry */
16786 		sgl_pg_pairs->sgl_pg0_addr_lo =
16787 				cpu_to_le32(putPaddrLow(sglq_entry->phys));
16788 		sgl_pg_pairs->sgl_pg0_addr_hi =
16789 				cpu_to_le32(putPaddrHigh(sglq_entry->phys));
16790 		sgl_pg_pairs->sgl_pg1_addr_lo =
16791 				cpu_to_le32(putPaddrLow(0));
16792 		sgl_pg_pairs->sgl_pg1_addr_hi =
16793 				cpu_to_le32(putPaddrHigh(0));
16794 
16795 		/* Keep the first xritag on the list */
16796 		if (pg_pairs == 0)
16797 			xritag_start = sglq_entry->sli4_xritag;
16798 		sgl_pg_pairs++;
16799 		pg_pairs++;
16800 	}
16801 
16802 	/* Complete initialization and perform endian conversion. */
16803 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
16804 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
16805 	sgl->word0 = cpu_to_le32(sgl->word0);
16806 
16807 	if (!phba->sli4_hba.intr_enable)
16808 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16809 	else {
16810 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
16811 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
16812 	}
16813 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
16814 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16815 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16816 	if (rc != MBX_TIMEOUT)
16817 		lpfc_sli4_mbox_cmd_free(phba, mbox);
16818 	if (shdr_status || shdr_add_status || rc) {
16819 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16820 				"2513 POST_SGL_BLOCK mailbox command failed "
16821 				"status x%x add_status x%x mbx status x%x\n",
16822 				shdr_status, shdr_add_status, rc);
16823 		rc = -ENXIO;
16824 	}
16825 	return rc;
16826 }
16827 
16828 /**
16829  * lpfc_sli4_post_scsi_sgl_block - post a block of scsi sgl list to firmware
16830  * @phba: pointer to lpfc hba data structure.
16831  * @sblist: pointer to scsi buffer list.
16832  * @count: number of scsi buffers on the list.
16833  *
16834  * This routine is invoked to post a block of @count scsi sgl pages from a
16835  * SCSI buffer list @sblist to the HBA using non-embedded mailbox command.
16836  * No Lock is held.
16837  *
16838  **/
16839 int
16840 lpfc_sli4_post_scsi_sgl_block(struct lpfc_hba *phba,
16841 			      struct list_head *sblist,
16842 			      int count)
16843 {
16844 	struct lpfc_scsi_buf *psb;
16845 	struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
16846 	struct sgl_page_pairs *sgl_pg_pairs;
16847 	void *viraddr;
16848 	LPFC_MBOXQ_t *mbox;
16849 	uint32_t reqlen, alloclen, pg_pairs;
16850 	uint32_t mbox_tmo;
16851 	uint16_t xritag_start = 0;
16852 	int rc = 0;
16853 	uint32_t shdr_status, shdr_add_status;
16854 	dma_addr_t pdma_phys_bpl1;
16855 	union lpfc_sli4_cfg_shdr *shdr;
16856 
16857 	/* Calculate the requested length of the dma memory */
16858 	reqlen = count * sizeof(struct sgl_page_pairs) +
16859 		 sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
16860 	if (reqlen > SLI4_PAGE_SIZE) {
16861 		lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
16862 				"0217 Block sgl registration required DMA "
16863 				"size (%d) great than a page\n", reqlen);
16864 		return -ENOMEM;
16865 	}
16866 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16867 	if (!mbox) {
16868 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16869 				"0283 Failed to allocate mbox cmd memory\n");
16870 		return -ENOMEM;
16871 	}
16872 
16873 	/* Allocate DMA memory and set up the non-embedded mailbox command */
16874 	alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16875 				LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
16876 				LPFC_SLI4_MBX_NEMBED);
16877 
16878 	if (alloclen < reqlen) {
16879 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16880 				"2561 Allocated DMA memory size (%d) is "
16881 				"less than the requested DMA memory "
16882 				"size (%d)\n", alloclen, reqlen);
16883 		lpfc_sli4_mbox_cmd_free(phba, mbox);
16884 		return -ENOMEM;
16885 	}
16886 
16887 	/* Get the first SGE entry from the non-embedded DMA memory */
16888 	viraddr = mbox->sge_array->addr[0];
16889 
16890 	/* Set up the SGL pages in the non-embedded DMA pages */
16891 	sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
16892 	sgl_pg_pairs = &sgl->sgl_pg_pairs;
16893 
16894 	pg_pairs = 0;
16895 	list_for_each_entry(psb, sblist, list) {
16896 		/* Set up the sge entry */
16897 		sgl_pg_pairs->sgl_pg0_addr_lo =
16898 			cpu_to_le32(putPaddrLow(psb->dma_phys_bpl));
16899 		sgl_pg_pairs->sgl_pg0_addr_hi =
16900 			cpu_to_le32(putPaddrHigh(psb->dma_phys_bpl));
16901 		if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
16902 			pdma_phys_bpl1 = psb->dma_phys_bpl + SGL_PAGE_SIZE;
16903 		else
16904 			pdma_phys_bpl1 = 0;
16905 		sgl_pg_pairs->sgl_pg1_addr_lo =
16906 			cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
16907 		sgl_pg_pairs->sgl_pg1_addr_hi =
16908 			cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
16909 		/* Keep the first xritag on the list */
16910 		if (pg_pairs == 0)
16911 			xritag_start = psb->cur_iocbq.sli4_xritag;
16912 		sgl_pg_pairs++;
16913 		pg_pairs++;
16914 	}
16915 	bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
16916 	bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
16917 	/* Perform endian conversion if necessary */
16918 	sgl->word0 = cpu_to_le32(sgl->word0);
16919 
16920 	if (!phba->sli4_hba.intr_enable)
16921 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16922 	else {
16923 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
16924 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
16925 	}
16926 	shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
16927 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16928 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16929 	if (rc != MBX_TIMEOUT)
16930 		lpfc_sli4_mbox_cmd_free(phba, mbox);
16931 	if (shdr_status || shdr_add_status || rc) {
16932 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16933 				"2564 POST_SGL_BLOCK mailbox command failed "
16934 				"status x%x add_status x%x mbx status x%x\n",
16935 				shdr_status, shdr_add_status, rc);
16936 		rc = -ENXIO;
16937 	}
16938 	return rc;
16939 }
16940 
16941 /**
16942  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
16943  * @phba: pointer to lpfc_hba struct that the frame was received on
16944  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
16945  *
16946  * This function checks the fields in the @fc_hdr to see if the FC frame is a
16947  * valid type of frame that the LPFC driver will handle. This function will
16948  * return a zero if the frame is a valid frame or a non zero value when the
16949  * frame does not pass the check.
16950  **/
16951 static int
16952 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
16953 {
16954 	/*  make rctl_names static to save stack space */
16955 	struct fc_vft_header *fc_vft_hdr;
16956 	uint32_t *header = (uint32_t *) fc_hdr;
16957 
16958 	switch (fc_hdr->fh_r_ctl) {
16959 	case FC_RCTL_DD_UNCAT:		/* uncategorized information */
16960 	case FC_RCTL_DD_SOL_DATA:	/* solicited data */
16961 	case FC_RCTL_DD_UNSOL_CTL:	/* unsolicited control */
16962 	case FC_RCTL_DD_SOL_CTL:	/* solicited control or reply */
16963 	case FC_RCTL_DD_UNSOL_DATA:	/* unsolicited data */
16964 	case FC_RCTL_DD_DATA_DESC:	/* data descriptor */
16965 	case FC_RCTL_DD_UNSOL_CMD:	/* unsolicited command */
16966 	case FC_RCTL_DD_CMD_STATUS:	/* command status */
16967 	case FC_RCTL_ELS_REQ:	/* extended link services request */
16968 	case FC_RCTL_ELS_REP:	/* extended link services reply */
16969 	case FC_RCTL_ELS4_REQ:	/* FC-4 ELS request */
16970 	case FC_RCTL_ELS4_REP:	/* FC-4 ELS reply */
16971 	case FC_RCTL_BA_NOP:  	/* basic link service NOP */
16972 	case FC_RCTL_BA_ABTS: 	/* basic link service abort */
16973 	case FC_RCTL_BA_RMC: 	/* remove connection */
16974 	case FC_RCTL_BA_ACC:	/* basic accept */
16975 	case FC_RCTL_BA_RJT:	/* basic reject */
16976 	case FC_RCTL_BA_PRMT:
16977 	case FC_RCTL_ACK_1:	/* acknowledge_1 */
16978 	case FC_RCTL_ACK_0:	/* acknowledge_0 */
16979 	case FC_RCTL_P_RJT:	/* port reject */
16980 	case FC_RCTL_F_RJT:	/* fabric reject */
16981 	case FC_RCTL_P_BSY:	/* port busy */
16982 	case FC_RCTL_F_BSY:	/* fabric busy to data frame */
16983 	case FC_RCTL_F_BSYL:	/* fabric busy to link control frame */
16984 	case FC_RCTL_LCR:	/* link credit reset */
16985 	case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
16986 	case FC_RCTL_END:	/* end */
16987 		break;
16988 	case FC_RCTL_VFTH:	/* Virtual Fabric tagging Header */
16989 		fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
16990 		fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
16991 		return lpfc_fc_frame_check(phba, fc_hdr);
16992 	default:
16993 		goto drop;
16994 	}
16995 
16996 	switch (fc_hdr->fh_type) {
16997 	case FC_TYPE_BLS:
16998 	case FC_TYPE_ELS:
16999 	case FC_TYPE_FCP:
17000 	case FC_TYPE_CT:
17001 	case FC_TYPE_NVME:
17002 		break;
17003 	case FC_TYPE_IP:
17004 	case FC_TYPE_ILS:
17005 	default:
17006 		goto drop;
17007 	}
17008 
17009 	lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
17010 			"2538 Received frame rctl:x%x, type:x%x, "
17011 			"frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
17012 			fc_hdr->fh_r_ctl, fc_hdr->fh_type,
17013 			be32_to_cpu(header[0]), be32_to_cpu(header[1]),
17014 			be32_to_cpu(header[2]), be32_to_cpu(header[3]),
17015 			be32_to_cpu(header[4]), be32_to_cpu(header[5]),
17016 			be32_to_cpu(header[6]));
17017 	return 0;
17018 drop:
17019 	lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
17020 			"2539 Dropped frame rctl:x%x type:x%x\n",
17021 			fc_hdr->fh_r_ctl, fc_hdr->fh_type);
17022 	return 1;
17023 }
17024 
17025 /**
17026  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
17027  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17028  *
17029  * This function processes the FC header to retrieve the VFI from the VF
17030  * header, if one exists. This function will return the VFI if one exists
17031  * or 0 if no VSAN Header exists.
17032  **/
17033 static uint32_t
17034 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
17035 {
17036 	struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17037 
17038 	if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
17039 		return 0;
17040 	return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
17041 }
17042 
17043 /**
17044  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
17045  * @phba: Pointer to the HBA structure to search for the vport on
17046  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17047  * @fcfi: The FC Fabric ID that the frame came from
17048  *
17049  * This function searches the @phba for a vport that matches the content of the
17050  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
17051  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
17052  * returns the matching vport pointer or NULL if unable to match frame to a
17053  * vport.
17054  **/
17055 static struct lpfc_vport *
17056 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
17057 		       uint16_t fcfi, uint32_t did)
17058 {
17059 	struct lpfc_vport **vports;
17060 	struct lpfc_vport *vport = NULL;
17061 	int i;
17062 
17063 	if (did == Fabric_DID)
17064 		return phba->pport;
17065 	if ((phba->pport->fc_flag & FC_PT2PT) &&
17066 		!(phba->link_state == LPFC_HBA_READY))
17067 		return phba->pport;
17068 
17069 	vports = lpfc_create_vport_work_array(phba);
17070 	if (vports != NULL) {
17071 		for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
17072 			if (phba->fcf.fcfi == fcfi &&
17073 			    vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
17074 			    vports[i]->fc_myDID == did) {
17075 				vport = vports[i];
17076 				break;
17077 			}
17078 		}
17079 	}
17080 	lpfc_destroy_vport_work_array(phba, vports);
17081 	return vport;
17082 }
17083 
17084 /**
17085  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
17086  * @vport: The vport to work on.
17087  *
17088  * This function updates the receive sequence time stamp for this vport. The
17089  * receive sequence time stamp indicates the time that the last frame of the
17090  * the sequence that has been idle for the longest amount of time was received.
17091  * the driver uses this time stamp to indicate if any received sequences have
17092  * timed out.
17093  **/
17094 static void
17095 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
17096 {
17097 	struct lpfc_dmabuf *h_buf;
17098 	struct hbq_dmabuf *dmabuf = NULL;
17099 
17100 	/* get the oldest sequence on the rcv list */
17101 	h_buf = list_get_first(&vport->rcv_buffer_list,
17102 			       struct lpfc_dmabuf, list);
17103 	if (!h_buf)
17104 		return;
17105 	dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17106 	vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
17107 }
17108 
17109 /**
17110  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
17111  * @vport: The vport that the received sequences were sent to.
17112  *
17113  * This function cleans up all outstanding received sequences. This is called
17114  * by the driver when a link event or user action invalidates all the received
17115  * sequences.
17116  **/
17117 void
17118 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
17119 {
17120 	struct lpfc_dmabuf *h_buf, *hnext;
17121 	struct lpfc_dmabuf *d_buf, *dnext;
17122 	struct hbq_dmabuf *dmabuf = NULL;
17123 
17124 	/* start with the oldest sequence on the rcv list */
17125 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17126 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17127 		list_del_init(&dmabuf->hbuf.list);
17128 		list_for_each_entry_safe(d_buf, dnext,
17129 					 &dmabuf->dbuf.list, list) {
17130 			list_del_init(&d_buf->list);
17131 			lpfc_in_buf_free(vport->phba, d_buf);
17132 		}
17133 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17134 	}
17135 }
17136 
17137 /**
17138  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
17139  * @vport: The vport that the received sequences were sent to.
17140  *
17141  * This function determines whether any received sequences have timed out by
17142  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
17143  * indicates that there is at least one timed out sequence this routine will
17144  * go through the received sequences one at a time from most inactive to most
17145  * active to determine which ones need to be cleaned up. Once it has determined
17146  * that a sequence needs to be cleaned up it will simply free up the resources
17147  * without sending an abort.
17148  **/
17149 void
17150 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
17151 {
17152 	struct lpfc_dmabuf *h_buf, *hnext;
17153 	struct lpfc_dmabuf *d_buf, *dnext;
17154 	struct hbq_dmabuf *dmabuf = NULL;
17155 	unsigned long timeout;
17156 	int abort_count = 0;
17157 
17158 	timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17159 		   vport->rcv_buffer_time_stamp);
17160 	if (list_empty(&vport->rcv_buffer_list) ||
17161 	    time_before(jiffies, timeout))
17162 		return;
17163 	/* start with the oldest sequence on the rcv list */
17164 	list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17165 		dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17166 		timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17167 			   dmabuf->time_stamp);
17168 		if (time_before(jiffies, timeout))
17169 			break;
17170 		abort_count++;
17171 		list_del_init(&dmabuf->hbuf.list);
17172 		list_for_each_entry_safe(d_buf, dnext,
17173 					 &dmabuf->dbuf.list, list) {
17174 			list_del_init(&d_buf->list);
17175 			lpfc_in_buf_free(vport->phba, d_buf);
17176 		}
17177 		lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17178 	}
17179 	if (abort_count)
17180 		lpfc_update_rcv_time_stamp(vport);
17181 }
17182 
17183 /**
17184  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
17185  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
17186  *
17187  * This function searches through the existing incomplete sequences that have
17188  * been sent to this @vport. If the frame matches one of the incomplete
17189  * sequences then the dbuf in the @dmabuf is added to the list of frames that
17190  * make up that sequence. If no sequence is found that matches this frame then
17191  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
17192  * This function returns a pointer to the first dmabuf in the sequence list that
17193  * the frame was linked to.
17194  **/
17195 static struct hbq_dmabuf *
17196 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
17197 {
17198 	struct fc_frame_header *new_hdr;
17199 	struct fc_frame_header *temp_hdr;
17200 	struct lpfc_dmabuf *d_buf;
17201 	struct lpfc_dmabuf *h_buf;
17202 	struct hbq_dmabuf *seq_dmabuf = NULL;
17203 	struct hbq_dmabuf *temp_dmabuf = NULL;
17204 	uint8_t	found = 0;
17205 
17206 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
17207 	dmabuf->time_stamp = jiffies;
17208 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17209 
17210 	/* Use the hdr_buf to find the sequence that this frame belongs to */
17211 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
17212 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
17213 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
17214 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
17215 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
17216 			continue;
17217 		/* found a pending sequence that matches this frame */
17218 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17219 		break;
17220 	}
17221 	if (!seq_dmabuf) {
17222 		/*
17223 		 * This indicates first frame received for this sequence.
17224 		 * Queue the buffer on the vport's rcv_buffer_list.
17225 		 */
17226 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
17227 		lpfc_update_rcv_time_stamp(vport);
17228 		return dmabuf;
17229 	}
17230 	temp_hdr = seq_dmabuf->hbuf.virt;
17231 	if (be16_to_cpu(new_hdr->fh_seq_cnt) <
17232 		be16_to_cpu(temp_hdr->fh_seq_cnt)) {
17233 		list_del_init(&seq_dmabuf->hbuf.list);
17234 		list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
17235 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
17236 		lpfc_update_rcv_time_stamp(vport);
17237 		return dmabuf;
17238 	}
17239 	/* move this sequence to the tail to indicate a young sequence */
17240 	list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
17241 	seq_dmabuf->time_stamp = jiffies;
17242 	lpfc_update_rcv_time_stamp(vport);
17243 	if (list_empty(&seq_dmabuf->dbuf.list)) {
17244 		temp_hdr = dmabuf->hbuf.virt;
17245 		list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
17246 		return seq_dmabuf;
17247 	}
17248 	/* find the correct place in the sequence to insert this frame */
17249 	d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
17250 	while (!found) {
17251 		temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17252 		temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
17253 		/*
17254 		 * If the frame's sequence count is greater than the frame on
17255 		 * the list then insert the frame right after this frame
17256 		 */
17257 		if (be16_to_cpu(new_hdr->fh_seq_cnt) >
17258 			be16_to_cpu(temp_hdr->fh_seq_cnt)) {
17259 			list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
17260 			found = 1;
17261 			break;
17262 		}
17263 
17264 		if (&d_buf->list == &seq_dmabuf->dbuf.list)
17265 			break;
17266 		d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
17267 	}
17268 
17269 	if (found)
17270 		return seq_dmabuf;
17271 	return NULL;
17272 }
17273 
17274 /**
17275  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
17276  * @vport: pointer to a vitural port
17277  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17278  *
17279  * This function tries to abort from the partially assembed sequence, described
17280  * by the information from basic abbort @dmabuf. It checks to see whether such
17281  * partially assembled sequence held by the driver. If so, it shall free up all
17282  * the frames from the partially assembled sequence.
17283  *
17284  * Return
17285  * true  -- if there is matching partially assembled sequence present and all
17286  *          the frames freed with the sequence;
17287  * false -- if there is no matching partially assembled sequence present so
17288  *          nothing got aborted in the lower layer driver
17289  **/
17290 static bool
17291 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
17292 			    struct hbq_dmabuf *dmabuf)
17293 {
17294 	struct fc_frame_header *new_hdr;
17295 	struct fc_frame_header *temp_hdr;
17296 	struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
17297 	struct hbq_dmabuf *seq_dmabuf = NULL;
17298 
17299 	/* Use the hdr_buf to find the sequence that matches this frame */
17300 	INIT_LIST_HEAD(&dmabuf->dbuf.list);
17301 	INIT_LIST_HEAD(&dmabuf->hbuf.list);
17302 	new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17303 	list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
17304 		temp_hdr = (struct fc_frame_header *)h_buf->virt;
17305 		if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
17306 		    (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
17307 		    (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
17308 			continue;
17309 		/* found a pending sequence that matches this frame */
17310 		seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17311 		break;
17312 	}
17313 
17314 	/* Free up all the frames from the partially assembled sequence */
17315 	if (seq_dmabuf) {
17316 		list_for_each_entry_safe(d_buf, n_buf,
17317 					 &seq_dmabuf->dbuf.list, list) {
17318 			list_del_init(&d_buf->list);
17319 			lpfc_in_buf_free(vport->phba, d_buf);
17320 		}
17321 		return true;
17322 	}
17323 	return false;
17324 }
17325 
17326 /**
17327  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
17328  * @vport: pointer to a vitural port
17329  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17330  *
17331  * This function tries to abort from the assembed sequence from upper level
17332  * protocol, described by the information from basic abbort @dmabuf. It
17333  * checks to see whether such pending context exists at upper level protocol.
17334  * If so, it shall clean up the pending context.
17335  *
17336  * Return
17337  * true  -- if there is matching pending context of the sequence cleaned
17338  *          at ulp;
17339  * false -- if there is no matching pending context of the sequence present
17340  *          at ulp.
17341  **/
17342 static bool
17343 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
17344 {
17345 	struct lpfc_hba *phba = vport->phba;
17346 	int handled;
17347 
17348 	/* Accepting abort at ulp with SLI4 only */
17349 	if (phba->sli_rev < LPFC_SLI_REV4)
17350 		return false;
17351 
17352 	/* Register all caring upper level protocols to attend abort */
17353 	handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
17354 	if (handled)
17355 		return true;
17356 
17357 	return false;
17358 }
17359 
17360 /**
17361  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
17362  * @phba: Pointer to HBA context object.
17363  * @cmd_iocbq: pointer to the command iocbq structure.
17364  * @rsp_iocbq: pointer to the response iocbq structure.
17365  *
17366  * This function handles the sequence abort response iocb command complete
17367  * event. It properly releases the memory allocated to the sequence abort
17368  * accept iocb.
17369  **/
17370 static void
17371 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
17372 			     struct lpfc_iocbq *cmd_iocbq,
17373 			     struct lpfc_iocbq *rsp_iocbq)
17374 {
17375 	struct lpfc_nodelist *ndlp;
17376 
17377 	if (cmd_iocbq) {
17378 		ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
17379 		lpfc_nlp_put(ndlp);
17380 		lpfc_nlp_not_used(ndlp);
17381 		lpfc_sli_release_iocbq(phba, cmd_iocbq);
17382 	}
17383 
17384 	/* Failure means BLS ABORT RSP did not get delivered to remote node*/
17385 	if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
17386 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17387 			"3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
17388 			rsp_iocbq->iocb.ulpStatus,
17389 			rsp_iocbq->iocb.un.ulpWord[4]);
17390 }
17391 
17392 /**
17393  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
17394  * @phba: Pointer to HBA context object.
17395  * @xri: xri id in transaction.
17396  *
17397  * This function validates the xri maps to the known range of XRIs allocated an
17398  * used by the driver.
17399  **/
17400 uint16_t
17401 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
17402 		      uint16_t xri)
17403 {
17404 	uint16_t i;
17405 
17406 	for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
17407 		if (xri == phba->sli4_hba.xri_ids[i])
17408 			return i;
17409 	}
17410 	return NO_XRI;
17411 }
17412 
17413 /**
17414  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
17415  * @phba: Pointer to HBA context object.
17416  * @fc_hdr: pointer to a FC frame header.
17417  *
17418  * This function sends a basic response to a previous unsol sequence abort
17419  * event after aborting the sequence handling.
17420  **/
17421 void
17422 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
17423 			struct fc_frame_header *fc_hdr, bool aborted)
17424 {
17425 	struct lpfc_hba *phba = vport->phba;
17426 	struct lpfc_iocbq *ctiocb = NULL;
17427 	struct lpfc_nodelist *ndlp;
17428 	uint16_t oxid, rxid, xri, lxri;
17429 	uint32_t sid, fctl;
17430 	IOCB_t *icmd;
17431 	int rc;
17432 
17433 	if (!lpfc_is_link_up(phba))
17434 		return;
17435 
17436 	sid = sli4_sid_from_fc_hdr(fc_hdr);
17437 	oxid = be16_to_cpu(fc_hdr->fh_ox_id);
17438 	rxid = be16_to_cpu(fc_hdr->fh_rx_id);
17439 
17440 	ndlp = lpfc_findnode_did(vport, sid);
17441 	if (!ndlp) {
17442 		ndlp = lpfc_nlp_init(vport, sid);
17443 		if (!ndlp) {
17444 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
17445 					 "1268 Failed to allocate ndlp for "
17446 					 "oxid:x%x SID:x%x\n", oxid, sid);
17447 			return;
17448 		}
17449 		/* Put ndlp onto pport node list */
17450 		lpfc_enqueue_node(vport, ndlp);
17451 	} else if (!NLP_CHK_NODE_ACT(ndlp)) {
17452 		/* re-setup ndlp without removing from node list */
17453 		ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_UNUSED_NODE);
17454 		if (!ndlp) {
17455 			lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
17456 					 "3275 Failed to active ndlp found "
17457 					 "for oxid:x%x SID:x%x\n", oxid, sid);
17458 			return;
17459 		}
17460 	}
17461 
17462 	/* Allocate buffer for rsp iocb */
17463 	ctiocb = lpfc_sli_get_iocbq(phba);
17464 	if (!ctiocb)
17465 		return;
17466 
17467 	/* Extract the F_CTL field from FC_HDR */
17468 	fctl = sli4_fctl_from_fc_hdr(fc_hdr);
17469 
17470 	icmd = &ctiocb->iocb;
17471 	icmd->un.xseq64.bdl.bdeSize = 0;
17472 	icmd->un.xseq64.bdl.ulpIoTag32 = 0;
17473 	icmd->un.xseq64.w5.hcsw.Dfctl = 0;
17474 	icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
17475 	icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
17476 
17477 	/* Fill in the rest of iocb fields */
17478 	icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
17479 	icmd->ulpBdeCount = 0;
17480 	icmd->ulpLe = 1;
17481 	icmd->ulpClass = CLASS3;
17482 	icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
17483 	ctiocb->context1 = lpfc_nlp_get(ndlp);
17484 
17485 	ctiocb->iocb_cmpl = NULL;
17486 	ctiocb->vport = phba->pport;
17487 	ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
17488 	ctiocb->sli4_lxritag = NO_XRI;
17489 	ctiocb->sli4_xritag = NO_XRI;
17490 
17491 	if (fctl & FC_FC_EX_CTX)
17492 		/* Exchange responder sent the abort so we
17493 		 * own the oxid.
17494 		 */
17495 		xri = oxid;
17496 	else
17497 		xri = rxid;
17498 	lxri = lpfc_sli4_xri_inrange(phba, xri);
17499 	if (lxri != NO_XRI)
17500 		lpfc_set_rrq_active(phba, ndlp, lxri,
17501 			(xri == oxid) ? rxid : oxid, 0);
17502 	/* For BA_ABTS from exchange responder, if the logical xri with
17503 	 * the oxid maps to the FCP XRI range, the port no longer has
17504 	 * that exchange context, send a BLS_RJT. Override the IOCB for
17505 	 * a BA_RJT.
17506 	 */
17507 	if ((fctl & FC_FC_EX_CTX) &&
17508 	    (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
17509 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
17510 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
17511 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
17512 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
17513 	}
17514 
17515 	/* If BA_ABTS failed to abort a partially assembled receive sequence,
17516 	 * the driver no longer has that exchange, send a BLS_RJT. Override
17517 	 * the IOCB for a BA_RJT.
17518 	 */
17519 	if (aborted == false) {
17520 		icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
17521 		bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
17522 		bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
17523 		bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
17524 	}
17525 
17526 	if (fctl & FC_FC_EX_CTX) {
17527 		/* ABTS sent by responder to CT exchange, construction
17528 		 * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
17529 		 * field and RX_ID from ABTS for RX_ID field.
17530 		 */
17531 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
17532 	} else {
17533 		/* ABTS sent by initiator to CT exchange, construction
17534 		 * of BA_ACC will need to allocate a new XRI as for the
17535 		 * XRI_TAG field.
17536 		 */
17537 		bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
17538 	}
17539 	bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
17540 	bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
17541 
17542 	/* Xmit CT abts response on exchange <xid> */
17543 	lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
17544 			 "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
17545 			 icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
17546 
17547 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
17548 	if (rc == IOCB_ERROR) {
17549 		lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
17550 				 "2925 Failed to issue CT ABTS RSP x%x on "
17551 				 "xri x%x, Data x%x\n",
17552 				 icmd->un.xseq64.w5.hcsw.Rctl, oxid,
17553 				 phba->link_state);
17554 		lpfc_nlp_put(ndlp);
17555 		ctiocb->context1 = NULL;
17556 		lpfc_sli_release_iocbq(phba, ctiocb);
17557 	}
17558 }
17559 
17560 /**
17561  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
17562  * @vport: Pointer to the vport on which this sequence was received
17563  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17564  *
17565  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
17566  * receive sequence is only partially assembed by the driver, it shall abort
17567  * the partially assembled frames for the sequence. Otherwise, if the
17568  * unsolicited receive sequence has been completely assembled and passed to
17569  * the Upper Layer Protocol (UPL), it then mark the per oxid status for the
17570  * unsolicited sequence has been aborted. After that, it will issue a basic
17571  * accept to accept the abort.
17572  **/
17573 static void
17574 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
17575 			     struct hbq_dmabuf *dmabuf)
17576 {
17577 	struct lpfc_hba *phba = vport->phba;
17578 	struct fc_frame_header fc_hdr;
17579 	uint32_t fctl;
17580 	bool aborted;
17581 
17582 	/* Make a copy of fc_hdr before the dmabuf being released */
17583 	memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
17584 	fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
17585 
17586 	if (fctl & FC_FC_EX_CTX) {
17587 		/* ABTS by responder to exchange, no cleanup needed */
17588 		aborted = true;
17589 	} else {
17590 		/* ABTS by initiator to exchange, need to do cleanup */
17591 		aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
17592 		if (aborted == false)
17593 			aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
17594 	}
17595 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
17596 
17597 	if (phba->nvmet_support) {
17598 		lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
17599 		return;
17600 	}
17601 
17602 	/* Respond with BA_ACC or BA_RJT accordingly */
17603 	lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
17604 }
17605 
17606 /**
17607  * lpfc_seq_complete - Indicates if a sequence is complete
17608  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17609  *
17610  * This function checks the sequence, starting with the frame described by
17611  * @dmabuf, to see if all the frames associated with this sequence are present.
17612  * the frames associated with this sequence are linked to the @dmabuf using the
17613  * dbuf list. This function looks for two major things. 1) That the first frame
17614  * has a sequence count of zero. 2) There is a frame with last frame of sequence
17615  * set. 3) That there are no holes in the sequence count. The function will
17616  * return 1 when the sequence is complete, otherwise it will return 0.
17617  **/
17618 static int
17619 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
17620 {
17621 	struct fc_frame_header *hdr;
17622 	struct lpfc_dmabuf *d_buf;
17623 	struct hbq_dmabuf *seq_dmabuf;
17624 	uint32_t fctl;
17625 	int seq_count = 0;
17626 
17627 	hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17628 	/* make sure first fame of sequence has a sequence count of zero */
17629 	if (hdr->fh_seq_cnt != seq_count)
17630 		return 0;
17631 	fctl = (hdr->fh_f_ctl[0] << 16 |
17632 		hdr->fh_f_ctl[1] << 8 |
17633 		hdr->fh_f_ctl[2]);
17634 	/* If last frame of sequence we can return success. */
17635 	if (fctl & FC_FC_END_SEQ)
17636 		return 1;
17637 	list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
17638 		seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17639 		hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
17640 		/* If there is a hole in the sequence count then fail. */
17641 		if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
17642 			return 0;
17643 		fctl = (hdr->fh_f_ctl[0] << 16 |
17644 			hdr->fh_f_ctl[1] << 8 |
17645 			hdr->fh_f_ctl[2]);
17646 		/* If last frame of sequence we can return success. */
17647 		if (fctl & FC_FC_END_SEQ)
17648 			return 1;
17649 	}
17650 	return 0;
17651 }
17652 
17653 /**
17654  * lpfc_prep_seq - Prep sequence for ULP processing
17655  * @vport: Pointer to the vport on which this sequence was received
17656  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17657  *
17658  * This function takes a sequence, described by a list of frames, and creates
17659  * a list of iocbq structures to describe the sequence. This iocbq list will be
17660  * used to issue to the generic unsolicited sequence handler. This routine
17661  * returns a pointer to the first iocbq in the list. If the function is unable
17662  * to allocate an iocbq then it throw out the received frames that were not
17663  * able to be described and return a pointer to the first iocbq. If unable to
17664  * allocate any iocbqs (including the first) this function will return NULL.
17665  **/
17666 static struct lpfc_iocbq *
17667 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
17668 {
17669 	struct hbq_dmabuf *hbq_buf;
17670 	struct lpfc_dmabuf *d_buf, *n_buf;
17671 	struct lpfc_iocbq *first_iocbq, *iocbq;
17672 	struct fc_frame_header *fc_hdr;
17673 	uint32_t sid;
17674 	uint32_t len, tot_len;
17675 	struct ulp_bde64 *pbde;
17676 
17677 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
17678 	/* remove from receive buffer list */
17679 	list_del_init(&seq_dmabuf->hbuf.list);
17680 	lpfc_update_rcv_time_stamp(vport);
17681 	/* get the Remote Port's SID */
17682 	sid = sli4_sid_from_fc_hdr(fc_hdr);
17683 	tot_len = 0;
17684 	/* Get an iocbq struct to fill in. */
17685 	first_iocbq = lpfc_sli_get_iocbq(vport->phba);
17686 	if (first_iocbq) {
17687 		/* Initialize the first IOCB. */
17688 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
17689 		first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
17690 		first_iocbq->vport = vport;
17691 
17692 		/* Check FC Header to see what TYPE of frame we are rcv'ing */
17693 		if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
17694 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
17695 			first_iocbq->iocb.un.rcvels.parmRo =
17696 				sli4_did_from_fc_hdr(fc_hdr);
17697 			first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
17698 		} else
17699 			first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
17700 		first_iocbq->iocb.ulpContext = NO_XRI;
17701 		first_iocbq->iocb.unsli3.rcvsli3.ox_id =
17702 			be16_to_cpu(fc_hdr->fh_ox_id);
17703 		/* iocbq is prepped for internal consumption.  Physical vpi. */
17704 		first_iocbq->iocb.unsli3.rcvsli3.vpi =
17705 			vport->phba->vpi_ids[vport->vpi];
17706 		/* put the first buffer into the first IOCBq */
17707 		tot_len = bf_get(lpfc_rcqe_length,
17708 				       &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
17709 
17710 		first_iocbq->context2 = &seq_dmabuf->dbuf;
17711 		first_iocbq->context3 = NULL;
17712 		first_iocbq->iocb.ulpBdeCount = 1;
17713 		if (tot_len > LPFC_DATA_BUF_SIZE)
17714 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
17715 							LPFC_DATA_BUF_SIZE;
17716 		else
17717 			first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
17718 
17719 		first_iocbq->iocb.un.rcvels.remoteID = sid;
17720 
17721 		first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
17722 	}
17723 	iocbq = first_iocbq;
17724 	/*
17725 	 * Each IOCBq can have two Buffers assigned, so go through the list
17726 	 * of buffers for this sequence and save two buffers in each IOCBq
17727 	 */
17728 	list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
17729 		if (!iocbq) {
17730 			lpfc_in_buf_free(vport->phba, d_buf);
17731 			continue;
17732 		}
17733 		if (!iocbq->context3) {
17734 			iocbq->context3 = d_buf;
17735 			iocbq->iocb.ulpBdeCount++;
17736 			/* We need to get the size out of the right CQE */
17737 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17738 			len = bf_get(lpfc_rcqe_length,
17739 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
17740 			pbde = (struct ulp_bde64 *)
17741 					&iocbq->iocb.unsli3.sli3Words[4];
17742 			if (len > LPFC_DATA_BUF_SIZE)
17743 				pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
17744 			else
17745 				pbde->tus.f.bdeSize = len;
17746 
17747 			iocbq->iocb.unsli3.rcvsli3.acc_len += len;
17748 			tot_len += len;
17749 		} else {
17750 			iocbq = lpfc_sli_get_iocbq(vport->phba);
17751 			if (!iocbq) {
17752 				if (first_iocbq) {
17753 					first_iocbq->iocb.ulpStatus =
17754 							IOSTAT_FCP_RSP_ERROR;
17755 					first_iocbq->iocb.un.ulpWord[4] =
17756 							IOERR_NO_RESOURCES;
17757 				}
17758 				lpfc_in_buf_free(vport->phba, d_buf);
17759 				continue;
17760 			}
17761 			/* We need to get the size out of the right CQE */
17762 			hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17763 			len = bf_get(lpfc_rcqe_length,
17764 				       &hbq_buf->cq_event.cqe.rcqe_cmpl);
17765 			iocbq->context2 = d_buf;
17766 			iocbq->context3 = NULL;
17767 			iocbq->iocb.ulpBdeCount = 1;
17768 			if (len > LPFC_DATA_BUF_SIZE)
17769 				iocbq->iocb.un.cont64[0].tus.f.bdeSize =
17770 							LPFC_DATA_BUF_SIZE;
17771 			else
17772 				iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
17773 
17774 			tot_len += len;
17775 			iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
17776 
17777 			iocbq->iocb.un.rcvels.remoteID = sid;
17778 			list_add_tail(&iocbq->list, &first_iocbq->list);
17779 		}
17780 	}
17781 	return first_iocbq;
17782 }
17783 
17784 static void
17785 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
17786 			  struct hbq_dmabuf *seq_dmabuf)
17787 {
17788 	struct fc_frame_header *fc_hdr;
17789 	struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
17790 	struct lpfc_hba *phba = vport->phba;
17791 
17792 	fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
17793 	iocbq = lpfc_prep_seq(vport, seq_dmabuf);
17794 	if (!iocbq) {
17795 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17796 				"2707 Ring %d handler: Failed to allocate "
17797 				"iocb Rctl x%x Type x%x received\n",
17798 				LPFC_ELS_RING,
17799 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
17800 		return;
17801 	}
17802 	if (!lpfc_complete_unsol_iocb(phba,
17803 				      phba->sli4_hba.els_wq->pring,
17804 				      iocbq, fc_hdr->fh_r_ctl,
17805 				      fc_hdr->fh_type))
17806 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17807 				"2540 Ring %d handler: unexpected Rctl "
17808 				"x%x Type x%x received\n",
17809 				LPFC_ELS_RING,
17810 				fc_hdr->fh_r_ctl, fc_hdr->fh_type);
17811 
17812 	/* Free iocb created in lpfc_prep_seq */
17813 	list_for_each_entry_safe(curr_iocb, next_iocb,
17814 		&iocbq->list, list) {
17815 		list_del_init(&curr_iocb->list);
17816 		lpfc_sli_release_iocbq(phba, curr_iocb);
17817 	}
17818 	lpfc_sli_release_iocbq(phba, iocbq);
17819 }
17820 
17821 static void
17822 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
17823 			    struct lpfc_iocbq *rspiocb)
17824 {
17825 	struct lpfc_dmabuf *pcmd = cmdiocb->context2;
17826 
17827 	if (pcmd && pcmd->virt)
17828 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
17829 	kfree(pcmd);
17830 	lpfc_sli_release_iocbq(phba, cmdiocb);
17831 	lpfc_drain_txq(phba);
17832 }
17833 
17834 static void
17835 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
17836 			      struct hbq_dmabuf *dmabuf)
17837 {
17838 	struct fc_frame_header *fc_hdr;
17839 	struct lpfc_hba *phba = vport->phba;
17840 	struct lpfc_iocbq *iocbq = NULL;
17841 	union  lpfc_wqe *wqe;
17842 	struct lpfc_dmabuf *pcmd = NULL;
17843 	uint32_t frame_len;
17844 	int rc;
17845 	unsigned long iflags;
17846 
17847 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17848 	frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
17849 
17850 	/* Send the received frame back */
17851 	iocbq = lpfc_sli_get_iocbq(phba);
17852 	if (!iocbq) {
17853 		/* Queue cq event and wakeup worker thread to process it */
17854 		spin_lock_irqsave(&phba->hbalock, iflags);
17855 		list_add_tail(&dmabuf->cq_event.list,
17856 			      &phba->sli4_hba.sp_queue_event);
17857 		phba->hba_flag |= HBA_SP_QUEUE_EVT;
17858 		spin_unlock_irqrestore(&phba->hbalock, iflags);
17859 		lpfc_worker_wake_up(phba);
17860 		return;
17861 	}
17862 
17863 	/* Allocate buffer for command payload */
17864 	pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
17865 	if (pcmd)
17866 		pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
17867 					    &pcmd->phys);
17868 	if (!pcmd || !pcmd->virt)
17869 		goto exit;
17870 
17871 	INIT_LIST_HEAD(&pcmd->list);
17872 
17873 	/* copyin the payload */
17874 	memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
17875 
17876 	/* fill in BDE's for command */
17877 	iocbq->iocb.un.xseq64.bdl.addrHigh = putPaddrHigh(pcmd->phys);
17878 	iocbq->iocb.un.xseq64.bdl.addrLow = putPaddrLow(pcmd->phys);
17879 	iocbq->iocb.un.xseq64.bdl.bdeFlags = BUFF_TYPE_BDE_64;
17880 	iocbq->iocb.un.xseq64.bdl.bdeSize = frame_len;
17881 
17882 	iocbq->context2 = pcmd;
17883 	iocbq->vport = vport;
17884 	iocbq->iocb_flag &= ~LPFC_FIP_ELS_ID_MASK;
17885 	iocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
17886 
17887 	/*
17888 	 * Setup rest of the iocb as though it were a WQE
17889 	 * Build the SEND_FRAME WQE
17890 	 */
17891 	wqe = (union lpfc_wqe *)&iocbq->iocb;
17892 
17893 	wqe->send_frame.frame_len = frame_len;
17894 	wqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((uint32_t *)fc_hdr));
17895 	wqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((uint32_t *)fc_hdr + 1));
17896 	wqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((uint32_t *)fc_hdr + 2));
17897 	wqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((uint32_t *)fc_hdr + 3));
17898 	wqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((uint32_t *)fc_hdr + 4));
17899 	wqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((uint32_t *)fc_hdr + 5));
17900 
17901 	iocbq->iocb.ulpCommand = CMD_SEND_FRAME;
17902 	iocbq->iocb.ulpLe = 1;
17903 	iocbq->iocb_cmpl = lpfc_sli4_mds_loopback_cmpl;
17904 	rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
17905 	if (rc == IOCB_ERROR)
17906 		goto exit;
17907 
17908 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
17909 	return;
17910 
17911 exit:
17912 	lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
17913 			"2023 Unable to process MDS loopback frame\n");
17914 	if (pcmd && pcmd->virt)
17915 		dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
17916 	kfree(pcmd);
17917 	if (iocbq)
17918 		lpfc_sli_release_iocbq(phba, iocbq);
17919 	lpfc_in_buf_free(phba, &dmabuf->dbuf);
17920 }
17921 
17922 /**
17923  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
17924  * @phba: Pointer to HBA context object.
17925  *
17926  * This function is called with no lock held. This function processes all
17927  * the received buffers and gives it to upper layers when a received buffer
17928  * indicates that it is the final frame in the sequence. The interrupt
17929  * service routine processes received buffers at interrupt contexts.
17930  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
17931  * appropriate receive function when the final frame in a sequence is received.
17932  **/
17933 void
17934 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
17935 				 struct hbq_dmabuf *dmabuf)
17936 {
17937 	struct hbq_dmabuf *seq_dmabuf;
17938 	struct fc_frame_header *fc_hdr;
17939 	struct lpfc_vport *vport;
17940 	uint32_t fcfi;
17941 	uint32_t did;
17942 
17943 	/* Process each received buffer */
17944 	fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17945 
17946 	if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
17947 	    fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
17948 		vport = phba->pport;
17949 		/* Handle MDS Loopback frames */
17950 		lpfc_sli4_handle_mds_loopback(vport, dmabuf);
17951 		return;
17952 	}
17953 
17954 	/* check to see if this a valid type of frame */
17955 	if (lpfc_fc_frame_check(phba, fc_hdr)) {
17956 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
17957 		return;
17958 	}
17959 
17960 	if ((bf_get(lpfc_cqe_code,
17961 		    &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
17962 		fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
17963 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
17964 	else
17965 		fcfi = bf_get(lpfc_rcqe_fcf_id,
17966 			      &dmabuf->cq_event.cqe.rcqe_cmpl);
17967 
17968 	/* d_id this frame is directed to */
17969 	did = sli4_did_from_fc_hdr(fc_hdr);
17970 
17971 	vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
17972 	if (!vport) {
17973 		/* throw out the frame */
17974 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
17975 		return;
17976 	}
17977 
17978 	/* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
17979 	if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
17980 		(did != Fabric_DID)) {
17981 		/*
17982 		 * Throw out the frame if we are not pt2pt.
17983 		 * The pt2pt protocol allows for discovery frames
17984 		 * to be received without a registered VPI.
17985 		 */
17986 		if (!(vport->fc_flag & FC_PT2PT) ||
17987 			(phba->link_state == LPFC_HBA_READY)) {
17988 			lpfc_in_buf_free(phba, &dmabuf->dbuf);
17989 			return;
17990 		}
17991 	}
17992 
17993 	/* Handle the basic abort sequence (BA_ABTS) event */
17994 	if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
17995 		lpfc_sli4_handle_unsol_abort(vport, dmabuf);
17996 		return;
17997 	}
17998 
17999 	/* Link this frame */
18000 	seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
18001 	if (!seq_dmabuf) {
18002 		/* unable to add frame to vport - throw it out */
18003 		lpfc_in_buf_free(phba, &dmabuf->dbuf);
18004 		return;
18005 	}
18006 	/* If not last frame in sequence continue processing frames. */
18007 	if (!lpfc_seq_complete(seq_dmabuf))
18008 		return;
18009 
18010 	/* Send the complete sequence to the upper layer protocol */
18011 	lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
18012 }
18013 
18014 /**
18015  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
18016  * @phba: pointer to lpfc hba data structure.
18017  *
18018  * This routine is invoked to post rpi header templates to the
18019  * HBA consistent with the SLI-4 interface spec.  This routine
18020  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18021  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18022  *
18023  * This routine does not require any locks.  It's usage is expected
18024  * to be driver load or reset recovery when the driver is
18025  * sequential.
18026  *
18027  * Return codes
18028  * 	0 - successful
18029  *      -EIO - The mailbox failed to complete successfully.
18030  * 	When this error occurs, the driver is not guaranteed
18031  *	to have any rpi regions posted to the device and
18032  *	must either attempt to repost the regions or take a
18033  *	fatal error.
18034  **/
18035 int
18036 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
18037 {
18038 	struct lpfc_rpi_hdr *rpi_page;
18039 	uint32_t rc = 0;
18040 	uint16_t lrpi = 0;
18041 
18042 	/* SLI4 ports that support extents do not require RPI headers. */
18043 	if (!phba->sli4_hba.rpi_hdrs_in_use)
18044 		goto exit;
18045 	if (phba->sli4_hba.extents_in_use)
18046 		return -EIO;
18047 
18048 	list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
18049 		/*
18050 		 * Assign the rpi headers a physical rpi only if the driver
18051 		 * has not initialized those resources.  A port reset only
18052 		 * needs the headers posted.
18053 		 */
18054 		if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
18055 		    LPFC_RPI_RSRC_RDY)
18056 			rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18057 
18058 		rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
18059 		if (rc != MBX_SUCCESS) {
18060 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18061 					"2008 Error %d posting all rpi "
18062 					"headers\n", rc);
18063 			rc = -EIO;
18064 			break;
18065 		}
18066 	}
18067 
18068  exit:
18069 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
18070 	       LPFC_RPI_RSRC_RDY);
18071 	return rc;
18072 }
18073 
18074 /**
18075  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
18076  * @phba: pointer to lpfc hba data structure.
18077  * @rpi_page:  pointer to the rpi memory region.
18078  *
18079  * This routine is invoked to post a single rpi header to the
18080  * HBA consistent with the SLI-4 interface spec.  This memory region
18081  * maps up to 64 rpi context regions.
18082  *
18083  * Return codes
18084  * 	0 - successful
18085  * 	-ENOMEM - No available memory
18086  *      -EIO - The mailbox failed to complete successfully.
18087  **/
18088 int
18089 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
18090 {
18091 	LPFC_MBOXQ_t *mboxq;
18092 	struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
18093 	uint32_t rc = 0;
18094 	uint32_t shdr_status, shdr_add_status;
18095 	union lpfc_sli4_cfg_shdr *shdr;
18096 
18097 	/* SLI4 ports that support extents do not require RPI headers. */
18098 	if (!phba->sli4_hba.rpi_hdrs_in_use)
18099 		return rc;
18100 	if (phba->sli4_hba.extents_in_use)
18101 		return -EIO;
18102 
18103 	/* The port is notified of the header region via a mailbox command. */
18104 	mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18105 	if (!mboxq) {
18106 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18107 				"2001 Unable to allocate memory for issuing "
18108 				"SLI_CONFIG_SPECIAL mailbox command\n");
18109 		return -ENOMEM;
18110 	}
18111 
18112 	/* Post all rpi memory regions to the port. */
18113 	hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
18114 	lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
18115 			 LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
18116 			 sizeof(struct lpfc_mbx_post_hdr_tmpl) -
18117 			 sizeof(struct lpfc_sli4_cfg_mhdr),
18118 			 LPFC_SLI4_MBX_EMBED);
18119 
18120 
18121 	/* Post the physical rpi to the port for this rpi header. */
18122 	bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
18123 	       rpi_page->start_rpi);
18124 	bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
18125 	       hdr_tmpl, rpi_page->page_count);
18126 
18127 	hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
18128 	hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
18129 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
18130 	shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
18131 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18132 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18133 	if (rc != MBX_TIMEOUT)
18134 		mempool_free(mboxq, phba->mbox_mem_pool);
18135 	if (shdr_status || shdr_add_status || rc) {
18136 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18137 				"2514 POST_RPI_HDR mailbox failed with "
18138 				"status x%x add_status x%x, mbx status x%x\n",
18139 				shdr_status, shdr_add_status, rc);
18140 		rc = -ENXIO;
18141 	} else {
18142 		/*
18143 		 * The next_rpi stores the next logical module-64 rpi value used
18144 		 * to post physical rpis in subsequent rpi postings.
18145 		 */
18146 		spin_lock_irq(&phba->hbalock);
18147 		phba->sli4_hba.next_rpi = rpi_page->next_rpi;
18148 		spin_unlock_irq(&phba->hbalock);
18149 	}
18150 	return rc;
18151 }
18152 
18153 /**
18154  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
18155  * @phba: pointer to lpfc hba data structure.
18156  *
18157  * This routine is invoked to post rpi header templates to the
18158  * HBA consistent with the SLI-4 interface spec.  This routine
18159  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18160  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18161  *
18162  * Returns
18163  * 	A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
18164  * 	LPFC_RPI_ALLOC_ERROR if no rpis are available.
18165  **/
18166 int
18167 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
18168 {
18169 	unsigned long rpi;
18170 	uint16_t max_rpi, rpi_limit;
18171 	uint16_t rpi_remaining, lrpi = 0;
18172 	struct lpfc_rpi_hdr *rpi_hdr;
18173 	unsigned long iflag;
18174 
18175 	/*
18176 	 * Fetch the next logical rpi.  Because this index is logical,
18177 	 * the  driver starts at 0 each time.
18178 	 */
18179 	spin_lock_irqsave(&phba->hbalock, iflag);
18180 	max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
18181 	rpi_limit = phba->sli4_hba.next_rpi;
18182 
18183 	rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
18184 	if (rpi >= rpi_limit)
18185 		rpi = LPFC_RPI_ALLOC_ERROR;
18186 	else {
18187 		set_bit(rpi, phba->sli4_hba.rpi_bmask);
18188 		phba->sli4_hba.max_cfg_param.rpi_used++;
18189 		phba->sli4_hba.rpi_count++;
18190 	}
18191 	lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
18192 			"0001 rpi:%x max:%x lim:%x\n",
18193 			(int) rpi, max_rpi, rpi_limit);
18194 
18195 	/*
18196 	 * Don't try to allocate more rpi header regions if the device limit
18197 	 * has been exhausted.
18198 	 */
18199 	if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
18200 	    (phba->sli4_hba.rpi_count >= max_rpi)) {
18201 		spin_unlock_irqrestore(&phba->hbalock, iflag);
18202 		return rpi;
18203 	}
18204 
18205 	/*
18206 	 * RPI header postings are not required for SLI4 ports capable of
18207 	 * extents.
18208 	 */
18209 	if (!phba->sli4_hba.rpi_hdrs_in_use) {
18210 		spin_unlock_irqrestore(&phba->hbalock, iflag);
18211 		return rpi;
18212 	}
18213 
18214 	/*
18215 	 * If the driver is running low on rpi resources, allocate another
18216 	 * page now.  Note that the next_rpi value is used because
18217 	 * it represents how many are actually in use whereas max_rpi notes
18218 	 * how many are supported max by the device.
18219 	 */
18220 	rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
18221 	spin_unlock_irqrestore(&phba->hbalock, iflag);
18222 	if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
18223 		rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
18224 		if (!rpi_hdr) {
18225 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18226 					"2002 Error Could not grow rpi "
18227 					"count\n");
18228 		} else {
18229 			lrpi = rpi_hdr->start_rpi;
18230 			rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18231 			lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
18232 		}
18233 	}
18234 
18235 	return rpi;
18236 }
18237 
18238 /**
18239  * lpfc_sli4_free_rpi - Release an rpi for reuse.
18240  * @phba: pointer to lpfc hba data structure.
18241  *
18242  * This routine is invoked to release an rpi to the pool of
18243  * available rpis maintained by the driver.
18244  **/
18245 static void
18246 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
18247 {
18248 	if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
18249 		phba->sli4_hba.rpi_count--;
18250 		phba->sli4_hba.max_cfg_param.rpi_used--;
18251 	}
18252 }
18253 
18254 /**
18255  * lpfc_sli4_free_rpi - Release an rpi for reuse.
18256  * @phba: pointer to lpfc hba data structure.
18257  *
18258  * This routine is invoked to release an rpi to the pool of
18259  * available rpis maintained by the driver.
18260  **/
18261 void
18262 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
18263 {
18264 	spin_lock_irq(&phba->hbalock);
18265 	__lpfc_sli4_free_rpi(phba, rpi);
18266 	spin_unlock_irq(&phba->hbalock);
18267 }
18268 
18269 /**
18270  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
18271  * @phba: pointer to lpfc hba data structure.
18272  *
18273  * This routine is invoked to remove the memory region that
18274  * provided rpi via a bitmask.
18275  **/
18276 void
18277 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
18278 {
18279 	kfree(phba->sli4_hba.rpi_bmask);
18280 	kfree(phba->sli4_hba.rpi_ids);
18281 	bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
18282 }
18283 
18284 /**
18285  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
18286  * @phba: pointer to lpfc hba data structure.
18287  *
18288  * This routine is invoked to remove the memory region that
18289  * provided rpi via a bitmask.
18290  **/
18291 int
18292 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
18293 	void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
18294 {
18295 	LPFC_MBOXQ_t *mboxq;
18296 	struct lpfc_hba *phba = ndlp->phba;
18297 	int rc;
18298 
18299 	/* The port is notified of the header region via a mailbox command. */
18300 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18301 	if (!mboxq)
18302 		return -ENOMEM;
18303 
18304 	/* Post all rpi memory regions to the port. */
18305 	lpfc_resume_rpi(mboxq, ndlp);
18306 	if (cmpl) {
18307 		mboxq->mbox_cmpl = cmpl;
18308 		mboxq->ctx_buf = arg;
18309 		mboxq->ctx_ndlp = ndlp;
18310 	} else
18311 		mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
18312 	mboxq->vport = ndlp->vport;
18313 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18314 	if (rc == MBX_NOT_FINISHED) {
18315 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18316 				"2010 Resume RPI Mailbox failed "
18317 				"status %d, mbxStatus x%x\n", rc,
18318 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
18319 		mempool_free(mboxq, phba->mbox_mem_pool);
18320 		return -EIO;
18321 	}
18322 	return 0;
18323 }
18324 
18325 /**
18326  * lpfc_sli4_init_vpi - Initialize a vpi with the port
18327  * @vport: Pointer to the vport for which the vpi is being initialized
18328  *
18329  * This routine is invoked to activate a vpi with the port.
18330  *
18331  * Returns:
18332  *    0 success
18333  *    -Evalue otherwise
18334  **/
18335 int
18336 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
18337 {
18338 	LPFC_MBOXQ_t *mboxq;
18339 	int rc = 0;
18340 	int retval = MBX_SUCCESS;
18341 	uint32_t mbox_tmo;
18342 	struct lpfc_hba *phba = vport->phba;
18343 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18344 	if (!mboxq)
18345 		return -ENOMEM;
18346 	lpfc_init_vpi(phba, mboxq, vport->vpi);
18347 	mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
18348 	rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
18349 	if (rc != MBX_SUCCESS) {
18350 		lpfc_printf_vlog(vport, KERN_ERR, LOG_SLI,
18351 				"2022 INIT VPI Mailbox failed "
18352 				"status %d, mbxStatus x%x\n", rc,
18353 				bf_get(lpfc_mqe_status, &mboxq->u.mqe));
18354 		retval = -EIO;
18355 	}
18356 	if (rc != MBX_TIMEOUT)
18357 		mempool_free(mboxq, vport->phba->mbox_mem_pool);
18358 
18359 	return retval;
18360 }
18361 
18362 /**
18363  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
18364  * @phba: pointer to lpfc hba data structure.
18365  * @mboxq: Pointer to mailbox object.
18366  *
18367  * This routine is invoked to manually add a single FCF record. The caller
18368  * must pass a completely initialized FCF_Record.  This routine takes
18369  * care of the nonembedded mailbox operations.
18370  **/
18371 static void
18372 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
18373 {
18374 	void *virt_addr;
18375 	union lpfc_sli4_cfg_shdr *shdr;
18376 	uint32_t shdr_status, shdr_add_status;
18377 
18378 	virt_addr = mboxq->sge_array->addr[0];
18379 	/* The IOCTL status is embedded in the mailbox subheader. */
18380 	shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
18381 	shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18382 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18383 
18384 	if ((shdr_status || shdr_add_status) &&
18385 		(shdr_status != STATUS_FCF_IN_USE))
18386 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18387 			"2558 ADD_FCF_RECORD mailbox failed with "
18388 			"status x%x add_status x%x\n",
18389 			shdr_status, shdr_add_status);
18390 
18391 	lpfc_sli4_mbox_cmd_free(phba, mboxq);
18392 }
18393 
18394 /**
18395  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
18396  * @phba: pointer to lpfc hba data structure.
18397  * @fcf_record:  pointer to the initialized fcf record to add.
18398  *
18399  * This routine is invoked to manually add a single FCF record. The caller
18400  * must pass a completely initialized FCF_Record.  This routine takes
18401  * care of the nonembedded mailbox operations.
18402  **/
18403 int
18404 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
18405 {
18406 	int rc = 0;
18407 	LPFC_MBOXQ_t *mboxq;
18408 	uint8_t *bytep;
18409 	void *virt_addr;
18410 	struct lpfc_mbx_sge sge;
18411 	uint32_t alloc_len, req_len;
18412 	uint32_t fcfindex;
18413 
18414 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18415 	if (!mboxq) {
18416 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18417 			"2009 Failed to allocate mbox for ADD_FCF cmd\n");
18418 		return -ENOMEM;
18419 	}
18420 
18421 	req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
18422 		  sizeof(uint32_t);
18423 
18424 	/* Allocate DMA memory and set up the non-embedded mailbox command */
18425 	alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
18426 				     LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
18427 				     req_len, LPFC_SLI4_MBX_NEMBED);
18428 	if (alloc_len < req_len) {
18429 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18430 			"2523 Allocated DMA memory size (x%x) is "
18431 			"less than the requested DMA memory "
18432 			"size (x%x)\n", alloc_len, req_len);
18433 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
18434 		return -ENOMEM;
18435 	}
18436 
18437 	/*
18438 	 * Get the first SGE entry from the non-embedded DMA memory.  This
18439 	 * routine only uses a single SGE.
18440 	 */
18441 	lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
18442 	virt_addr = mboxq->sge_array->addr[0];
18443 	/*
18444 	 * Configure the FCF record for FCFI 0.  This is the driver's
18445 	 * hardcoded default and gets used in nonFIP mode.
18446 	 */
18447 	fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
18448 	bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
18449 	lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
18450 
18451 	/*
18452 	 * Copy the fcf_index and the FCF Record Data. The data starts after
18453 	 * the FCoE header plus word10. The data copy needs to be endian
18454 	 * correct.
18455 	 */
18456 	bytep += sizeof(uint32_t);
18457 	lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
18458 	mboxq->vport = phba->pport;
18459 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
18460 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18461 	if (rc == MBX_NOT_FINISHED) {
18462 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18463 			"2515 ADD_FCF_RECORD mailbox failed with "
18464 			"status 0x%x\n", rc);
18465 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
18466 		rc = -EIO;
18467 	} else
18468 		rc = 0;
18469 
18470 	return rc;
18471 }
18472 
18473 /**
18474  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
18475  * @phba: pointer to lpfc hba data structure.
18476  * @fcf_record:  pointer to the fcf record to write the default data.
18477  * @fcf_index: FCF table entry index.
18478  *
18479  * This routine is invoked to build the driver's default FCF record.  The
18480  * values used are hardcoded.  This routine handles memory initialization.
18481  *
18482  **/
18483 void
18484 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
18485 				struct fcf_record *fcf_record,
18486 				uint16_t fcf_index)
18487 {
18488 	memset(fcf_record, 0, sizeof(struct fcf_record));
18489 	fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
18490 	fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
18491 	fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
18492 	bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
18493 	bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
18494 	bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
18495 	bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
18496 	bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
18497 	bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
18498 	bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
18499 	bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
18500 	bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
18501 	bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
18502 	bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
18503 	bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
18504 	bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
18505 		LPFC_FCF_FPMA | LPFC_FCF_SPMA);
18506 	/* Set the VLAN bit map */
18507 	if (phba->valid_vlan) {
18508 		fcf_record->vlan_bitmap[phba->vlan_id / 8]
18509 			= 1 << (phba->vlan_id % 8);
18510 	}
18511 }
18512 
18513 /**
18514  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
18515  * @phba: pointer to lpfc hba data structure.
18516  * @fcf_index: FCF table entry offset.
18517  *
18518  * This routine is invoked to scan the entire FCF table by reading FCF
18519  * record and processing it one at a time starting from the @fcf_index
18520  * for initial FCF discovery or fast FCF failover rediscovery.
18521  *
18522  * Return 0 if the mailbox command is submitted successfully, none 0
18523  * otherwise.
18524  **/
18525 int
18526 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
18527 {
18528 	int rc = 0, error;
18529 	LPFC_MBOXQ_t *mboxq;
18530 
18531 	phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
18532 	phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
18533 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18534 	if (!mboxq) {
18535 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18536 				"2000 Failed to allocate mbox for "
18537 				"READ_FCF cmd\n");
18538 		error = -ENOMEM;
18539 		goto fail_fcf_scan;
18540 	}
18541 	/* Construct the read FCF record mailbox command */
18542 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
18543 	if (rc) {
18544 		error = -EINVAL;
18545 		goto fail_fcf_scan;
18546 	}
18547 	/* Issue the mailbox command asynchronously */
18548 	mboxq->vport = phba->pport;
18549 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
18550 
18551 	spin_lock_irq(&phba->hbalock);
18552 	phba->hba_flag |= FCF_TS_INPROG;
18553 	spin_unlock_irq(&phba->hbalock);
18554 
18555 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18556 	if (rc == MBX_NOT_FINISHED)
18557 		error = -EIO;
18558 	else {
18559 		/* Reset eligible FCF count for new scan */
18560 		if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
18561 			phba->fcf.eligible_fcf_cnt = 0;
18562 		error = 0;
18563 	}
18564 fail_fcf_scan:
18565 	if (error) {
18566 		if (mboxq)
18567 			lpfc_sli4_mbox_cmd_free(phba, mboxq);
18568 		/* FCF scan failed, clear FCF_TS_INPROG flag */
18569 		spin_lock_irq(&phba->hbalock);
18570 		phba->hba_flag &= ~FCF_TS_INPROG;
18571 		spin_unlock_irq(&phba->hbalock);
18572 	}
18573 	return error;
18574 }
18575 
18576 /**
18577  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
18578  * @phba: pointer to lpfc hba data structure.
18579  * @fcf_index: FCF table entry offset.
18580  *
18581  * This routine is invoked to read an FCF record indicated by @fcf_index
18582  * and to use it for FLOGI roundrobin FCF failover.
18583  *
18584  * Return 0 if the mailbox command is submitted successfully, none 0
18585  * otherwise.
18586  **/
18587 int
18588 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
18589 {
18590 	int rc = 0, error;
18591 	LPFC_MBOXQ_t *mboxq;
18592 
18593 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18594 	if (!mboxq) {
18595 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
18596 				"2763 Failed to allocate mbox for "
18597 				"READ_FCF cmd\n");
18598 		error = -ENOMEM;
18599 		goto fail_fcf_read;
18600 	}
18601 	/* Construct the read FCF record mailbox command */
18602 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
18603 	if (rc) {
18604 		error = -EINVAL;
18605 		goto fail_fcf_read;
18606 	}
18607 	/* Issue the mailbox command asynchronously */
18608 	mboxq->vport = phba->pport;
18609 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
18610 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18611 	if (rc == MBX_NOT_FINISHED)
18612 		error = -EIO;
18613 	else
18614 		error = 0;
18615 
18616 fail_fcf_read:
18617 	if (error && mboxq)
18618 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
18619 	return error;
18620 }
18621 
18622 /**
18623  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
18624  * @phba: pointer to lpfc hba data structure.
18625  * @fcf_index: FCF table entry offset.
18626  *
18627  * This routine is invoked to read an FCF record indicated by @fcf_index to
18628  * determine whether it's eligible for FLOGI roundrobin failover list.
18629  *
18630  * Return 0 if the mailbox command is submitted successfully, none 0
18631  * otherwise.
18632  **/
18633 int
18634 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
18635 {
18636 	int rc = 0, error;
18637 	LPFC_MBOXQ_t *mboxq;
18638 
18639 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18640 	if (!mboxq) {
18641 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
18642 				"2758 Failed to allocate mbox for "
18643 				"READ_FCF cmd\n");
18644 				error = -ENOMEM;
18645 				goto fail_fcf_read;
18646 	}
18647 	/* Construct the read FCF record mailbox command */
18648 	rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
18649 	if (rc) {
18650 		error = -EINVAL;
18651 		goto fail_fcf_read;
18652 	}
18653 	/* Issue the mailbox command asynchronously */
18654 	mboxq->vport = phba->pport;
18655 	mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
18656 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18657 	if (rc == MBX_NOT_FINISHED)
18658 		error = -EIO;
18659 	else
18660 		error = 0;
18661 
18662 fail_fcf_read:
18663 	if (error && mboxq)
18664 		lpfc_sli4_mbox_cmd_free(phba, mboxq);
18665 	return error;
18666 }
18667 
18668 /**
18669  * lpfc_check_next_fcf_pri_level
18670  * phba pointer to the lpfc_hba struct for this port.
18671  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
18672  * routine when the rr_bmask is empty. The FCF indecies are put into the
18673  * rr_bmask based on their priority level. Starting from the highest priority
18674  * to the lowest. The most likely FCF candidate will be in the highest
18675  * priority group. When this routine is called it searches the fcf_pri list for
18676  * next lowest priority group and repopulates the rr_bmask with only those
18677  * fcf_indexes.
18678  * returns:
18679  * 1=success 0=failure
18680  **/
18681 static int
18682 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
18683 {
18684 	uint16_t next_fcf_pri;
18685 	uint16_t last_index;
18686 	struct lpfc_fcf_pri *fcf_pri;
18687 	int rc;
18688 	int ret = 0;
18689 
18690 	last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
18691 			LPFC_SLI4_FCF_TBL_INDX_MAX);
18692 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
18693 			"3060 Last IDX %d\n", last_index);
18694 
18695 	/* Verify the priority list has 2 or more entries */
18696 	spin_lock_irq(&phba->hbalock);
18697 	if (list_empty(&phba->fcf.fcf_pri_list) ||
18698 	    list_is_singular(&phba->fcf.fcf_pri_list)) {
18699 		spin_unlock_irq(&phba->hbalock);
18700 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
18701 			"3061 Last IDX %d\n", last_index);
18702 		return 0; /* Empty rr list */
18703 	}
18704 	spin_unlock_irq(&phba->hbalock);
18705 
18706 	next_fcf_pri = 0;
18707 	/*
18708 	 * Clear the rr_bmask and set all of the bits that are at this
18709 	 * priority.
18710 	 */
18711 	memset(phba->fcf.fcf_rr_bmask, 0,
18712 			sizeof(*phba->fcf.fcf_rr_bmask));
18713 	spin_lock_irq(&phba->hbalock);
18714 	list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
18715 		if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
18716 			continue;
18717 		/*
18718 		 * the 1st priority that has not FLOGI failed
18719 		 * will be the highest.
18720 		 */
18721 		if (!next_fcf_pri)
18722 			next_fcf_pri = fcf_pri->fcf_rec.priority;
18723 		spin_unlock_irq(&phba->hbalock);
18724 		if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
18725 			rc = lpfc_sli4_fcf_rr_index_set(phba,
18726 						fcf_pri->fcf_rec.fcf_index);
18727 			if (rc)
18728 				return 0;
18729 		}
18730 		spin_lock_irq(&phba->hbalock);
18731 	}
18732 	/*
18733 	 * if next_fcf_pri was not set above and the list is not empty then
18734 	 * we have failed flogis on all of them. So reset flogi failed
18735 	 * and start at the beginning.
18736 	 */
18737 	if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
18738 		list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
18739 			fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
18740 			/*
18741 			 * the 1st priority that has not FLOGI failed
18742 			 * will be the highest.
18743 			 */
18744 			if (!next_fcf_pri)
18745 				next_fcf_pri = fcf_pri->fcf_rec.priority;
18746 			spin_unlock_irq(&phba->hbalock);
18747 			if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
18748 				rc = lpfc_sli4_fcf_rr_index_set(phba,
18749 						fcf_pri->fcf_rec.fcf_index);
18750 				if (rc)
18751 					return 0;
18752 			}
18753 			spin_lock_irq(&phba->hbalock);
18754 		}
18755 	} else
18756 		ret = 1;
18757 	spin_unlock_irq(&phba->hbalock);
18758 
18759 	return ret;
18760 }
18761 /**
18762  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
18763  * @phba: pointer to lpfc hba data structure.
18764  *
18765  * This routine is to get the next eligible FCF record index in a round
18766  * robin fashion. If the next eligible FCF record index equals to the
18767  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
18768  * shall be returned, otherwise, the next eligible FCF record's index
18769  * shall be returned.
18770  **/
18771 uint16_t
18772 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
18773 {
18774 	uint16_t next_fcf_index;
18775 
18776 initial_priority:
18777 	/* Search start from next bit of currently registered FCF index */
18778 	next_fcf_index = phba->fcf.current_rec.fcf_indx;
18779 
18780 next_priority:
18781 	/* Determine the next fcf index to check */
18782 	next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
18783 	next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
18784 				       LPFC_SLI4_FCF_TBL_INDX_MAX,
18785 				       next_fcf_index);
18786 
18787 	/* Wrap around condition on phba->fcf.fcf_rr_bmask */
18788 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
18789 		/*
18790 		 * If we have wrapped then we need to clear the bits that
18791 		 * have been tested so that we can detect when we should
18792 		 * change the priority level.
18793 		 */
18794 		next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
18795 					       LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
18796 	}
18797 
18798 
18799 	/* Check roundrobin failover list empty condition */
18800 	if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
18801 		next_fcf_index == phba->fcf.current_rec.fcf_indx) {
18802 		/*
18803 		 * If next fcf index is not found check if there are lower
18804 		 * Priority level fcf's in the fcf_priority list.
18805 		 * Set up the rr_bmask with all of the avaiable fcf bits
18806 		 * at that level and continue the selection process.
18807 		 */
18808 		if (lpfc_check_next_fcf_pri_level(phba))
18809 			goto initial_priority;
18810 		lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
18811 				"2844 No roundrobin failover FCF available\n");
18812 
18813 		return LPFC_FCOE_FCF_NEXT_NONE;
18814 	}
18815 
18816 	if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
18817 		phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
18818 		LPFC_FCF_FLOGI_FAILED) {
18819 		if (list_is_singular(&phba->fcf.fcf_pri_list))
18820 			return LPFC_FCOE_FCF_NEXT_NONE;
18821 
18822 		goto next_priority;
18823 	}
18824 
18825 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
18826 			"2845 Get next roundrobin failover FCF (x%x)\n",
18827 			next_fcf_index);
18828 
18829 	return next_fcf_index;
18830 }
18831 
18832 /**
18833  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
18834  * @phba: pointer to lpfc hba data structure.
18835  *
18836  * This routine sets the FCF record index in to the eligible bmask for
18837  * roundrobin failover search. It checks to make sure that the index
18838  * does not go beyond the range of the driver allocated bmask dimension
18839  * before setting the bit.
18840  *
18841  * Returns 0 if the index bit successfully set, otherwise, it returns
18842  * -EINVAL.
18843  **/
18844 int
18845 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
18846 {
18847 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
18848 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
18849 				"2610 FCF (x%x) reached driver's book "
18850 				"keeping dimension:x%x\n",
18851 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
18852 		return -EINVAL;
18853 	}
18854 	/* Set the eligible FCF record index bmask */
18855 	set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
18856 
18857 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
18858 			"2790 Set FCF (x%x) to roundrobin FCF failover "
18859 			"bmask\n", fcf_index);
18860 
18861 	return 0;
18862 }
18863 
18864 /**
18865  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
18866  * @phba: pointer to lpfc hba data structure.
18867  *
18868  * This routine clears the FCF record index from the eligible bmask for
18869  * roundrobin failover search. It checks to make sure that the index
18870  * does not go beyond the range of the driver allocated bmask dimension
18871  * before clearing the bit.
18872  **/
18873 void
18874 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
18875 {
18876 	struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
18877 	if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
18878 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
18879 				"2762 FCF (x%x) reached driver's book "
18880 				"keeping dimension:x%x\n",
18881 				fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
18882 		return;
18883 	}
18884 	/* Clear the eligible FCF record index bmask */
18885 	spin_lock_irq(&phba->hbalock);
18886 	list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
18887 				 list) {
18888 		if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
18889 			list_del_init(&fcf_pri->list);
18890 			break;
18891 		}
18892 	}
18893 	spin_unlock_irq(&phba->hbalock);
18894 	clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
18895 
18896 	lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
18897 			"2791 Clear FCF (x%x) from roundrobin failover "
18898 			"bmask\n", fcf_index);
18899 }
18900 
18901 /**
18902  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
18903  * @phba: pointer to lpfc hba data structure.
18904  *
18905  * This routine is the completion routine for the rediscover FCF table mailbox
18906  * command. If the mailbox command returned failure, it will try to stop the
18907  * FCF rediscover wait timer.
18908  **/
18909 static void
18910 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
18911 {
18912 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
18913 	uint32_t shdr_status, shdr_add_status;
18914 
18915 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
18916 
18917 	shdr_status = bf_get(lpfc_mbox_hdr_status,
18918 			     &redisc_fcf->header.cfg_shdr.response);
18919 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
18920 			     &redisc_fcf->header.cfg_shdr.response);
18921 	if (shdr_status || shdr_add_status) {
18922 		lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
18923 				"2746 Requesting for FCF rediscovery failed "
18924 				"status x%x add_status x%x\n",
18925 				shdr_status, shdr_add_status);
18926 		if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
18927 			spin_lock_irq(&phba->hbalock);
18928 			phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
18929 			spin_unlock_irq(&phba->hbalock);
18930 			/*
18931 			 * CVL event triggered FCF rediscover request failed,
18932 			 * last resort to re-try current registered FCF entry.
18933 			 */
18934 			lpfc_retry_pport_discovery(phba);
18935 		} else {
18936 			spin_lock_irq(&phba->hbalock);
18937 			phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
18938 			spin_unlock_irq(&phba->hbalock);
18939 			/*
18940 			 * DEAD FCF event triggered FCF rediscover request
18941 			 * failed, last resort to fail over as a link down
18942 			 * to FCF registration.
18943 			 */
18944 			lpfc_sli4_fcf_dead_failthrough(phba);
18945 		}
18946 	} else {
18947 		lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
18948 				"2775 Start FCF rediscover quiescent timer\n");
18949 		/*
18950 		 * Start FCF rediscovery wait timer for pending FCF
18951 		 * before rescan FCF record table.
18952 		 */
18953 		lpfc_fcf_redisc_wait_start_timer(phba);
18954 	}
18955 
18956 	mempool_free(mbox, phba->mbox_mem_pool);
18957 }
18958 
18959 /**
18960  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
18961  * @phba: pointer to lpfc hba data structure.
18962  *
18963  * This routine is invoked to request for rediscovery of the entire FCF table
18964  * by the port.
18965  **/
18966 int
18967 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
18968 {
18969 	LPFC_MBOXQ_t *mbox;
18970 	struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
18971 	int rc, length;
18972 
18973 	/* Cancel retry delay timers to all vports before FCF rediscover */
18974 	lpfc_cancel_all_vport_retry_delay_timer(phba);
18975 
18976 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18977 	if (!mbox) {
18978 		lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18979 				"2745 Failed to allocate mbox for "
18980 				"requesting FCF rediscover.\n");
18981 		return -ENOMEM;
18982 	}
18983 
18984 	length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
18985 		  sizeof(struct lpfc_sli4_cfg_mhdr));
18986 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18987 			 LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
18988 			 length, LPFC_SLI4_MBX_EMBED);
18989 
18990 	redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
18991 	/* Set count to 0 for invalidating the entire FCF database */
18992 	bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
18993 
18994 	/* Issue the mailbox command asynchronously */
18995 	mbox->vport = phba->pport;
18996 	mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
18997 	rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
18998 
18999 	if (rc == MBX_NOT_FINISHED) {
19000 		mempool_free(mbox, phba->mbox_mem_pool);
19001 		return -EIO;
19002 	}
19003 	return 0;
19004 }
19005 
19006 /**
19007  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
19008  * @phba: pointer to lpfc hba data structure.
19009  *
19010  * This function is the failover routine as a last resort to the FCF DEAD
19011  * event when driver failed to perform fast FCF failover.
19012  **/
19013 void
19014 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
19015 {
19016 	uint32_t link_state;
19017 
19018 	/*
19019 	 * Last resort as FCF DEAD event failover will treat this as
19020 	 * a link down, but save the link state because we don't want
19021 	 * it to be changed to Link Down unless it is already down.
19022 	 */
19023 	link_state = phba->link_state;
19024 	lpfc_linkdown(phba);
19025 	phba->link_state = link_state;
19026 
19027 	/* Unregister FCF if no devices connected to it */
19028 	lpfc_unregister_unused_fcf(phba);
19029 }
19030 
19031 /**
19032  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
19033  * @phba: pointer to lpfc hba data structure.
19034  * @rgn23_data: pointer to configure region 23 data.
19035  *
19036  * This function gets SLI3 port configure region 23 data through memory dump
19037  * mailbox command. When it successfully retrieves data, the size of the data
19038  * will be returned, otherwise, 0 will be returned.
19039  **/
19040 static uint32_t
19041 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19042 {
19043 	LPFC_MBOXQ_t *pmb = NULL;
19044 	MAILBOX_t *mb;
19045 	uint32_t offset = 0;
19046 	int rc;
19047 
19048 	if (!rgn23_data)
19049 		return 0;
19050 
19051 	pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19052 	if (!pmb) {
19053 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19054 				"2600 failed to allocate mailbox memory\n");
19055 		return 0;
19056 	}
19057 	mb = &pmb->u.mb;
19058 
19059 	do {
19060 		lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
19061 		rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
19062 
19063 		if (rc != MBX_SUCCESS) {
19064 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19065 					"2601 failed to read config "
19066 					"region 23, rc 0x%x Status 0x%x\n",
19067 					rc, mb->mbxStatus);
19068 			mb->un.varDmp.word_cnt = 0;
19069 		}
19070 		/*
19071 		 * dump mem may return a zero when finished or we got a
19072 		 * mailbox error, either way we are done.
19073 		 */
19074 		if (mb->un.varDmp.word_cnt == 0)
19075 			break;
19076 		if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
19077 			mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
19078 
19079 		lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
19080 				       rgn23_data + offset,
19081 				       mb->un.varDmp.word_cnt);
19082 		offset += mb->un.varDmp.word_cnt;
19083 	} while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
19084 
19085 	mempool_free(pmb, phba->mbox_mem_pool);
19086 	return offset;
19087 }
19088 
19089 /**
19090  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
19091  * @phba: pointer to lpfc hba data structure.
19092  * @rgn23_data: pointer to configure region 23 data.
19093  *
19094  * This function gets SLI4 port configure region 23 data through memory dump
19095  * mailbox command. When it successfully retrieves data, the size of the data
19096  * will be returned, otherwise, 0 will be returned.
19097  **/
19098 static uint32_t
19099 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19100 {
19101 	LPFC_MBOXQ_t *mboxq = NULL;
19102 	struct lpfc_dmabuf *mp = NULL;
19103 	struct lpfc_mqe *mqe;
19104 	uint32_t data_length = 0;
19105 	int rc;
19106 
19107 	if (!rgn23_data)
19108 		return 0;
19109 
19110 	mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19111 	if (!mboxq) {
19112 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19113 				"3105 failed to allocate mailbox memory\n");
19114 		return 0;
19115 	}
19116 
19117 	if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
19118 		goto out;
19119 	mqe = &mboxq->u.mqe;
19120 	mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
19121 	rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19122 	if (rc)
19123 		goto out;
19124 	data_length = mqe->un.mb_words[5];
19125 	if (data_length == 0)
19126 		goto out;
19127 	if (data_length > DMP_RGN23_SIZE) {
19128 		data_length = 0;
19129 		goto out;
19130 	}
19131 	lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
19132 out:
19133 	mempool_free(mboxq, phba->mbox_mem_pool);
19134 	if (mp) {
19135 		lpfc_mbuf_free(phba, mp->virt, mp->phys);
19136 		kfree(mp);
19137 	}
19138 	return data_length;
19139 }
19140 
19141 /**
19142  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
19143  * @phba: pointer to lpfc hba data structure.
19144  *
19145  * This function read region 23 and parse TLV for port status to
19146  * decide if the user disaled the port. If the TLV indicates the
19147  * port is disabled, the hba_flag is set accordingly.
19148  **/
19149 void
19150 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
19151 {
19152 	uint8_t *rgn23_data = NULL;
19153 	uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
19154 	uint32_t offset = 0;
19155 
19156 	/* Get adapter Region 23 data */
19157 	rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
19158 	if (!rgn23_data)
19159 		goto out;
19160 
19161 	if (phba->sli_rev < LPFC_SLI_REV4)
19162 		data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
19163 	else {
19164 		if_type = bf_get(lpfc_sli_intf_if_type,
19165 				 &phba->sli4_hba.sli_intf);
19166 		if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
19167 			goto out;
19168 		data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
19169 	}
19170 
19171 	if (!data_size)
19172 		goto out;
19173 
19174 	/* Check the region signature first */
19175 	if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
19176 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19177 			"2619 Config region 23 has bad signature\n");
19178 			goto out;
19179 	}
19180 	offset += 4;
19181 
19182 	/* Check the data structure version */
19183 	if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
19184 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19185 			"2620 Config region 23 has bad version\n");
19186 		goto out;
19187 	}
19188 	offset += 4;
19189 
19190 	/* Parse TLV entries in the region */
19191 	while (offset < data_size) {
19192 		if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
19193 			break;
19194 		/*
19195 		 * If the TLV is not driver specific TLV or driver id is
19196 		 * not linux driver id, skip the record.
19197 		 */
19198 		if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
19199 		    (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
19200 		    (rgn23_data[offset + 3] != 0)) {
19201 			offset += rgn23_data[offset + 1] * 4 + 4;
19202 			continue;
19203 		}
19204 
19205 		/* Driver found a driver specific TLV in the config region */
19206 		sub_tlv_len = rgn23_data[offset + 1] * 4;
19207 		offset += 4;
19208 		tlv_offset = 0;
19209 
19210 		/*
19211 		 * Search for configured port state sub-TLV.
19212 		 */
19213 		while ((offset < data_size) &&
19214 			(tlv_offset < sub_tlv_len)) {
19215 			if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
19216 				offset += 4;
19217 				tlv_offset += 4;
19218 				break;
19219 			}
19220 			if (rgn23_data[offset] != PORT_STE_TYPE) {
19221 				offset += rgn23_data[offset + 1] * 4 + 4;
19222 				tlv_offset += rgn23_data[offset + 1] * 4 + 4;
19223 				continue;
19224 			}
19225 
19226 			/* This HBA contains PORT_STE configured */
19227 			if (!rgn23_data[offset + 2])
19228 				phba->hba_flag |= LINK_DISABLED;
19229 
19230 			goto out;
19231 		}
19232 	}
19233 
19234 out:
19235 	kfree(rgn23_data);
19236 	return;
19237 }
19238 
19239 /**
19240  * lpfc_wr_object - write an object to the firmware
19241  * @phba: HBA structure that indicates port to create a queue on.
19242  * @dmabuf_list: list of dmabufs to write to the port.
19243  * @size: the total byte value of the objects to write to the port.
19244  * @offset: the current offset to be used to start the transfer.
19245  *
19246  * This routine will create a wr_object mailbox command to send to the port.
19247  * the mailbox command will be constructed using the dma buffers described in
19248  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
19249  * BDEs that the imbedded mailbox can support. The @offset variable will be
19250  * used to indicate the starting offset of the transfer and will also return
19251  * the offset after the write object mailbox has completed. @size is used to
19252  * determine the end of the object and whether the eof bit should be set.
19253  *
19254  * Return 0 is successful and offset will contain the the new offset to use
19255  * for the next write.
19256  * Return negative value for error cases.
19257  **/
19258 int
19259 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
19260 	       uint32_t size, uint32_t *offset)
19261 {
19262 	struct lpfc_mbx_wr_object *wr_object;
19263 	LPFC_MBOXQ_t *mbox;
19264 	int rc = 0, i = 0;
19265 	uint32_t shdr_status, shdr_add_status, shdr_change_status;
19266 	uint32_t mbox_tmo;
19267 	struct lpfc_dmabuf *dmabuf;
19268 	uint32_t written = 0;
19269 	bool check_change_status = false;
19270 
19271 	mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19272 	if (!mbox)
19273 		return -ENOMEM;
19274 
19275 	lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
19276 			LPFC_MBOX_OPCODE_WRITE_OBJECT,
19277 			sizeof(struct lpfc_mbx_wr_object) -
19278 			sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
19279 
19280 	wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
19281 	wr_object->u.request.write_offset = *offset;
19282 	sprintf((uint8_t *)wr_object->u.request.object_name, "/");
19283 	wr_object->u.request.object_name[0] =
19284 		cpu_to_le32(wr_object->u.request.object_name[0]);
19285 	bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
19286 	list_for_each_entry(dmabuf, dmabuf_list, list) {
19287 		if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
19288 			break;
19289 		wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
19290 		wr_object->u.request.bde[i].addrHigh =
19291 			putPaddrHigh(dmabuf->phys);
19292 		if (written + SLI4_PAGE_SIZE >= size) {
19293 			wr_object->u.request.bde[i].tus.f.bdeSize =
19294 				(size - written);
19295 			written += (size - written);
19296 			bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
19297 			bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
19298 			check_change_status = true;
19299 		} else {
19300 			wr_object->u.request.bde[i].tus.f.bdeSize =
19301 				SLI4_PAGE_SIZE;
19302 			written += SLI4_PAGE_SIZE;
19303 		}
19304 		i++;
19305 	}
19306 	wr_object->u.request.bde_count = i;
19307 	bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
19308 	if (!phba->sli4_hba.intr_enable)
19309 		rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
19310 	else {
19311 		mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
19312 		rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
19313 	}
19314 	/* The IOCTL status is embedded in the mailbox subheader. */
19315 	shdr_status = bf_get(lpfc_mbox_hdr_status,
19316 			     &wr_object->header.cfg_shdr.response);
19317 	shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
19318 				 &wr_object->header.cfg_shdr.response);
19319 	if (check_change_status) {
19320 		shdr_change_status = bf_get(lpfc_wr_object_change_status,
19321 					    &wr_object->u.response);
19322 		switch (shdr_change_status) {
19323 		case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
19324 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19325 					"3198 Firmware write complete: System "
19326 					"reboot required to instantiate\n");
19327 			break;
19328 		case (LPFC_CHANGE_STATUS_FW_RESET):
19329 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19330 					"3199 Firmware write complete: Firmware"
19331 					" reset required to instantiate\n");
19332 			break;
19333 		case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
19334 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19335 					"3200 Firmware write complete: Port "
19336 					"Migration or PCI Reset required to "
19337 					"instantiate\n");
19338 			break;
19339 		case (LPFC_CHANGE_STATUS_PCI_RESET):
19340 			lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19341 					"3201 Firmware write complete: PCI "
19342 					"Reset required to instantiate\n");
19343 			break;
19344 		default:
19345 			break;
19346 		}
19347 	}
19348 	if (rc != MBX_TIMEOUT)
19349 		mempool_free(mbox, phba->mbox_mem_pool);
19350 	if (shdr_status || shdr_add_status || rc) {
19351 		lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19352 				"3025 Write Object mailbox failed with "
19353 				"status x%x add_status x%x, mbx status x%x\n",
19354 				shdr_status, shdr_add_status, rc);
19355 		rc = -ENXIO;
19356 		*offset = shdr_add_status;
19357 	} else
19358 		*offset += wr_object->u.response.actual_write_length;
19359 	return rc;
19360 }
19361 
19362 /**
19363  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
19364  * @vport: pointer to vport data structure.
19365  *
19366  * This function iterate through the mailboxq and clean up all REG_LOGIN
19367  * and REG_VPI mailbox commands associated with the vport. This function
19368  * is called when driver want to restart discovery of the vport due to
19369  * a Clear Virtual Link event.
19370  **/
19371 void
19372 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
19373 {
19374 	struct lpfc_hba *phba = vport->phba;
19375 	LPFC_MBOXQ_t *mb, *nextmb;
19376 	struct lpfc_dmabuf *mp;
19377 	struct lpfc_nodelist *ndlp;
19378 	struct lpfc_nodelist *act_mbx_ndlp = NULL;
19379 	struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
19380 	LIST_HEAD(mbox_cmd_list);
19381 	uint8_t restart_loop;
19382 
19383 	/* Clean up internally queued mailbox commands with the vport */
19384 	spin_lock_irq(&phba->hbalock);
19385 	list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
19386 		if (mb->vport != vport)
19387 			continue;
19388 
19389 		if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
19390 			(mb->u.mb.mbxCommand != MBX_REG_VPI))
19391 			continue;
19392 
19393 		list_del(&mb->list);
19394 		list_add_tail(&mb->list, &mbox_cmd_list);
19395 	}
19396 	/* Clean up active mailbox command with the vport */
19397 	mb = phba->sli.mbox_active;
19398 	if (mb && (mb->vport == vport)) {
19399 		if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
19400 			(mb->u.mb.mbxCommand == MBX_REG_VPI))
19401 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19402 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19403 			act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19404 			/* Put reference count for delayed processing */
19405 			act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
19406 			/* Unregister the RPI when mailbox complete */
19407 			mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
19408 		}
19409 	}
19410 	/* Cleanup any mailbox completions which are not yet processed */
19411 	do {
19412 		restart_loop = 0;
19413 		list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
19414 			/*
19415 			 * If this mailox is already processed or it is
19416 			 * for another vport ignore it.
19417 			 */
19418 			if ((mb->vport != vport) ||
19419 				(mb->mbox_flag & LPFC_MBX_IMED_UNREG))
19420 				continue;
19421 
19422 			if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
19423 				(mb->u.mb.mbxCommand != MBX_REG_VPI))
19424 				continue;
19425 
19426 			mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19427 			if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19428 				ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19429 				/* Unregister the RPI when mailbox complete */
19430 				mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
19431 				restart_loop = 1;
19432 				spin_unlock_irq(&phba->hbalock);
19433 				spin_lock(shost->host_lock);
19434 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19435 				spin_unlock(shost->host_lock);
19436 				spin_lock_irq(&phba->hbalock);
19437 				break;
19438 			}
19439 		}
19440 	} while (restart_loop);
19441 
19442 	spin_unlock_irq(&phba->hbalock);
19443 
19444 	/* Release the cleaned-up mailbox commands */
19445 	while (!list_empty(&mbox_cmd_list)) {
19446 		list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
19447 		if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19448 			mp = (struct lpfc_dmabuf *)(mb->ctx_buf);
19449 			if (mp) {
19450 				__lpfc_mbuf_free(phba, mp->virt, mp->phys);
19451 				kfree(mp);
19452 			}
19453 			mb->ctx_buf = NULL;
19454 			ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19455 			mb->ctx_ndlp = NULL;
19456 			if (ndlp) {
19457 				spin_lock(shost->host_lock);
19458 				ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19459 				spin_unlock(shost->host_lock);
19460 				lpfc_nlp_put(ndlp);
19461 			}
19462 		}
19463 		mempool_free(mb, phba->mbox_mem_pool);
19464 	}
19465 
19466 	/* Release the ndlp with the cleaned-up active mailbox command */
19467 	if (act_mbx_ndlp) {
19468 		spin_lock(shost->host_lock);
19469 		act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19470 		spin_unlock(shost->host_lock);
19471 		lpfc_nlp_put(act_mbx_ndlp);
19472 	}
19473 }
19474 
19475 /**
19476  * lpfc_drain_txq - Drain the txq
19477  * @phba: Pointer to HBA context object.
19478  *
19479  * This function attempt to submit IOCBs on the txq
19480  * to the adapter.  For SLI4 adapters, the txq contains
19481  * ELS IOCBs that have been deferred because the there
19482  * are no SGLs.  This congestion can occur with large
19483  * vport counts during node discovery.
19484  **/
19485 
19486 uint32_t
19487 lpfc_drain_txq(struct lpfc_hba *phba)
19488 {
19489 	LIST_HEAD(completions);
19490 	struct lpfc_sli_ring *pring;
19491 	struct lpfc_iocbq *piocbq = NULL;
19492 	unsigned long iflags = 0;
19493 	char *fail_msg = NULL;
19494 	struct lpfc_sglq *sglq;
19495 	union lpfc_wqe128 wqe;
19496 	uint32_t txq_cnt = 0;
19497 	struct lpfc_queue *wq;
19498 
19499 	if (phba->link_flag & LS_MDS_LOOPBACK) {
19500 		/* MDS WQE are posted only to first WQ*/
19501 		wq = phba->sli4_hba.fcp_wq[0];
19502 		if (unlikely(!wq))
19503 			return 0;
19504 		pring = wq->pring;
19505 	} else {
19506 		wq = phba->sli4_hba.els_wq;
19507 		if (unlikely(!wq))
19508 			return 0;
19509 		pring = lpfc_phba_elsring(phba);
19510 	}
19511 
19512 	if (unlikely(!pring) || list_empty(&pring->txq))
19513 		return 0;
19514 
19515 	spin_lock_irqsave(&pring->ring_lock, iflags);
19516 	list_for_each_entry(piocbq, &pring->txq, list) {
19517 		txq_cnt++;
19518 	}
19519 
19520 	if (txq_cnt > pring->txq_max)
19521 		pring->txq_max = txq_cnt;
19522 
19523 	spin_unlock_irqrestore(&pring->ring_lock, iflags);
19524 
19525 	while (!list_empty(&pring->txq)) {
19526 		spin_lock_irqsave(&pring->ring_lock, iflags);
19527 
19528 		piocbq = lpfc_sli_ringtx_get(phba, pring);
19529 		if (!piocbq) {
19530 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19531 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
19532 				"2823 txq empty and txq_cnt is %d\n ",
19533 				txq_cnt);
19534 			break;
19535 		}
19536 		sglq = __lpfc_sli_get_els_sglq(phba, piocbq);
19537 		if (!sglq) {
19538 			__lpfc_sli_ringtx_put(phba, pring, piocbq);
19539 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19540 			break;
19541 		}
19542 		txq_cnt--;
19543 
19544 		/* The xri and iocb resources secured,
19545 		 * attempt to issue request
19546 		 */
19547 		piocbq->sli4_lxritag = sglq->sli4_lxritag;
19548 		piocbq->sli4_xritag = sglq->sli4_xritag;
19549 		if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
19550 			fail_msg = "to convert bpl to sgl";
19551 		else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
19552 			fail_msg = "to convert iocb to wqe";
19553 		else if (lpfc_sli4_wq_put(wq, &wqe))
19554 			fail_msg = " - Wq is full";
19555 		else
19556 			lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
19557 
19558 		if (fail_msg) {
19559 			/* Failed means we can't issue and need to cancel */
19560 			lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
19561 					"2822 IOCB failed %s iotag 0x%x "
19562 					"xri 0x%x\n",
19563 					fail_msg,
19564 					piocbq->iotag, piocbq->sli4_xritag);
19565 			list_add_tail(&piocbq->list, &completions);
19566 		}
19567 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
19568 	}
19569 
19570 	/* Cancel all the IOCBs that cannot be issued */
19571 	lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
19572 				IOERR_SLI_ABORTED);
19573 
19574 	return txq_cnt;
19575 }
19576 
19577 /**
19578  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
19579  * @phba: Pointer to HBA context object.
19580  * @pwqe: Pointer to command WQE.
19581  * @sglq: Pointer to the scatter gather queue object.
19582  *
19583  * This routine converts the bpl or bde that is in the WQE
19584  * to a sgl list for the sli4 hardware. The physical address
19585  * of the bpl/bde is converted back to a virtual address.
19586  * If the WQE contains a BPL then the list of BDE's is
19587  * converted to sli4_sge's. If the WQE contains a single
19588  * BDE then it is converted to a single sli_sge.
19589  * The WQE is still in cpu endianness so the contents of
19590  * the bpl can be used without byte swapping.
19591  *
19592  * Returns valid XRI = Success, NO_XRI = Failure.
19593  */
19594 static uint16_t
19595 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
19596 		 struct lpfc_sglq *sglq)
19597 {
19598 	uint16_t xritag = NO_XRI;
19599 	struct ulp_bde64 *bpl = NULL;
19600 	struct ulp_bde64 bde;
19601 	struct sli4_sge *sgl  = NULL;
19602 	struct lpfc_dmabuf *dmabuf;
19603 	union lpfc_wqe128 *wqe;
19604 	int numBdes = 0;
19605 	int i = 0;
19606 	uint32_t offset = 0; /* accumulated offset in the sg request list */
19607 	int inbound = 0; /* number of sg reply entries inbound from firmware */
19608 	uint32_t cmd;
19609 
19610 	if (!pwqeq || !sglq)
19611 		return xritag;
19612 
19613 	sgl  = (struct sli4_sge *)sglq->sgl;
19614 	wqe = &pwqeq->wqe;
19615 	pwqeq->iocb.ulpIoTag = pwqeq->iotag;
19616 
19617 	cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
19618 	if (cmd == CMD_XMIT_BLS_RSP64_WQE)
19619 		return sglq->sli4_xritag;
19620 	numBdes = pwqeq->rsvd2;
19621 	if (numBdes) {
19622 		/* The addrHigh and addrLow fields within the WQE
19623 		 * have not been byteswapped yet so there is no
19624 		 * need to swap them back.
19625 		 */
19626 		if (pwqeq->context3)
19627 			dmabuf = (struct lpfc_dmabuf *)pwqeq->context3;
19628 		else
19629 			return xritag;
19630 
19631 		bpl  = (struct ulp_bde64 *)dmabuf->virt;
19632 		if (!bpl)
19633 			return xritag;
19634 
19635 		for (i = 0; i < numBdes; i++) {
19636 			/* Should already be byte swapped. */
19637 			sgl->addr_hi = bpl->addrHigh;
19638 			sgl->addr_lo = bpl->addrLow;
19639 
19640 			sgl->word2 = le32_to_cpu(sgl->word2);
19641 			if ((i+1) == numBdes)
19642 				bf_set(lpfc_sli4_sge_last, sgl, 1);
19643 			else
19644 				bf_set(lpfc_sli4_sge_last, sgl, 0);
19645 			/* swap the size field back to the cpu so we
19646 			 * can assign it to the sgl.
19647 			 */
19648 			bde.tus.w = le32_to_cpu(bpl->tus.w);
19649 			sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
19650 			/* The offsets in the sgl need to be accumulated
19651 			 * separately for the request and reply lists.
19652 			 * The request is always first, the reply follows.
19653 			 */
19654 			switch (cmd) {
19655 			case CMD_GEN_REQUEST64_WQE:
19656 				/* add up the reply sg entries */
19657 				if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
19658 					inbound++;
19659 				/* first inbound? reset the offset */
19660 				if (inbound == 1)
19661 					offset = 0;
19662 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
19663 				bf_set(lpfc_sli4_sge_type, sgl,
19664 					LPFC_SGE_TYPE_DATA);
19665 				offset += bde.tus.f.bdeSize;
19666 				break;
19667 			case CMD_FCP_TRSP64_WQE:
19668 				bf_set(lpfc_sli4_sge_offset, sgl, 0);
19669 				bf_set(lpfc_sli4_sge_type, sgl,
19670 					LPFC_SGE_TYPE_DATA);
19671 				break;
19672 			case CMD_FCP_TSEND64_WQE:
19673 			case CMD_FCP_TRECEIVE64_WQE:
19674 				bf_set(lpfc_sli4_sge_type, sgl,
19675 					bpl->tus.f.bdeFlags);
19676 				if (i < 3)
19677 					offset = 0;
19678 				else
19679 					offset += bde.tus.f.bdeSize;
19680 				bf_set(lpfc_sli4_sge_offset, sgl, offset);
19681 				break;
19682 			}
19683 			sgl->word2 = cpu_to_le32(sgl->word2);
19684 			bpl++;
19685 			sgl++;
19686 		}
19687 	} else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
19688 		/* The addrHigh and addrLow fields of the BDE have not
19689 		 * been byteswapped yet so they need to be swapped
19690 		 * before putting them in the sgl.
19691 		 */
19692 		sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
19693 		sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
19694 		sgl->word2 = le32_to_cpu(sgl->word2);
19695 		bf_set(lpfc_sli4_sge_last, sgl, 1);
19696 		sgl->word2 = cpu_to_le32(sgl->word2);
19697 		sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
19698 	}
19699 	return sglq->sli4_xritag;
19700 }
19701 
19702 /**
19703  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
19704  * @phba: Pointer to HBA context object.
19705  * @ring_number: Base sli ring number
19706  * @pwqe: Pointer to command WQE.
19707  **/
19708 int
19709 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, uint32_t ring_number,
19710 		    struct lpfc_iocbq *pwqe)
19711 {
19712 	union lpfc_wqe128 *wqe = &pwqe->wqe;
19713 	struct lpfc_nvmet_rcv_ctx *ctxp;
19714 	struct lpfc_queue *wq;
19715 	struct lpfc_sglq *sglq;
19716 	struct lpfc_sli_ring *pring;
19717 	unsigned long iflags;
19718 	uint32_t ret = 0;
19719 
19720 	/* NVME_LS and NVME_LS ABTS requests. */
19721 	if (pwqe->iocb_flag & LPFC_IO_NVME_LS) {
19722 		pring =  phba->sli4_hba.nvmels_wq->pring;
19723 		spin_lock_irqsave(&pring->ring_lock, iflags);
19724 		sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
19725 		if (!sglq) {
19726 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19727 			return WQE_BUSY;
19728 		}
19729 		pwqe->sli4_lxritag = sglq->sli4_lxritag;
19730 		pwqe->sli4_xritag = sglq->sli4_xritag;
19731 		if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
19732 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19733 			return WQE_ERROR;
19734 		}
19735 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
19736 		       pwqe->sli4_xritag);
19737 		ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
19738 		if (ret) {
19739 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19740 			return ret;
19741 		}
19742 
19743 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
19744 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
19745 		return 0;
19746 	}
19747 
19748 	/* NVME_FCREQ and NVME_ABTS requests */
19749 	if (pwqe->iocb_flag & LPFC_IO_NVME) {
19750 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
19751 		pring = phba->sli4_hba.nvme_wq[pwqe->hba_wqidx]->pring;
19752 
19753 		spin_lock_irqsave(&pring->ring_lock, iflags);
19754 		wq = phba->sli4_hba.nvme_wq[pwqe->hba_wqidx];
19755 		bf_set(wqe_cqid, &wqe->generic.wqe_com,
19756 		      phba->sli4_hba.nvme_cq[pwqe->hba_wqidx]->queue_id);
19757 		ret = lpfc_sli4_wq_put(wq, wqe);
19758 		if (ret) {
19759 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19760 			return ret;
19761 		}
19762 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
19763 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
19764 		return 0;
19765 	}
19766 
19767 	/* NVMET requests */
19768 	if (pwqe->iocb_flag & LPFC_IO_NVMET) {
19769 		/* Get the IO distribution (hba_wqidx) for WQ assignment. */
19770 		pring = phba->sli4_hba.nvme_wq[pwqe->hba_wqidx]->pring;
19771 
19772 		spin_lock_irqsave(&pring->ring_lock, iflags);
19773 		ctxp = pwqe->context2;
19774 		sglq = ctxp->ctxbuf->sglq;
19775 		if (pwqe->sli4_xritag ==  NO_XRI) {
19776 			pwqe->sli4_lxritag = sglq->sli4_lxritag;
19777 			pwqe->sli4_xritag = sglq->sli4_xritag;
19778 		}
19779 		bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
19780 		       pwqe->sli4_xritag);
19781 		wq = phba->sli4_hba.nvme_wq[pwqe->hba_wqidx];
19782 		bf_set(wqe_cqid, &wqe->generic.wqe_com,
19783 		      phba->sli4_hba.nvme_cq[pwqe->hba_wqidx]->queue_id);
19784 		ret = lpfc_sli4_wq_put(wq, wqe);
19785 		if (ret) {
19786 			spin_unlock_irqrestore(&pring->ring_lock, iflags);
19787 			return ret;
19788 		}
19789 		lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
19790 		spin_unlock_irqrestore(&pring->ring_lock, iflags);
19791 		return 0;
19792 	}
19793 	return WQE_ERROR;
19794 }
19795