scsi: lpfc: Fix crash after handling a pci error
[linux-2.6-microblaze.git] / drivers / scsi / lpfc / lpfc_sli.c
1 /*******************************************************************
2  * This file is part of the Emulex Linux Device Driver for         *
3  * Fibre Channel Host Bus Adapters.                                *
4  * Copyright (C) 2017-2020 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 bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
82                                    struct lpfc_queue *cq, struct lpfc_cqe *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_queue *eq,
87                                      struct lpfc_eqe *eqe);
88 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
89 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
90 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
91 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
92                                     struct lpfc_queue *cq,
93                                     struct lpfc_cqe *cqe);
94
95 static IOCB_t *
96 lpfc_get_iocb_from_iocbq(struct lpfc_iocbq *iocbq)
97 {
98         return &iocbq->iocb;
99 }
100
101 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
102 /**
103  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
104  * @srcp: Source memory pointer.
105  * @destp: Destination memory pointer.
106  * @cnt: Number of words required to be copied.
107  *       Must be a multiple of sizeof(uint64_t)
108  *
109  * This function is used for copying data between driver memory
110  * and the SLI WQ. This function also changes the endianness
111  * of each word if native endianness is different from SLI
112  * endianness. This function can be called with or without
113  * lock.
114  **/
115 static void
116 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
117 {
118         uint64_t *src = srcp;
119         uint64_t *dest = destp;
120         int i;
121
122         for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
123                 *dest++ = *src++;
124 }
125 #else
126 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
127 #endif
128
129 /**
130  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
131  * @q: The Work Queue to operate on.
132  * @wqe: The work Queue Entry to put on the Work queue.
133  *
134  * This routine will copy the contents of @wqe to the next available entry on
135  * the @q. This function will then ring the Work Queue Doorbell to signal the
136  * HBA to start processing the Work Queue Entry. This function returns 0 if
137  * successful. If no entries are available on @q then this function will return
138  * -ENOMEM.
139  * The caller is expected to hold the hbalock when calling this routine.
140  **/
141 static int
142 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
143 {
144         union lpfc_wqe *temp_wqe;
145         struct lpfc_register doorbell;
146         uint32_t host_index;
147         uint32_t idx;
148         uint32_t i = 0;
149         uint8_t *tmp;
150         u32 if_type;
151
152         /* sanity check on queue memory */
153         if (unlikely(!q))
154                 return -ENOMEM;
155         temp_wqe = lpfc_sli4_qe(q, q->host_index);
156
157         /* If the host has not yet processed the next entry then we are done */
158         idx = ((q->host_index + 1) % q->entry_count);
159         if (idx == q->hba_index) {
160                 q->WQ_overflow++;
161                 return -EBUSY;
162         }
163         q->WQ_posted++;
164         /* set consumption flag every once in a while */
165         if (!((q->host_index + 1) % q->notify_interval))
166                 bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
167         else
168                 bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
169         if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
170                 bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
171         lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
172         if (q->dpp_enable && q->phba->cfg_enable_dpp) {
173                 /* write to DPP aperture taking advatage of Combined Writes */
174                 tmp = (uint8_t *)temp_wqe;
175 #ifdef __raw_writeq
176                 for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
177                         __raw_writeq(*((uint64_t *)(tmp + i)),
178                                         q->dpp_regaddr + i);
179 #else
180                 for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
181                         __raw_writel(*((uint32_t *)(tmp + i)),
182                                         q->dpp_regaddr + i);
183 #endif
184         }
185         /* ensure WQE bcopy and DPP flushed before doorbell write */
186         wmb();
187
188         /* Update the host index before invoking device */
189         host_index = q->host_index;
190
191         q->host_index = idx;
192
193         /* Ring Doorbell */
194         doorbell.word0 = 0;
195         if (q->db_format == LPFC_DB_LIST_FORMAT) {
196                 if (q->dpp_enable && q->phba->cfg_enable_dpp) {
197                         bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
198                         bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
199                         bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
200                             q->dpp_id);
201                         bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
202                             q->queue_id);
203                 } else {
204                         bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
205                         bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
206
207                         /* Leave bits <23:16> clear for if_type 6 dpp */
208                         if_type = bf_get(lpfc_sli_intf_if_type,
209                                          &q->phba->sli4_hba.sli_intf);
210                         if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
211                                 bf_set(lpfc_wq_db_list_fm_index, &doorbell,
212                                        host_index);
213                 }
214         } else if (q->db_format == LPFC_DB_RING_FORMAT) {
215                 bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
216                 bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
217         } else {
218                 return -EINVAL;
219         }
220         writel(doorbell.word0, q->db_regaddr);
221
222         return 0;
223 }
224
225 /**
226  * lpfc_sli4_wq_release - Updates internal hba index for WQ
227  * @q: The Work Queue to operate on.
228  * @index: The index to advance the hba index to.
229  *
230  * This routine will update the HBA index of a queue to reflect consumption of
231  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
232  * an entry the host calls this function to update the queue's internal
233  * pointers. This routine returns the number of entries that were consumed by
234  * the HBA.
235  **/
236 static uint32_t
237 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
238 {
239         uint32_t released = 0;
240
241         /* sanity check on queue memory */
242         if (unlikely(!q))
243                 return 0;
244
245         if (q->hba_index == index)
246                 return 0;
247         do {
248                 q->hba_index = ((q->hba_index + 1) % q->entry_count);
249                 released++;
250         } while (q->hba_index != index);
251         return released;
252 }
253
254 /**
255  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
256  * @q: The Mailbox Queue to operate on.
257  * @wqe: The Mailbox Queue Entry to put on the Work queue.
258  *
259  * This routine will copy the contents of @mqe to the next available entry on
260  * the @q. This function will then ring the Work Queue Doorbell to signal the
261  * HBA to start processing the Work Queue Entry. This function returns 0 if
262  * successful. If no entries are available on @q then this function will return
263  * -ENOMEM.
264  * The caller is expected to hold the hbalock when calling this routine.
265  **/
266 static uint32_t
267 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
268 {
269         struct lpfc_mqe *temp_mqe;
270         struct lpfc_register doorbell;
271
272         /* sanity check on queue memory */
273         if (unlikely(!q))
274                 return -ENOMEM;
275         temp_mqe = lpfc_sli4_qe(q, q->host_index);
276
277         /* If the host has not yet processed the next entry then we are done */
278         if (((q->host_index + 1) % q->entry_count) == q->hba_index)
279                 return -ENOMEM;
280         lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
281         /* Save off the mailbox pointer for completion */
282         q->phba->mbox = (MAILBOX_t *)temp_mqe;
283
284         /* Update the host index before invoking device */
285         q->host_index = ((q->host_index + 1) % q->entry_count);
286
287         /* Ring Doorbell */
288         doorbell.word0 = 0;
289         bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
290         bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
291         writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
292         return 0;
293 }
294
295 /**
296  * lpfc_sli4_mq_release - Updates internal hba index for MQ
297  * @q: The Mailbox Queue to operate on.
298  *
299  * This routine will update the HBA index of a queue to reflect consumption of
300  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
301  * an entry the host calls this function to update the queue's internal
302  * pointers. This routine returns the number of entries that were consumed by
303  * the HBA.
304  **/
305 static uint32_t
306 lpfc_sli4_mq_release(struct lpfc_queue *q)
307 {
308         /* sanity check on queue memory */
309         if (unlikely(!q))
310                 return 0;
311
312         /* Clear the mailbox pointer for completion */
313         q->phba->mbox = NULL;
314         q->hba_index = ((q->hba_index + 1) % q->entry_count);
315         return 1;
316 }
317
318 /**
319  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
320  * @q: The Event Queue to get the first valid EQE from
321  *
322  * This routine will get the first valid Event Queue Entry from @q, update
323  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
324  * the Queue (no more work to do), or the Queue is full of EQEs that have been
325  * processed, but not popped back to the HBA then this routine will return NULL.
326  **/
327 static struct lpfc_eqe *
328 lpfc_sli4_eq_get(struct lpfc_queue *q)
329 {
330         struct lpfc_eqe *eqe;
331
332         /* sanity check on queue memory */
333         if (unlikely(!q))
334                 return NULL;
335         eqe = lpfc_sli4_qe(q, q->host_index);
336
337         /* If the next EQE is not valid then we are done */
338         if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
339                 return NULL;
340
341         /*
342          * insert barrier for instruction interlock : data from the hardware
343          * must have the valid bit checked before it can be copied and acted
344          * upon. Speculative instructions were allowing a bcopy at the start
345          * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
346          * after our return, to copy data before the valid bit check above
347          * was done. As such, some of the copied data was stale. The barrier
348          * ensures the check is before any data is copied.
349          */
350         mb();
351         return eqe;
352 }
353
354 /**
355  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
356  * @q: The Event Queue to disable interrupts
357  *
358  **/
359 void
360 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
361 {
362         struct lpfc_register doorbell;
363
364         doorbell.word0 = 0;
365         bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
366         bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
367         bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
368                 (q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
369         bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
370         writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
371 }
372
373 /**
374  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
375  * @q: The Event Queue to disable interrupts
376  *
377  **/
378 void
379 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
380 {
381         struct lpfc_register doorbell;
382
383         doorbell.word0 = 0;
384         bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
385         writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
386 }
387
388 /**
389  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
390  * @phba: adapter with EQ
391  * @q: The Event Queue that the host has completed processing for.
392  * @count: Number of elements that have been consumed
393  * @arm: Indicates whether the host wants to arms this CQ.
394  *
395  * This routine will notify the HBA, by ringing the doorbell, that count
396  * number of EQEs have been processed. The @arm parameter indicates whether
397  * the queue should be rearmed when ringing the doorbell.
398  **/
399 void
400 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
401                      uint32_t count, bool arm)
402 {
403         struct lpfc_register doorbell;
404
405         /* sanity check on queue memory */
406         if (unlikely(!q || (count == 0 && !arm)))
407                 return;
408
409         /* ring doorbell for number popped */
410         doorbell.word0 = 0;
411         if (arm) {
412                 bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
413                 bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
414         }
415         bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
416         bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
417         bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
418                         (q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
419         bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
420         writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
421         /* PCI read to flush PCI pipeline on re-arming for INTx mode */
422         if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
423                 readl(q->phba->sli4_hba.EQDBregaddr);
424 }
425
426 /**
427  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
428  * @phba: adapter with EQ
429  * @q: The Event Queue that the host has completed processing for.
430  * @count: Number of elements that have been consumed
431  * @arm: Indicates whether the host wants to arms this CQ.
432  *
433  * This routine will notify the HBA, by ringing the doorbell, that count
434  * number of EQEs have been processed. The @arm parameter indicates whether
435  * the queue should be rearmed when ringing the doorbell.
436  **/
437 void
438 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
439                           uint32_t count, bool arm)
440 {
441         struct lpfc_register doorbell;
442
443         /* sanity check on queue memory */
444         if (unlikely(!q || (count == 0 && !arm)))
445                 return;
446
447         /* ring doorbell for number popped */
448         doorbell.word0 = 0;
449         if (arm)
450                 bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
451         bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
452         bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
453         writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
454         /* PCI read to flush PCI pipeline on re-arming for INTx mode */
455         if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
456                 readl(q->phba->sli4_hba.EQDBregaddr);
457 }
458
459 static void
460 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
461                         struct lpfc_eqe *eqe)
462 {
463         if (!phba->sli4_hba.pc_sli4_params.eqav)
464                 bf_set_le32(lpfc_eqe_valid, eqe, 0);
465
466         eq->host_index = ((eq->host_index + 1) % eq->entry_count);
467
468         /* if the index wrapped around, toggle the valid bit */
469         if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
470                 eq->qe_valid = (eq->qe_valid) ? 0 : 1;
471 }
472
473 static void
474 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
475 {
476         struct lpfc_eqe *eqe = NULL;
477         u32 eq_count = 0, cq_count = 0;
478         struct lpfc_cqe *cqe = NULL;
479         struct lpfc_queue *cq = NULL, *childq = NULL;
480         int cqid = 0;
481
482         /* walk all the EQ entries and drop on the floor */
483         eqe = lpfc_sli4_eq_get(eq);
484         while (eqe) {
485                 /* Get the reference to the corresponding CQ */
486                 cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
487                 cq = NULL;
488
489                 list_for_each_entry(childq, &eq->child_list, list) {
490                         if (childq->queue_id == cqid) {
491                                 cq = childq;
492                                 break;
493                         }
494                 }
495                 /* If CQ is valid, iterate through it and drop all the CQEs */
496                 if (cq) {
497                         cqe = lpfc_sli4_cq_get(cq);
498                         while (cqe) {
499                                 __lpfc_sli4_consume_cqe(phba, cq, cqe);
500                                 cq_count++;
501                                 cqe = lpfc_sli4_cq_get(cq);
502                         }
503                         /* Clear and re-arm the CQ */
504                         phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
505                             LPFC_QUEUE_REARM);
506                         cq_count = 0;
507                 }
508                 __lpfc_sli4_consume_eqe(phba, eq, eqe);
509                 eq_count++;
510                 eqe = lpfc_sli4_eq_get(eq);
511         }
512
513         /* Clear and re-arm the EQ */
514         phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
515 }
516
517 static int
518 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
519                      uint8_t rearm)
520 {
521         struct lpfc_eqe *eqe;
522         int count = 0, consumed = 0;
523
524         if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
525                 goto rearm_and_exit;
526
527         eqe = lpfc_sli4_eq_get(eq);
528         while (eqe) {
529                 lpfc_sli4_hba_handle_eqe(phba, eq, eqe);
530                 __lpfc_sli4_consume_eqe(phba, eq, eqe);
531
532                 consumed++;
533                 if (!(++count % eq->max_proc_limit))
534                         break;
535
536                 if (!(count % eq->notify_interval)) {
537                         phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
538                                                         LPFC_QUEUE_NOARM);
539                         consumed = 0;
540                 }
541
542                 eqe = lpfc_sli4_eq_get(eq);
543         }
544         eq->EQ_processed += count;
545
546         /* Track the max number of EQEs processed in 1 intr */
547         if (count > eq->EQ_max_eqe)
548                 eq->EQ_max_eqe = count;
549
550         eq->queue_claimed = 0;
551
552 rearm_and_exit:
553         /* Always clear the EQ. */
554         phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
555
556         return count;
557 }
558
559 /**
560  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
561  * @q: The Completion Queue to get the first valid CQE from
562  *
563  * This routine will get the first valid Completion Queue Entry from @q, update
564  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
565  * the Queue (no more work to do), or the Queue is full of CQEs that have been
566  * processed, but not popped back to the HBA then this routine will return NULL.
567  **/
568 static struct lpfc_cqe *
569 lpfc_sli4_cq_get(struct lpfc_queue *q)
570 {
571         struct lpfc_cqe *cqe;
572
573         /* sanity check on queue memory */
574         if (unlikely(!q))
575                 return NULL;
576         cqe = lpfc_sli4_qe(q, q->host_index);
577
578         /* If the next CQE is not valid then we are done */
579         if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
580                 return NULL;
581
582         /*
583          * insert barrier for instruction interlock : data from the hardware
584          * must have the valid bit checked before it can be copied and acted
585          * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
586          * instructions allowing action on content before valid bit checked,
587          * add barrier here as well. May not be needed as "content" is a
588          * single 32-bit entity here (vs multi word structure for cq's).
589          */
590         mb();
591         return cqe;
592 }
593
594 static void
595 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
596                         struct lpfc_cqe *cqe)
597 {
598         if (!phba->sli4_hba.pc_sli4_params.cqav)
599                 bf_set_le32(lpfc_cqe_valid, cqe, 0);
600
601         cq->host_index = ((cq->host_index + 1) % cq->entry_count);
602
603         /* if the index wrapped around, toggle the valid bit */
604         if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
605                 cq->qe_valid = (cq->qe_valid) ? 0 : 1;
606 }
607
608 /**
609  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
610  * @phba: the adapter with the CQ
611  * @q: The Completion Queue that the host has completed processing for.
612  * @count: the number of elements that were consumed
613  * @arm: Indicates whether the host wants to arms this CQ.
614  *
615  * This routine will notify the HBA, by ringing the doorbell, that the
616  * CQEs have been processed. The @arm parameter specifies whether the
617  * queue should be rearmed when ringing the doorbell.
618  **/
619 void
620 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
621                      uint32_t count, bool arm)
622 {
623         struct lpfc_register doorbell;
624
625         /* sanity check on queue memory */
626         if (unlikely(!q || (count == 0 && !arm)))
627                 return;
628
629         /* ring doorbell for number popped */
630         doorbell.word0 = 0;
631         if (arm)
632                 bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
633         bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
634         bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
635         bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
636                         (q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
637         bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
638         writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
639 }
640
641 /**
642  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
643  * @phba: the adapter with the CQ
644  * @q: The Completion Queue that the host has completed processing for.
645  * @count: the number of elements that were consumed
646  * @arm: Indicates whether the host wants to arms this CQ.
647  *
648  * This routine will notify the HBA, by ringing the doorbell, that the
649  * CQEs have been processed. The @arm parameter specifies whether the
650  * queue should be rearmed when ringing the doorbell.
651  **/
652 void
653 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
654                          uint32_t count, bool arm)
655 {
656         struct lpfc_register doorbell;
657
658         /* sanity check on queue memory */
659         if (unlikely(!q || (count == 0 && !arm)))
660                 return;
661
662         /* ring doorbell for number popped */
663         doorbell.word0 = 0;
664         if (arm)
665                 bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
666         bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
667         bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
668         writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
669 }
670
671 /**
672  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
673  * @q: The Header Receive Queue to operate on.
674  * @wqe: The Receive Queue Entry to put on the Receive queue.
675  *
676  * This routine will copy the contents of @wqe to the next available entry on
677  * the @q. This function will then ring the Receive Queue Doorbell to signal the
678  * HBA to start processing the Receive Queue Entry. This function returns the
679  * index that the rqe was copied to if successful. If no entries are available
680  * on @q then this function will return -ENOMEM.
681  * The caller is expected to hold the hbalock when calling this routine.
682  **/
683 int
684 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
685                  struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
686 {
687         struct lpfc_rqe *temp_hrqe;
688         struct lpfc_rqe *temp_drqe;
689         struct lpfc_register doorbell;
690         int hq_put_index;
691         int dq_put_index;
692
693         /* sanity check on queue memory */
694         if (unlikely(!hq) || unlikely(!dq))
695                 return -ENOMEM;
696         hq_put_index = hq->host_index;
697         dq_put_index = dq->host_index;
698         temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
699         temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
700
701         if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
702                 return -EINVAL;
703         if (hq_put_index != dq_put_index)
704                 return -EINVAL;
705         /* If the host has not yet processed the next entry then we are done */
706         if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
707                 return -EBUSY;
708         lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
709         lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
710
711         /* Update the host index to point to the next slot */
712         hq->host_index = ((hq_put_index + 1) % hq->entry_count);
713         dq->host_index = ((dq_put_index + 1) % dq->entry_count);
714         hq->RQ_buf_posted++;
715
716         /* Ring The Header Receive Queue Doorbell */
717         if (!(hq->host_index % hq->notify_interval)) {
718                 doorbell.word0 = 0;
719                 if (hq->db_format == LPFC_DB_RING_FORMAT) {
720                         bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
721                                hq->notify_interval);
722                         bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
723                 } else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
724                         bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
725                                hq->notify_interval);
726                         bf_set(lpfc_rq_db_list_fm_index, &doorbell,
727                                hq->host_index);
728                         bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
729                 } else {
730                         return -EINVAL;
731                 }
732                 writel(doorbell.word0, hq->db_regaddr);
733         }
734         return hq_put_index;
735 }
736
737 /**
738  * lpfc_sli4_rq_release - Updates internal hba index for RQ
739  * @q: The Header Receive Queue to operate on.
740  *
741  * This routine will update the HBA index of a queue to reflect consumption of
742  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
743  * consumed an entry the host calls this function to update the queue's
744  * internal pointers. This routine returns the number of entries that were
745  * consumed by the HBA.
746  **/
747 static uint32_t
748 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
749 {
750         /* sanity check on queue memory */
751         if (unlikely(!hq) || unlikely(!dq))
752                 return 0;
753
754         if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
755                 return 0;
756         hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
757         dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
758         return 1;
759 }
760
761 /**
762  * lpfc_cmd_iocb - Get next command iocb entry in the ring
763  * @phba: Pointer to HBA context object.
764  * @pring: Pointer to driver SLI ring object.
765  *
766  * This function returns pointer to next command iocb entry
767  * in the command ring. The caller must hold hbalock to prevent
768  * other threads consume the next command iocb.
769  * SLI-2/SLI-3 provide different sized iocbs.
770  **/
771 static inline IOCB_t *
772 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
773 {
774         return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
775                            pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
776 }
777
778 /**
779  * lpfc_resp_iocb - Get next response iocb entry in the ring
780  * @phba: Pointer to HBA context object.
781  * @pring: Pointer to driver SLI ring object.
782  *
783  * This function returns pointer to next response iocb entry
784  * in the response ring. The caller must hold hbalock to make sure
785  * that no other thread consume the next response iocb.
786  * SLI-2/SLI-3 provide different sized iocbs.
787  **/
788 static inline IOCB_t *
789 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
790 {
791         return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
792                            pring->sli.sli3.rspidx * phba->iocb_rsp_size);
793 }
794
795 /**
796  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
797  * @phba: Pointer to HBA context object.
798  *
799  * This function is called with hbalock held. This function
800  * allocates a new driver iocb object from the iocb pool. If the
801  * allocation is successful, it returns pointer to the newly
802  * allocated iocb object else it returns NULL.
803  **/
804 struct lpfc_iocbq *
805 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
806 {
807         struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
808         struct lpfc_iocbq * iocbq = NULL;
809
810         lockdep_assert_held(&phba->hbalock);
811
812         list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
813         if (iocbq)
814                 phba->iocb_cnt++;
815         if (phba->iocb_cnt > phba->iocb_max)
816                 phba->iocb_max = phba->iocb_cnt;
817         return iocbq;
818 }
819
820 /**
821  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
822  * @phba: Pointer to HBA context object.
823  * @xritag: XRI value.
824  *
825  * This function clears the sglq pointer from the array of acive
826  * sglq's. The xritag that is passed in is used to index into the
827  * array. Before the xritag can be used it needs to be adjusted
828  * by subtracting the xribase.
829  *
830  * Returns sglq ponter = success, NULL = Failure.
831  **/
832 struct lpfc_sglq *
833 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
834 {
835         struct lpfc_sglq *sglq;
836
837         sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
838         phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
839         return sglq;
840 }
841
842 /**
843  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
844  * @phba: Pointer to HBA context object.
845  * @xritag: XRI value.
846  *
847  * This function returns the sglq pointer from the array of acive
848  * sglq's. The xritag that is passed in is used to index into the
849  * array. Before the xritag can be used it needs to be adjusted
850  * by subtracting the xribase.
851  *
852  * Returns sglq ponter = success, NULL = Failure.
853  **/
854 struct lpfc_sglq *
855 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
856 {
857         struct lpfc_sglq *sglq;
858
859         sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
860         return sglq;
861 }
862
863 /**
864  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
865  * @phba: Pointer to HBA context object.
866  * @xritag: xri used in this exchange.
867  * @rrq: The RRQ to be cleared.
868  *
869  **/
870 void
871 lpfc_clr_rrq_active(struct lpfc_hba *phba,
872                     uint16_t xritag,
873                     struct lpfc_node_rrq *rrq)
874 {
875         struct lpfc_nodelist *ndlp = NULL;
876
877         if ((rrq->vport) && NLP_CHK_NODE_ACT(rrq->ndlp))
878                 ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
879
880         /* The target DID could have been swapped (cable swap)
881          * we should use the ndlp from the findnode if it is
882          * available.
883          */
884         if ((!ndlp) && rrq->ndlp)
885                 ndlp = rrq->ndlp;
886
887         if (!ndlp)
888                 goto out;
889
890         if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
891                 rrq->send_rrq = 0;
892                 rrq->xritag = 0;
893                 rrq->rrq_stop_time = 0;
894         }
895 out:
896         mempool_free(rrq, phba->rrq_pool);
897 }
898
899 /**
900  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
901  * @phba: Pointer to HBA context object.
902  *
903  * This function is called with hbalock held. This function
904  * Checks if stop_time (ratov from setting rrq active) has
905  * been reached, if it has and the send_rrq flag is set then
906  * it will call lpfc_send_rrq. If the send_rrq flag is not set
907  * then it will just call the routine to clear the rrq and
908  * free the rrq resource.
909  * The timer is set to the next rrq that is going to expire before
910  * leaving the routine.
911  *
912  **/
913 void
914 lpfc_handle_rrq_active(struct lpfc_hba *phba)
915 {
916         struct lpfc_node_rrq *rrq;
917         struct lpfc_node_rrq *nextrrq;
918         unsigned long next_time;
919         unsigned long iflags;
920         LIST_HEAD(send_rrq);
921
922         spin_lock_irqsave(&phba->hbalock, iflags);
923         phba->hba_flag &= ~HBA_RRQ_ACTIVE;
924         next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
925         list_for_each_entry_safe(rrq, nextrrq,
926                                  &phba->active_rrq_list, list) {
927                 if (time_after(jiffies, rrq->rrq_stop_time))
928                         list_move(&rrq->list, &send_rrq);
929                 else if (time_before(rrq->rrq_stop_time, next_time))
930                         next_time = rrq->rrq_stop_time;
931         }
932         spin_unlock_irqrestore(&phba->hbalock, iflags);
933         if ((!list_empty(&phba->active_rrq_list)) &&
934             (!(phba->pport->load_flag & FC_UNLOADING)))
935                 mod_timer(&phba->rrq_tmr, next_time);
936         list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
937                 list_del(&rrq->list);
938                 if (!rrq->send_rrq) {
939                         /* this call will free the rrq */
940                         lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
941                 } else if (lpfc_send_rrq(phba, rrq)) {
942                         /* if we send the rrq then the completion handler
943                         *  will clear the bit in the xribitmap.
944                         */
945                         lpfc_clr_rrq_active(phba, rrq->xritag,
946                                             rrq);
947                 }
948         }
949 }
950
951 /**
952  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
953  * @vport: Pointer to vport context object.
954  * @xri: The xri used in the exchange.
955  * @did: The targets DID for this exchange.
956  *
957  * returns NULL = rrq not found in the phba->active_rrq_list.
958  *         rrq = rrq for this xri and target.
959  **/
960 struct lpfc_node_rrq *
961 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
962 {
963         struct lpfc_hba *phba = vport->phba;
964         struct lpfc_node_rrq *rrq;
965         struct lpfc_node_rrq *nextrrq;
966         unsigned long iflags;
967
968         if (phba->sli_rev != LPFC_SLI_REV4)
969                 return NULL;
970         spin_lock_irqsave(&phba->hbalock, iflags);
971         list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
972                 if (rrq->vport == vport && rrq->xritag == xri &&
973                                 rrq->nlp_DID == did){
974                         list_del(&rrq->list);
975                         spin_unlock_irqrestore(&phba->hbalock, iflags);
976                         return rrq;
977                 }
978         }
979         spin_unlock_irqrestore(&phba->hbalock, iflags);
980         return NULL;
981 }
982
983 /**
984  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
985  * @vport: Pointer to vport context object.
986  * @ndlp: Pointer to the lpfc_node_list structure.
987  * If ndlp is NULL Remove all active RRQs for this vport from the
988  * phba->active_rrq_list and clear the rrq.
989  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
990  **/
991 void
992 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
993
994 {
995         struct lpfc_hba *phba = vport->phba;
996         struct lpfc_node_rrq *rrq;
997         struct lpfc_node_rrq *nextrrq;
998         unsigned long iflags;
999         LIST_HEAD(rrq_list);
1000
1001         if (phba->sli_rev != LPFC_SLI_REV4)
1002                 return;
1003         if (!ndlp) {
1004                 lpfc_sli4_vport_delete_els_xri_aborted(vport);
1005                 lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
1006         }
1007         spin_lock_irqsave(&phba->hbalock, iflags);
1008         list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list)
1009                 if ((rrq->vport == vport) && (!ndlp  || rrq->ndlp == ndlp))
1010                         list_move(&rrq->list, &rrq_list);
1011         spin_unlock_irqrestore(&phba->hbalock, iflags);
1012
1013         list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1014                 list_del(&rrq->list);
1015                 lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1016         }
1017 }
1018
1019 /**
1020  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1021  * @phba: Pointer to HBA context object.
1022  * @ndlp: Targets nodelist pointer for this exchange.
1023  * @xritag the xri in the bitmap to test.
1024  *
1025  * This function returns:
1026  * 0 = rrq not active for this xri
1027  * 1 = rrq is valid for this xri.
1028  **/
1029 int
1030 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1031                         uint16_t  xritag)
1032 {
1033         if (!ndlp)
1034                 return 0;
1035         if (!ndlp->active_rrqs_xri_bitmap)
1036                 return 0;
1037         if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1038                 return 1;
1039         else
1040                 return 0;
1041 }
1042
1043 /**
1044  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1045  * @phba: Pointer to HBA context object.
1046  * @ndlp: nodelist pointer for this target.
1047  * @xritag: xri used in this exchange.
1048  * @rxid: Remote Exchange ID.
1049  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1050  *
1051  * This function takes the hbalock.
1052  * The active bit is always set in the active rrq xri_bitmap even
1053  * if there is no slot avaiable for the other rrq information.
1054  *
1055  * returns 0 rrq actived for this xri
1056  *         < 0 No memory or invalid ndlp.
1057  **/
1058 int
1059 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1060                     uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1061 {
1062         unsigned long iflags;
1063         struct lpfc_node_rrq *rrq;
1064         int empty;
1065
1066         if (!ndlp)
1067                 return -EINVAL;
1068
1069         if (!phba->cfg_enable_rrq)
1070                 return -EINVAL;
1071
1072         spin_lock_irqsave(&phba->hbalock, iflags);
1073         if (phba->pport->load_flag & FC_UNLOADING) {
1074                 phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1075                 goto out;
1076         }
1077
1078         /*
1079          * set the active bit even if there is no mem available.
1080          */
1081         if (NLP_CHK_FREE_REQ(ndlp))
1082                 goto out;
1083
1084         if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
1085                 goto out;
1086
1087         if (!ndlp->active_rrqs_xri_bitmap)
1088                 goto out;
1089
1090         if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1091                 goto out;
1092
1093         spin_unlock_irqrestore(&phba->hbalock, iflags);
1094         rrq = mempool_alloc(phba->rrq_pool, GFP_KERNEL);
1095         if (!rrq) {
1096                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1097                                 "3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1098                                 " DID:0x%x Send:%d\n",
1099                                 xritag, rxid, ndlp->nlp_DID, send_rrq);
1100                 return -EINVAL;
1101         }
1102         if (phba->cfg_enable_rrq == 1)
1103                 rrq->send_rrq = send_rrq;
1104         else
1105                 rrq->send_rrq = 0;
1106         rrq->xritag = xritag;
1107         rrq->rrq_stop_time = jiffies +
1108                                 msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1109         rrq->ndlp = ndlp;
1110         rrq->nlp_DID = ndlp->nlp_DID;
1111         rrq->vport = ndlp->vport;
1112         rrq->rxid = rxid;
1113         spin_lock_irqsave(&phba->hbalock, iflags);
1114         empty = list_empty(&phba->active_rrq_list);
1115         list_add_tail(&rrq->list, &phba->active_rrq_list);
1116         phba->hba_flag |= HBA_RRQ_ACTIVE;
1117         if (empty)
1118                 lpfc_worker_wake_up(phba);
1119         spin_unlock_irqrestore(&phba->hbalock, iflags);
1120         return 0;
1121 out:
1122         spin_unlock_irqrestore(&phba->hbalock, iflags);
1123         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1124                         "2921 Can't set rrq active xri:0x%x rxid:0x%x"
1125                         " DID:0x%x Send:%d\n",
1126                         xritag, rxid, ndlp->nlp_DID, send_rrq);
1127         return -EINVAL;
1128 }
1129
1130 /**
1131  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
1132  * @phba: Pointer to HBA context object.
1133  * @piocb: Pointer to the iocbq.
1134  *
1135  * The driver calls this function with either the nvme ls ring lock
1136  * or the fc els ring lock held depending on the iocb usage.  This function
1137  * gets a new driver sglq object from the sglq list. If the list is not empty
1138  * then it is successful, it returns pointer to the newly allocated sglq
1139  * object else it returns NULL.
1140  **/
1141 static struct lpfc_sglq *
1142 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1143 {
1144         struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
1145         struct lpfc_sglq *sglq = NULL;
1146         struct lpfc_sglq *start_sglq = NULL;
1147         struct lpfc_io_buf *lpfc_cmd;
1148         struct lpfc_nodelist *ndlp;
1149         struct lpfc_sli_ring *pring = NULL;
1150         int found = 0;
1151
1152         if (piocbq->iocb_flag & LPFC_IO_NVME_LS)
1153                 pring =  phba->sli4_hba.nvmels_wq->pring;
1154         else
1155                 pring = lpfc_phba_elsring(phba);
1156
1157         lockdep_assert_held(&pring->ring_lock);
1158
1159         if (piocbq->iocb_flag &  LPFC_IO_FCP) {
1160                 lpfc_cmd = (struct lpfc_io_buf *) piocbq->context1;
1161                 ndlp = lpfc_cmd->rdata->pnode;
1162         } else  if ((piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) &&
1163                         !(piocbq->iocb_flag & LPFC_IO_LIBDFC)) {
1164                 ndlp = piocbq->context_un.ndlp;
1165         } else  if (piocbq->iocb_flag & LPFC_IO_LIBDFC) {
1166                 if (piocbq->iocb_flag & LPFC_IO_LOOPBACK)
1167                         ndlp = NULL;
1168                 else
1169                         ndlp = piocbq->context_un.ndlp;
1170         } else {
1171                 ndlp = piocbq->context1;
1172         }
1173
1174         spin_lock(&phba->sli4_hba.sgl_list_lock);
1175         list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
1176         start_sglq = sglq;
1177         while (!found) {
1178                 if (!sglq)
1179                         break;
1180                 if (ndlp && ndlp->active_rrqs_xri_bitmap &&
1181                     test_bit(sglq->sli4_lxritag,
1182                     ndlp->active_rrqs_xri_bitmap)) {
1183                         /* This xri has an rrq outstanding for this DID.
1184                          * put it back in the list and get another xri.
1185                          */
1186                         list_add_tail(&sglq->list, lpfc_els_sgl_list);
1187                         sglq = NULL;
1188                         list_remove_head(lpfc_els_sgl_list, sglq,
1189                                                 struct lpfc_sglq, list);
1190                         if (sglq == start_sglq) {
1191                                 list_add_tail(&sglq->list, lpfc_els_sgl_list);
1192                                 sglq = NULL;
1193                                 break;
1194                         } else
1195                                 continue;
1196                 }
1197                 sglq->ndlp = ndlp;
1198                 found = 1;
1199                 phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1200                 sglq->state = SGL_ALLOCATED;
1201         }
1202         spin_unlock(&phba->sli4_hba.sgl_list_lock);
1203         return sglq;
1204 }
1205
1206 /**
1207  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
1208  * @phba: Pointer to HBA context object.
1209  * @piocb: Pointer to the iocbq.
1210  *
1211  * This function is called with the sgl_list lock held. This function
1212  * gets a new driver sglq object from the sglq list. If the
1213  * list is not empty then it is successful, it returns pointer to the newly
1214  * allocated sglq object else it returns NULL.
1215  **/
1216 struct lpfc_sglq *
1217 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1218 {
1219         struct list_head *lpfc_nvmet_sgl_list;
1220         struct lpfc_sglq *sglq = NULL;
1221
1222         lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
1223
1224         lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1225
1226         list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1227         if (!sglq)
1228                 return NULL;
1229         phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1230         sglq->state = SGL_ALLOCATED;
1231         return sglq;
1232 }
1233
1234 /**
1235  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1236  * @phba: Pointer to HBA context object.
1237  *
1238  * This function is called with no lock held. This function
1239  * allocates a new driver iocb object from the iocb pool. If the
1240  * allocation is successful, it returns pointer to the newly
1241  * allocated iocb object else it returns NULL.
1242  **/
1243 struct lpfc_iocbq *
1244 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1245 {
1246         struct lpfc_iocbq * iocbq = NULL;
1247         unsigned long iflags;
1248
1249         spin_lock_irqsave(&phba->hbalock, iflags);
1250         iocbq = __lpfc_sli_get_iocbq(phba);
1251         spin_unlock_irqrestore(&phba->hbalock, iflags);
1252         return iocbq;
1253 }
1254
1255 /**
1256  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1257  * @phba: Pointer to HBA context object.
1258  * @iocbq: Pointer to driver iocb object.
1259  *
1260  * This function is called with hbalock held to release driver
1261  * iocb object to the iocb pool. The iotag in the iocb object
1262  * does not change for each use of the iocb object. This function
1263  * clears all other fields of the iocb object when it is freed.
1264  * The sqlq structure that holds the xritag and phys and virtual
1265  * mappings for the scatter gather list is retrieved from the
1266  * active array of sglq. The get of the sglq pointer also clears
1267  * the entry in the array. If the status of the IO indiactes that
1268  * this IO was aborted then the sglq entry it put on the
1269  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1270  * IO has good status or fails for any other reason then the sglq
1271  * entry is added to the free list (lpfc_els_sgl_list).
1272  **/
1273 static void
1274 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1275 {
1276         struct lpfc_sglq *sglq;
1277         size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1278         unsigned long iflag = 0;
1279         struct lpfc_sli_ring *pring;
1280
1281         lockdep_assert_held(&phba->hbalock);
1282
1283         if (iocbq->sli4_xritag == NO_XRI)
1284                 sglq = NULL;
1285         else
1286                 sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1287
1288
1289         if (sglq)  {
1290                 if (iocbq->iocb_flag & LPFC_IO_NVMET) {
1291                         spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1292                                           iflag);
1293                         sglq->state = SGL_FREED;
1294                         sglq->ndlp = NULL;
1295                         list_add_tail(&sglq->list,
1296                                       &phba->sli4_hba.lpfc_nvmet_sgl_list);
1297                         spin_unlock_irqrestore(
1298                                 &phba->sli4_hba.sgl_list_lock, iflag);
1299                         goto out;
1300                 }
1301
1302                 pring = phba->sli4_hba.els_wq->pring;
1303                 if ((iocbq->iocb_flag & LPFC_EXCHANGE_BUSY) &&
1304                         (sglq->state != SGL_XRI_ABORTED)) {
1305                         spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1306                                           iflag);
1307                         list_add(&sglq->list,
1308                                  &phba->sli4_hba.lpfc_abts_els_sgl_list);
1309                         spin_unlock_irqrestore(
1310                                 &phba->sli4_hba.sgl_list_lock, iflag);
1311                 } else {
1312                         spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1313                                           iflag);
1314                         sglq->state = SGL_FREED;
1315                         sglq->ndlp = NULL;
1316                         list_add_tail(&sglq->list,
1317                                       &phba->sli4_hba.lpfc_els_sgl_list);
1318                         spin_unlock_irqrestore(
1319                                 &phba->sli4_hba.sgl_list_lock, iflag);
1320
1321                         /* Check if TXQ queue needs to be serviced */
1322                         if (!list_empty(&pring->txq))
1323                                 lpfc_worker_wake_up(phba);
1324                 }
1325         }
1326
1327 out:
1328         /*
1329          * Clean all volatile data fields, preserve iotag and node struct.
1330          */
1331         memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1332         iocbq->sli4_lxritag = NO_XRI;
1333         iocbq->sli4_xritag = NO_XRI;
1334         iocbq->iocb_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET |
1335                               LPFC_IO_NVME_LS);
1336         list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1337 }
1338
1339
1340 /**
1341  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1342  * @phba: Pointer to HBA context object.
1343  * @iocbq: Pointer to driver iocb object.
1344  *
1345  * This function is called with hbalock held to release driver
1346  * iocb object to the iocb pool. The iotag in the iocb object
1347  * does not change for each use of the iocb object. This function
1348  * clears all other fields of the iocb object when it is freed.
1349  **/
1350 static void
1351 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1352 {
1353         size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1354
1355         lockdep_assert_held(&phba->hbalock);
1356
1357         /*
1358          * Clean all volatile data fields, preserve iotag and node struct.
1359          */
1360         memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1361         iocbq->sli4_xritag = NO_XRI;
1362         list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1363 }
1364
1365 /**
1366  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1367  * @phba: Pointer to HBA context object.
1368  * @iocbq: Pointer to driver iocb object.
1369  *
1370  * This function is called with hbalock held to release driver
1371  * iocb object to the iocb pool. The iotag in the iocb object
1372  * does not change for each use of the iocb object. This function
1373  * clears all other fields of the iocb object when it is freed.
1374  **/
1375 static void
1376 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1377 {
1378         lockdep_assert_held(&phba->hbalock);
1379
1380         phba->__lpfc_sli_release_iocbq(phba, iocbq);
1381         phba->iocb_cnt--;
1382 }
1383
1384 /**
1385  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1386  * @phba: Pointer to HBA context object.
1387  * @iocbq: Pointer to driver iocb object.
1388  *
1389  * This function is called with no lock held to release the iocb to
1390  * iocb pool.
1391  **/
1392 void
1393 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1394 {
1395         unsigned long iflags;
1396
1397         /*
1398          * Clean all volatile data fields, preserve iotag and node struct.
1399          */
1400         spin_lock_irqsave(&phba->hbalock, iflags);
1401         __lpfc_sli_release_iocbq(phba, iocbq);
1402         spin_unlock_irqrestore(&phba->hbalock, iflags);
1403 }
1404
1405 /**
1406  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1407  * @phba: Pointer to HBA context object.
1408  * @iocblist: List of IOCBs.
1409  * @ulpstatus: ULP status in IOCB command field.
1410  * @ulpWord4: ULP word-4 in IOCB command field.
1411  *
1412  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1413  * on the list by invoking the complete callback function associated with the
1414  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1415  * fields.
1416  **/
1417 void
1418 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1419                       uint32_t ulpstatus, uint32_t ulpWord4)
1420 {
1421         struct lpfc_iocbq *piocb;
1422
1423         while (!list_empty(iocblist)) {
1424                 list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1425                 if (!piocb->iocb_cmpl) {
1426                         if (piocb->iocb_flag & LPFC_IO_NVME)
1427                                 lpfc_nvme_cancel_iocb(phba, piocb);
1428                         else
1429                                 lpfc_sli_release_iocbq(phba, piocb);
1430                 } else {
1431                         piocb->iocb.ulpStatus = ulpstatus;
1432                         piocb->iocb.un.ulpWord[4] = ulpWord4;
1433                         (piocb->iocb_cmpl) (phba, piocb, piocb);
1434                 }
1435         }
1436         return;
1437 }
1438
1439 /**
1440  * lpfc_sli_iocb_cmd_type - Get the iocb type
1441  * @iocb_cmnd: iocb command code.
1442  *
1443  * This function is called by ring event handler function to get the iocb type.
1444  * This function translates the iocb command to an iocb command type used to
1445  * decide the final disposition of each completed IOCB.
1446  * The function returns
1447  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1448  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1449  * LPFC_ABORT_IOCB   if it is an abort iocb
1450  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1451  *
1452  * The caller is not required to hold any lock.
1453  **/
1454 static lpfc_iocb_type
1455 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1456 {
1457         lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1458
1459         if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1460                 return 0;
1461
1462         switch (iocb_cmnd) {
1463         case CMD_XMIT_SEQUENCE_CR:
1464         case CMD_XMIT_SEQUENCE_CX:
1465         case CMD_XMIT_BCAST_CN:
1466         case CMD_XMIT_BCAST_CX:
1467         case CMD_ELS_REQUEST_CR:
1468         case CMD_ELS_REQUEST_CX:
1469         case CMD_CREATE_XRI_CR:
1470         case CMD_CREATE_XRI_CX:
1471         case CMD_GET_RPI_CN:
1472         case CMD_XMIT_ELS_RSP_CX:
1473         case CMD_GET_RPI_CR:
1474         case CMD_FCP_IWRITE_CR:
1475         case CMD_FCP_IWRITE_CX:
1476         case CMD_FCP_IREAD_CR:
1477         case CMD_FCP_IREAD_CX:
1478         case CMD_FCP_ICMND_CR:
1479         case CMD_FCP_ICMND_CX:
1480         case CMD_FCP_TSEND_CX:
1481         case CMD_FCP_TRSP_CX:
1482         case CMD_FCP_TRECEIVE_CX:
1483         case CMD_FCP_AUTO_TRSP_CX:
1484         case CMD_ADAPTER_MSG:
1485         case CMD_ADAPTER_DUMP:
1486         case CMD_XMIT_SEQUENCE64_CR:
1487         case CMD_XMIT_SEQUENCE64_CX:
1488         case CMD_XMIT_BCAST64_CN:
1489         case CMD_XMIT_BCAST64_CX:
1490         case CMD_ELS_REQUEST64_CR:
1491         case CMD_ELS_REQUEST64_CX:
1492         case CMD_FCP_IWRITE64_CR:
1493         case CMD_FCP_IWRITE64_CX:
1494         case CMD_FCP_IREAD64_CR:
1495         case CMD_FCP_IREAD64_CX:
1496         case CMD_FCP_ICMND64_CR:
1497         case CMD_FCP_ICMND64_CX:
1498         case CMD_FCP_TSEND64_CX:
1499         case CMD_FCP_TRSP64_CX:
1500         case CMD_FCP_TRECEIVE64_CX:
1501         case CMD_GEN_REQUEST64_CR:
1502         case CMD_GEN_REQUEST64_CX:
1503         case CMD_XMIT_ELS_RSP64_CX:
1504         case DSSCMD_IWRITE64_CR:
1505         case DSSCMD_IWRITE64_CX:
1506         case DSSCMD_IREAD64_CR:
1507         case DSSCMD_IREAD64_CX:
1508                 type = LPFC_SOL_IOCB;
1509                 break;
1510         case CMD_ABORT_XRI_CN:
1511         case CMD_ABORT_XRI_CX:
1512         case CMD_CLOSE_XRI_CN:
1513         case CMD_CLOSE_XRI_CX:
1514         case CMD_XRI_ABORTED_CX:
1515         case CMD_ABORT_MXRI64_CN:
1516         case CMD_XMIT_BLS_RSP64_CX:
1517                 type = LPFC_ABORT_IOCB;
1518                 break;
1519         case CMD_RCV_SEQUENCE_CX:
1520         case CMD_RCV_ELS_REQ_CX:
1521         case CMD_RCV_SEQUENCE64_CX:
1522         case CMD_RCV_ELS_REQ64_CX:
1523         case CMD_ASYNC_STATUS:
1524         case CMD_IOCB_RCV_SEQ64_CX:
1525         case CMD_IOCB_RCV_ELS64_CX:
1526         case CMD_IOCB_RCV_CONT64_CX:
1527         case CMD_IOCB_RET_XRI64_CX:
1528                 type = LPFC_UNSOL_IOCB;
1529                 break;
1530         case CMD_IOCB_XMIT_MSEQ64_CR:
1531         case CMD_IOCB_XMIT_MSEQ64_CX:
1532         case CMD_IOCB_RCV_SEQ_LIST64_CX:
1533         case CMD_IOCB_RCV_ELS_LIST64_CX:
1534         case CMD_IOCB_CLOSE_EXTENDED_CN:
1535         case CMD_IOCB_ABORT_EXTENDED_CN:
1536         case CMD_IOCB_RET_HBQE64_CN:
1537         case CMD_IOCB_FCP_IBIDIR64_CR:
1538         case CMD_IOCB_FCP_IBIDIR64_CX:
1539         case CMD_IOCB_FCP_ITASKMGT64_CX:
1540         case CMD_IOCB_LOGENTRY_CN:
1541         case CMD_IOCB_LOGENTRY_ASYNC_CN:
1542                 printk("%s - Unhandled SLI-3 Command x%x\n",
1543                                 __func__, iocb_cmnd);
1544                 type = LPFC_UNKNOWN_IOCB;
1545                 break;
1546         default:
1547                 type = LPFC_UNKNOWN_IOCB;
1548                 break;
1549         }
1550
1551         return type;
1552 }
1553
1554 /**
1555  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1556  * @phba: Pointer to HBA context object.
1557  *
1558  * This function is called from SLI initialization code
1559  * to configure every ring of the HBA's SLI interface. The
1560  * caller is not required to hold any lock. This function issues
1561  * a config_ring mailbox command for each ring.
1562  * This function returns zero if successful else returns a negative
1563  * error code.
1564  **/
1565 static int
1566 lpfc_sli_ring_map(struct lpfc_hba *phba)
1567 {
1568         struct lpfc_sli *psli = &phba->sli;
1569         LPFC_MBOXQ_t *pmb;
1570         MAILBOX_t *pmbox;
1571         int i, rc, ret = 0;
1572
1573         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1574         if (!pmb)
1575                 return -ENOMEM;
1576         pmbox = &pmb->u.mb;
1577         phba->link_state = LPFC_INIT_MBX_CMDS;
1578         for (i = 0; i < psli->num_rings; i++) {
1579                 lpfc_config_ring(phba, i, pmb);
1580                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1581                 if (rc != MBX_SUCCESS) {
1582                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
1583                                         "0446 Adapter failed to init (%d), "
1584                                         "mbxCmd x%x CFG_RING, mbxStatus x%x, "
1585                                         "ring %d\n",
1586                                         rc, pmbox->mbxCommand,
1587                                         pmbox->mbxStatus, i);
1588                         phba->link_state = LPFC_HBA_ERROR;
1589                         ret = -ENXIO;
1590                         break;
1591                 }
1592         }
1593         mempool_free(pmb, phba->mbox_mem_pool);
1594         return ret;
1595 }
1596
1597 /**
1598  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1599  * @phba: Pointer to HBA context object.
1600  * @pring: Pointer to driver SLI ring object.
1601  * @piocb: Pointer to the driver iocb object.
1602  *
1603  * The driver calls this function with the hbalock held for SLI3 ports or
1604  * the ring lock held for SLI4 ports. The function adds the
1605  * new iocb to txcmplq of the given ring. This function always returns
1606  * 0. If this function is called for ELS ring, this function checks if
1607  * there is a vport associated with the ELS command. This function also
1608  * starts els_tmofunc timer if this is an ELS command.
1609  **/
1610 static int
1611 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1612                         struct lpfc_iocbq *piocb)
1613 {
1614         if (phba->sli_rev == LPFC_SLI_REV4)
1615                 lockdep_assert_held(&pring->ring_lock);
1616         else
1617                 lockdep_assert_held(&phba->hbalock);
1618
1619         BUG_ON(!piocb);
1620
1621         list_add_tail(&piocb->list, &pring->txcmplq);
1622         piocb->iocb_flag |= LPFC_IO_ON_TXCMPLQ;
1623         pring->txcmplq_cnt++;
1624
1625         if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1626            (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
1627            (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
1628                 BUG_ON(!piocb->vport);
1629                 if (!(piocb->vport->load_flag & FC_UNLOADING))
1630                         mod_timer(&piocb->vport->els_tmofunc,
1631                                   jiffies +
1632                                   msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1633         }
1634
1635         return 0;
1636 }
1637
1638 /**
1639  * lpfc_sli_ringtx_get - Get first element of the txq
1640  * @phba: Pointer to HBA context object.
1641  * @pring: Pointer to driver SLI ring object.
1642  *
1643  * This function is called with hbalock held to get next
1644  * iocb in txq of the given ring. If there is any iocb in
1645  * the txq, the function returns first iocb in the list after
1646  * removing the iocb from the list, else it returns NULL.
1647  **/
1648 struct lpfc_iocbq *
1649 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1650 {
1651         struct lpfc_iocbq *cmd_iocb;
1652
1653         lockdep_assert_held(&phba->hbalock);
1654
1655         list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1656         return cmd_iocb;
1657 }
1658
1659 /**
1660  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
1661  * @phba: Pointer to HBA context object.
1662  * @pring: Pointer to driver SLI ring object.
1663  *
1664  * This function is called with hbalock held and the caller must post the
1665  * iocb without releasing the lock. If the caller releases the lock,
1666  * iocb slot returned by the function is not guaranteed to be available.
1667  * The function returns pointer to the next available iocb slot if there
1668  * is available slot in the ring, else it returns NULL.
1669  * If the get index of the ring is ahead of the put index, the function
1670  * will post an error attention event to the worker thread to take the
1671  * HBA to offline state.
1672  **/
1673 static IOCB_t *
1674 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1675 {
1676         struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
1677         uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
1678
1679         lockdep_assert_held(&phba->hbalock);
1680
1681         if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
1682            (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
1683                 pring->sli.sli3.next_cmdidx = 0;
1684
1685         if (unlikely(pring->sli.sli3.local_getidx ==
1686                 pring->sli.sli3.next_cmdidx)) {
1687
1688                 pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
1689
1690                 if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
1691                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
1692                                         "0315 Ring %d issue: portCmdGet %d "
1693                                         "is bigger than cmd ring %d\n",
1694                                         pring->ringno,
1695                                         pring->sli.sli3.local_getidx,
1696                                         max_cmd_idx);
1697
1698                         phba->link_state = LPFC_HBA_ERROR;
1699                         /*
1700                          * All error attention handlers are posted to
1701                          * worker thread
1702                          */
1703                         phba->work_ha |= HA_ERATT;
1704                         phba->work_hs = HS_FFER3;
1705
1706                         lpfc_worker_wake_up(phba);
1707
1708                         return NULL;
1709                 }
1710
1711                 if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
1712                         return NULL;
1713         }
1714
1715         return lpfc_cmd_iocb(phba, pring);
1716 }
1717
1718 /**
1719  * lpfc_sli_next_iotag - Get an iotag for the iocb
1720  * @phba: Pointer to HBA context object.
1721  * @iocbq: Pointer to driver iocb object.
1722  *
1723  * This function gets an iotag for the iocb. If there is no unused iotag and
1724  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
1725  * array and assigns a new iotag.
1726  * The function returns the allocated iotag if successful, else returns zero.
1727  * Zero is not a valid iotag.
1728  * The caller is not required to hold any lock.
1729  **/
1730 uint16_t
1731 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1732 {
1733         struct lpfc_iocbq **new_arr;
1734         struct lpfc_iocbq **old_arr;
1735         size_t new_len;
1736         struct lpfc_sli *psli = &phba->sli;
1737         uint16_t iotag;
1738
1739         spin_lock_irq(&phba->hbalock);
1740         iotag = psli->last_iotag;
1741         if(++iotag < psli->iocbq_lookup_len) {
1742                 psli->last_iotag = iotag;
1743                 psli->iocbq_lookup[iotag] = iocbq;
1744                 spin_unlock_irq(&phba->hbalock);
1745                 iocbq->iotag = iotag;
1746                 return iotag;
1747         } else if (psli->iocbq_lookup_len < (0xffff
1748                                            - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
1749                 new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
1750                 spin_unlock_irq(&phba->hbalock);
1751                 new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
1752                                   GFP_KERNEL);
1753                 if (new_arr) {
1754                         spin_lock_irq(&phba->hbalock);
1755                         old_arr = psli->iocbq_lookup;
1756                         if (new_len <= psli->iocbq_lookup_len) {
1757                                 /* highly unprobable case */
1758                                 kfree(new_arr);
1759                                 iotag = psli->last_iotag;
1760                                 if(++iotag < psli->iocbq_lookup_len) {
1761                                         psli->last_iotag = iotag;
1762                                         psli->iocbq_lookup[iotag] = iocbq;
1763                                         spin_unlock_irq(&phba->hbalock);
1764                                         iocbq->iotag = iotag;
1765                                         return iotag;
1766                                 }
1767                                 spin_unlock_irq(&phba->hbalock);
1768                                 return 0;
1769                         }
1770                         if (psli->iocbq_lookup)
1771                                 memcpy(new_arr, old_arr,
1772                                        ((psli->last_iotag  + 1) *
1773                                         sizeof (struct lpfc_iocbq *)));
1774                         psli->iocbq_lookup = new_arr;
1775                         psli->iocbq_lookup_len = new_len;
1776                         psli->last_iotag = iotag;
1777                         psli->iocbq_lookup[iotag] = iocbq;
1778                         spin_unlock_irq(&phba->hbalock);
1779                         iocbq->iotag = iotag;
1780                         kfree(old_arr);
1781                         return iotag;
1782                 }
1783         } else
1784                 spin_unlock_irq(&phba->hbalock);
1785
1786         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
1787                         "0318 Failed to allocate IOTAG.last IOTAG is %d\n",
1788                         psli->last_iotag);
1789
1790         return 0;
1791 }
1792
1793 /**
1794  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
1795  * @phba: Pointer to HBA context object.
1796  * @pring: Pointer to driver SLI ring object.
1797  * @iocb: Pointer to iocb slot in the ring.
1798  * @nextiocb: Pointer to driver iocb object which need to be
1799  *            posted to firmware.
1800  *
1801  * This function is called with hbalock held to post a new iocb to
1802  * the firmware. This function copies the new iocb to ring iocb slot and
1803  * updates the ring pointers. It adds the new iocb to txcmplq if there is
1804  * a completion call back for this iocb else the function will free the
1805  * iocb object.
1806  **/
1807 static void
1808 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1809                 IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
1810 {
1811         lockdep_assert_held(&phba->hbalock);
1812         /*
1813          * Set up an iotag
1814          */
1815         nextiocb->iocb.ulpIoTag = (nextiocb->iocb_cmpl) ? nextiocb->iotag : 0;
1816
1817
1818         if (pring->ringno == LPFC_ELS_RING) {
1819                 lpfc_debugfs_slow_ring_trc(phba,
1820                         "IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
1821                         *(((uint32_t *) &nextiocb->iocb) + 4),
1822                         *(((uint32_t *) &nextiocb->iocb) + 6),
1823                         *(((uint32_t *) &nextiocb->iocb) + 7));
1824         }
1825
1826         /*
1827          * Issue iocb command to adapter
1828          */
1829         lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
1830         wmb();
1831         pring->stats.iocb_cmd++;
1832
1833         /*
1834          * If there is no completion routine to call, we can release the
1835          * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
1836          * that have no rsp ring completion, iocb_cmpl MUST be NULL.
1837          */
1838         if (nextiocb->iocb_cmpl)
1839                 lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
1840         else
1841                 __lpfc_sli_release_iocbq(phba, nextiocb);
1842
1843         /*
1844          * Let the HBA know what IOCB slot will be the next one the
1845          * driver will put a command into.
1846          */
1847         pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
1848         writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
1849 }
1850
1851 /**
1852  * lpfc_sli_update_full_ring - Update the chip attention register
1853  * @phba: Pointer to HBA context object.
1854  * @pring: Pointer to driver SLI ring object.
1855  *
1856  * The caller is not required to hold any lock for calling this function.
1857  * This function updates the chip attention bits for the ring to inform firmware
1858  * that there are pending work to be done for this ring and requests an
1859  * interrupt when there is space available in the ring. This function is
1860  * called when the driver is unable to post more iocbs to the ring due
1861  * to unavailability of space in the ring.
1862  **/
1863 static void
1864 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1865 {
1866         int ringno = pring->ringno;
1867
1868         pring->flag |= LPFC_CALL_RING_AVAILABLE;
1869
1870         wmb();
1871
1872         /*
1873          * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
1874          * The HBA will tell us when an IOCB entry is available.
1875          */
1876         writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
1877         readl(phba->CAregaddr); /* flush */
1878
1879         pring->stats.iocb_cmd_full++;
1880 }
1881
1882 /**
1883  * lpfc_sli_update_ring - Update chip attention register
1884  * @phba: Pointer to HBA context object.
1885  * @pring: Pointer to driver SLI ring object.
1886  *
1887  * This function updates the chip attention register bit for the
1888  * given ring to inform HBA that there is more work to be done
1889  * in this ring. The caller is not required to hold any lock.
1890  **/
1891 static void
1892 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1893 {
1894         int ringno = pring->ringno;
1895
1896         /*
1897          * Tell the HBA that there is work to do in this ring.
1898          */
1899         if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
1900                 wmb();
1901                 writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
1902                 readl(phba->CAregaddr); /* flush */
1903         }
1904 }
1905
1906 /**
1907  * lpfc_sli_resume_iocb - Process iocbs in the txq
1908  * @phba: Pointer to HBA context object.
1909  * @pring: Pointer to driver SLI ring object.
1910  *
1911  * This function is called with hbalock held to post pending iocbs
1912  * in the txq to the firmware. This function is called when driver
1913  * detects space available in the ring.
1914  **/
1915 static void
1916 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1917 {
1918         IOCB_t *iocb;
1919         struct lpfc_iocbq *nextiocb;
1920
1921         lockdep_assert_held(&phba->hbalock);
1922
1923         /*
1924          * Check to see if:
1925          *  (a) there is anything on the txq to send
1926          *  (b) link is up
1927          *  (c) link attention events can be processed (fcp ring only)
1928          *  (d) IOCB processing is not blocked by the outstanding mbox command.
1929          */
1930
1931         if (lpfc_is_link_up(phba) &&
1932             (!list_empty(&pring->txq)) &&
1933             (pring->ringno != LPFC_FCP_RING ||
1934              phba->sli.sli_flag & LPFC_PROCESS_LA)) {
1935
1936                 while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
1937                        (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
1938                         lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
1939
1940                 if (iocb)
1941                         lpfc_sli_update_ring(phba, pring);
1942                 else
1943                         lpfc_sli_update_full_ring(phba, pring);
1944         }
1945
1946         return;
1947 }
1948
1949 /**
1950  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
1951  * @phba: Pointer to HBA context object.
1952  * @hbqno: HBQ number.
1953  *
1954  * This function is called with hbalock held to get the next
1955  * available slot for the given HBQ. If there is free slot
1956  * available for the HBQ it will return pointer to the next available
1957  * HBQ entry else it will return NULL.
1958  **/
1959 static struct lpfc_hbq_entry *
1960 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
1961 {
1962         struct hbq_s *hbqp = &phba->hbqs[hbqno];
1963
1964         lockdep_assert_held(&phba->hbalock);
1965
1966         if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
1967             ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
1968                 hbqp->next_hbqPutIdx = 0;
1969
1970         if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
1971                 uint32_t raw_index = phba->hbq_get[hbqno];
1972                 uint32_t getidx = le32_to_cpu(raw_index);
1973
1974                 hbqp->local_hbqGetIdx = getidx;
1975
1976                 if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
1977                         lpfc_printf_log(phba, KERN_ERR,
1978                                         LOG_SLI | LOG_VPORT,
1979                                         "1802 HBQ %d: local_hbqGetIdx "
1980                                         "%u is > than hbqp->entry_count %u\n",
1981                                         hbqno, hbqp->local_hbqGetIdx,
1982                                         hbqp->entry_count);
1983
1984                         phba->link_state = LPFC_HBA_ERROR;
1985                         return NULL;
1986                 }
1987
1988                 if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
1989                         return NULL;
1990         }
1991
1992         return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
1993                         hbqp->hbqPutIdx;
1994 }
1995
1996 /**
1997  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
1998  * @phba: Pointer to HBA context object.
1999  *
2000  * This function is called with no lock held to free all the
2001  * hbq buffers while uninitializing the SLI interface. It also
2002  * frees the HBQ buffers returned by the firmware but not yet
2003  * processed by the upper layers.
2004  **/
2005 void
2006 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
2007 {
2008         struct lpfc_dmabuf *dmabuf, *next_dmabuf;
2009         struct hbq_dmabuf *hbq_buf;
2010         unsigned long flags;
2011         int i, hbq_count;
2012
2013         hbq_count = lpfc_sli_hbq_count();
2014         /* Return all memory used by all HBQs */
2015         spin_lock_irqsave(&phba->hbalock, flags);
2016         for (i = 0; i < hbq_count; ++i) {
2017                 list_for_each_entry_safe(dmabuf, next_dmabuf,
2018                                 &phba->hbqs[i].hbq_buffer_list, list) {
2019                         hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2020                         list_del(&hbq_buf->dbuf.list);
2021                         (phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2022                 }
2023                 phba->hbqs[i].buffer_count = 0;
2024         }
2025
2026         /* Mark the HBQs not in use */
2027         phba->hbq_in_use = 0;
2028         spin_unlock_irqrestore(&phba->hbalock, flags);
2029 }
2030
2031 /**
2032  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2033  * @phba: Pointer to HBA context object.
2034  * @hbqno: HBQ number.
2035  * @hbq_buf: Pointer to HBQ buffer.
2036  *
2037  * This function is called with the hbalock held to post a
2038  * hbq buffer to the firmware. If the function finds an empty
2039  * slot in the HBQ, it will post the buffer. The function will return
2040  * pointer to the hbq entry if it successfully post the buffer
2041  * else it will return NULL.
2042  **/
2043 static int
2044 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2045                          struct hbq_dmabuf *hbq_buf)
2046 {
2047         lockdep_assert_held(&phba->hbalock);
2048         return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2049 }
2050
2051 /**
2052  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2053  * @phba: Pointer to HBA context object.
2054  * @hbqno: HBQ number.
2055  * @hbq_buf: Pointer to HBQ buffer.
2056  *
2057  * This function is called with the hbalock held to post a hbq buffer to the
2058  * firmware. If the function finds an empty slot in the HBQ, it will post the
2059  * buffer and place it on the hbq_buffer_list. The function will return zero if
2060  * it successfully post the buffer else it will return an error.
2061  **/
2062 static int
2063 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2064                             struct hbq_dmabuf *hbq_buf)
2065 {
2066         struct lpfc_hbq_entry *hbqe;
2067         dma_addr_t physaddr = hbq_buf->dbuf.phys;
2068
2069         lockdep_assert_held(&phba->hbalock);
2070         /* Get next HBQ entry slot to use */
2071         hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2072         if (hbqe) {
2073                 struct hbq_s *hbqp = &phba->hbqs[hbqno];
2074
2075                 hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2076                 hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2077                 hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2078                 hbqe->bde.tus.f.bdeFlags = 0;
2079                 hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2080                 hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2081                                 /* Sync SLIM */
2082                 hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2083                 writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2084                                 /* flush */
2085                 readl(phba->hbq_put + hbqno);
2086                 list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2087                 return 0;
2088         } else
2089                 return -ENOMEM;
2090 }
2091
2092 /**
2093  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2094  * @phba: Pointer to HBA context object.
2095  * @hbqno: HBQ number.
2096  * @hbq_buf: Pointer to HBQ buffer.
2097  *
2098  * This function is called with the hbalock held to post an RQE to the SLI4
2099  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2100  * the hbq_buffer_list and return zero, otherwise it will return an error.
2101  **/
2102 static int
2103 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2104                             struct hbq_dmabuf *hbq_buf)
2105 {
2106         int rc;
2107         struct lpfc_rqe hrqe;
2108         struct lpfc_rqe drqe;
2109         struct lpfc_queue *hrq;
2110         struct lpfc_queue *drq;
2111
2112         if (hbqno != LPFC_ELS_HBQ)
2113                 return 1;
2114         hrq = phba->sli4_hba.hdr_rq;
2115         drq = phba->sli4_hba.dat_rq;
2116
2117         lockdep_assert_held(&phba->hbalock);
2118         hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2119         hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2120         drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2121         drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2122         rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2123         if (rc < 0)
2124                 return rc;
2125         hbq_buf->tag = (rc | (hbqno << 16));
2126         list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2127         return 0;
2128 }
2129
2130 /* HBQ for ELS and CT traffic. */
2131 static struct lpfc_hbq_init lpfc_els_hbq = {
2132         .rn = 1,
2133         .entry_count = 256,
2134         .mask_count = 0,
2135         .profile = 0,
2136         .ring_mask = (1 << LPFC_ELS_RING),
2137         .buffer_count = 0,
2138         .init_count = 40,
2139         .add_count = 40,
2140 };
2141
2142 /* Array of HBQs */
2143 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2144         &lpfc_els_hbq,
2145 };
2146
2147 /**
2148  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2149  * @phba: Pointer to HBA context object.
2150  * @hbqno: HBQ number.
2151  * @count: Number of HBQ buffers to be posted.
2152  *
2153  * This function is called with no lock held to post more hbq buffers to the
2154  * given HBQ. The function returns the number of HBQ buffers successfully
2155  * posted.
2156  **/
2157 static int
2158 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2159 {
2160         uint32_t i, posted = 0;
2161         unsigned long flags;
2162         struct hbq_dmabuf *hbq_buffer;
2163         LIST_HEAD(hbq_buf_list);
2164         if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2165                 return 0;
2166
2167         if ((phba->hbqs[hbqno].buffer_count + count) >
2168             lpfc_hbq_defs[hbqno]->entry_count)
2169                 count = lpfc_hbq_defs[hbqno]->entry_count -
2170                                         phba->hbqs[hbqno].buffer_count;
2171         if (!count)
2172                 return 0;
2173         /* Allocate HBQ entries */
2174         for (i = 0; i < count; i++) {
2175                 hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2176                 if (!hbq_buffer)
2177                         break;
2178                 list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2179         }
2180         /* Check whether HBQ is still in use */
2181         spin_lock_irqsave(&phba->hbalock, flags);
2182         if (!phba->hbq_in_use)
2183                 goto err;
2184         while (!list_empty(&hbq_buf_list)) {
2185                 list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2186                                  dbuf.list);
2187                 hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2188                                       (hbqno << 16));
2189                 if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2190                         phba->hbqs[hbqno].buffer_count++;
2191                         posted++;
2192                 } else
2193                         (phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2194         }
2195         spin_unlock_irqrestore(&phba->hbalock, flags);
2196         return posted;
2197 err:
2198         spin_unlock_irqrestore(&phba->hbalock, flags);
2199         while (!list_empty(&hbq_buf_list)) {
2200                 list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2201                                  dbuf.list);
2202                 (phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2203         }
2204         return 0;
2205 }
2206
2207 /**
2208  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2209  * @phba: Pointer to HBA context object.
2210  * @qno: HBQ number.
2211  *
2212  * This function posts more buffers to the HBQ. This function
2213  * is called with no lock held. The function returns the number of HBQ entries
2214  * successfully allocated.
2215  **/
2216 int
2217 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2218 {
2219         if (phba->sli_rev == LPFC_SLI_REV4)
2220                 return 0;
2221         else
2222                 return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2223                                          lpfc_hbq_defs[qno]->add_count);
2224 }
2225
2226 /**
2227  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2228  * @phba: Pointer to HBA context object.
2229  * @qno:  HBQ queue number.
2230  *
2231  * This function is called from SLI initialization code path with
2232  * no lock held to post initial HBQ buffers to firmware. The
2233  * function returns the number of HBQ entries successfully allocated.
2234  **/
2235 static int
2236 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2237 {
2238         if (phba->sli_rev == LPFC_SLI_REV4)
2239                 return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2240                                         lpfc_hbq_defs[qno]->entry_count);
2241         else
2242                 return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2243                                          lpfc_hbq_defs[qno]->init_count);
2244 }
2245
2246 /**
2247  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2248  * @phba: Pointer to HBA context object.
2249  * @hbqno: HBQ number.
2250  *
2251  * This function removes the first hbq buffer on an hbq list and returns a
2252  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2253  **/
2254 static struct hbq_dmabuf *
2255 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2256 {
2257         struct lpfc_dmabuf *d_buf;
2258
2259         list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2260         if (!d_buf)
2261                 return NULL;
2262         return container_of(d_buf, struct hbq_dmabuf, dbuf);
2263 }
2264
2265 /**
2266  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2267  * @phba: Pointer to HBA context object.
2268  * @hbqno: HBQ number.
2269  *
2270  * This function removes the first RQ buffer on an RQ buffer list and returns a
2271  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2272  **/
2273 static struct rqb_dmabuf *
2274 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2275 {
2276         struct lpfc_dmabuf *h_buf;
2277         struct lpfc_rqb *rqbp;
2278
2279         rqbp = hrq->rqbp;
2280         list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2281                          struct lpfc_dmabuf, list);
2282         if (!h_buf)
2283                 return NULL;
2284         rqbp->buffer_count--;
2285         return container_of(h_buf, struct rqb_dmabuf, hbuf);
2286 }
2287
2288 /**
2289  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2290  * @phba: Pointer to HBA context object.
2291  * @tag: Tag of the hbq buffer.
2292  *
2293  * This function searches for the hbq buffer associated with the given tag in
2294  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2295  * otherwise it returns NULL.
2296  **/
2297 static struct hbq_dmabuf *
2298 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2299 {
2300         struct lpfc_dmabuf *d_buf;
2301         struct hbq_dmabuf *hbq_buf;
2302         uint32_t hbqno;
2303
2304         hbqno = tag >> 16;
2305         if (hbqno >= LPFC_MAX_HBQS)
2306                 return NULL;
2307
2308         spin_lock_irq(&phba->hbalock);
2309         list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2310                 hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2311                 if (hbq_buf->tag == tag) {
2312                         spin_unlock_irq(&phba->hbalock);
2313                         return hbq_buf;
2314                 }
2315         }
2316         spin_unlock_irq(&phba->hbalock);
2317         lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_VPORT,
2318                         "1803 Bad hbq tag. Data: x%x x%x\n",
2319                         tag, phba->hbqs[tag >> 16].buffer_count);
2320         return NULL;
2321 }
2322
2323 /**
2324  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2325  * @phba: Pointer to HBA context object.
2326  * @hbq_buffer: Pointer to HBQ buffer.
2327  *
2328  * This function is called with hbalock. This function gives back
2329  * the hbq buffer to firmware. If the HBQ does not have space to
2330  * post the buffer, it will free the buffer.
2331  **/
2332 void
2333 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2334 {
2335         uint32_t hbqno;
2336
2337         if (hbq_buffer) {
2338                 hbqno = hbq_buffer->tag >> 16;
2339                 if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2340                         (phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2341         }
2342 }
2343
2344 /**
2345  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2346  * @mbxCommand: mailbox command code.
2347  *
2348  * This function is called by the mailbox event handler function to verify
2349  * that the completed mailbox command is a legitimate mailbox command. If the
2350  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2351  * and the mailbox event handler will take the HBA offline.
2352  **/
2353 static int
2354 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2355 {
2356         uint8_t ret;
2357
2358         switch (mbxCommand) {
2359         case MBX_LOAD_SM:
2360         case MBX_READ_NV:
2361         case MBX_WRITE_NV:
2362         case MBX_WRITE_VPARMS:
2363         case MBX_RUN_BIU_DIAG:
2364         case MBX_INIT_LINK:
2365         case MBX_DOWN_LINK:
2366         case MBX_CONFIG_LINK:
2367         case MBX_CONFIG_RING:
2368         case MBX_RESET_RING:
2369         case MBX_READ_CONFIG:
2370         case MBX_READ_RCONFIG:
2371         case MBX_READ_SPARM:
2372         case MBX_READ_STATUS:
2373         case MBX_READ_RPI:
2374         case MBX_READ_XRI:
2375         case MBX_READ_REV:
2376         case MBX_READ_LNK_STAT:
2377         case MBX_REG_LOGIN:
2378         case MBX_UNREG_LOGIN:
2379         case MBX_CLEAR_LA:
2380         case MBX_DUMP_MEMORY:
2381         case MBX_DUMP_CONTEXT:
2382         case MBX_RUN_DIAGS:
2383         case MBX_RESTART:
2384         case MBX_UPDATE_CFG:
2385         case MBX_DOWN_LOAD:
2386         case MBX_DEL_LD_ENTRY:
2387         case MBX_RUN_PROGRAM:
2388         case MBX_SET_MASK:
2389         case MBX_SET_VARIABLE:
2390         case MBX_UNREG_D_ID:
2391         case MBX_KILL_BOARD:
2392         case MBX_CONFIG_FARP:
2393         case MBX_BEACON:
2394         case MBX_LOAD_AREA:
2395         case MBX_RUN_BIU_DIAG64:
2396         case MBX_CONFIG_PORT:
2397         case MBX_READ_SPARM64:
2398         case MBX_READ_RPI64:
2399         case MBX_REG_LOGIN64:
2400         case MBX_READ_TOPOLOGY:
2401         case MBX_WRITE_WWN:
2402         case MBX_SET_DEBUG:
2403         case MBX_LOAD_EXP_ROM:
2404         case MBX_ASYNCEVT_ENABLE:
2405         case MBX_REG_VPI:
2406         case MBX_UNREG_VPI:
2407         case MBX_HEARTBEAT:
2408         case MBX_PORT_CAPABILITIES:
2409         case MBX_PORT_IOV_CONTROL:
2410         case MBX_SLI4_CONFIG:
2411         case MBX_SLI4_REQ_FTRS:
2412         case MBX_REG_FCFI:
2413         case MBX_UNREG_FCFI:
2414         case MBX_REG_VFI:
2415         case MBX_UNREG_VFI:
2416         case MBX_INIT_VPI:
2417         case MBX_INIT_VFI:
2418         case MBX_RESUME_RPI:
2419         case MBX_READ_EVENT_LOG_STATUS:
2420         case MBX_READ_EVENT_LOG:
2421         case MBX_SECURITY_MGMT:
2422         case MBX_AUTH_PORT:
2423         case MBX_ACCESS_VDATA:
2424                 ret = mbxCommand;
2425                 break;
2426         default:
2427                 ret = MBX_SHUTDOWN;
2428                 break;
2429         }
2430         return ret;
2431 }
2432
2433 /**
2434  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2435  * @phba: Pointer to HBA context object.
2436  * @pmboxq: Pointer to mailbox command.
2437  *
2438  * This is completion handler function for mailbox commands issued from
2439  * lpfc_sli_issue_mbox_wait function. This function is called by the
2440  * mailbox event handler function with no lock held. This function
2441  * will wake up thread waiting on the wait queue pointed by context1
2442  * of the mailbox.
2443  **/
2444 void
2445 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2446 {
2447         unsigned long drvr_flag;
2448         struct completion *pmbox_done;
2449
2450         /*
2451          * If pmbox_done is empty, the driver thread gave up waiting and
2452          * continued running.
2453          */
2454         pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2455         spin_lock_irqsave(&phba->hbalock, drvr_flag);
2456         pmbox_done = (struct completion *)pmboxq->context3;
2457         if (pmbox_done)
2458                 complete(pmbox_done);
2459         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2460         return;
2461 }
2462
2463 static void
2464 __lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2465 {
2466         unsigned long iflags;
2467
2468         if (ndlp->nlp_flag & NLP_RELEASE_RPI) {
2469                 lpfc_sli4_free_rpi(vport->phba, ndlp->nlp_rpi);
2470                 spin_lock_irqsave(&vport->phba->ndlp_lock, iflags);
2471                 ndlp->nlp_flag &= ~NLP_RELEASE_RPI;
2472                 ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
2473                 spin_unlock_irqrestore(&vport->phba->ndlp_lock, iflags);
2474         }
2475         ndlp->nlp_flag &= ~NLP_UNREG_INP;
2476 }
2477
2478 /**
2479  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2480  * @phba: Pointer to HBA context object.
2481  * @pmb: Pointer to mailbox object.
2482  *
2483  * This function is the default mailbox completion handler. It
2484  * frees the memory resources associated with the completed mailbox
2485  * command. If the completed command is a REG_LOGIN mailbox command,
2486  * this function will issue a UREG_LOGIN to re-claim the RPI.
2487  **/
2488 void
2489 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2490 {
2491         struct lpfc_vport  *vport = pmb->vport;
2492         struct lpfc_dmabuf *mp;
2493         struct lpfc_nodelist *ndlp;
2494         struct Scsi_Host *shost;
2495         uint16_t rpi, vpi;
2496         int rc;
2497
2498         mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
2499
2500         if (mp) {
2501                 lpfc_mbuf_free(phba, mp->virt, mp->phys);
2502                 kfree(mp);
2503         }
2504
2505         /*
2506          * If a REG_LOGIN succeeded  after node is destroyed or node
2507          * is in re-discovery driver need to cleanup the RPI.
2508          */
2509         if (!(phba->pport->load_flag & FC_UNLOADING) &&
2510             pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2511             !pmb->u.mb.mbxStatus) {
2512                 rpi = pmb->u.mb.un.varWords[0];
2513                 vpi = pmb->u.mb.un.varRegLogin.vpi;
2514                 if (phba->sli_rev == LPFC_SLI_REV4)
2515                         vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2516                 lpfc_unreg_login(phba, vpi, rpi, pmb);
2517                 pmb->vport = vport;
2518                 pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2519                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2520                 if (rc != MBX_NOT_FINISHED)
2521                         return;
2522         }
2523
2524         if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2525                 !(phba->pport->load_flag & FC_UNLOADING) &&
2526                 !pmb->u.mb.mbxStatus) {
2527                 shost = lpfc_shost_from_vport(vport);
2528                 spin_lock_irq(shost->host_lock);
2529                 vport->vpi_state |= LPFC_VPI_REGISTERED;
2530                 vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2531                 spin_unlock_irq(shost->host_lock);
2532         }
2533
2534         if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2535                 ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2536                 lpfc_nlp_put(ndlp);
2537                 pmb->ctx_buf = NULL;
2538                 pmb->ctx_ndlp = NULL;
2539         }
2540
2541         if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2542                 ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2543
2544                 /* Check to see if there are any deferred events to process */
2545                 if (ndlp) {
2546                         lpfc_printf_vlog(
2547                                 vport,
2548                                 KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2549                                 "1438 UNREG cmpl deferred mbox x%x "
2550                                 "on NPort x%x Data: x%x x%x %px\n",
2551                                 ndlp->nlp_rpi, ndlp->nlp_DID,
2552                                 ndlp->nlp_flag, ndlp->nlp_defer_did, ndlp);
2553
2554                         if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2555                             (ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING)) {
2556                                 ndlp->nlp_flag &= ~NLP_UNREG_INP;
2557                                 ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2558                                 lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2559                         } else {
2560                                 __lpfc_sli_rpi_release(vport, ndlp);
2561                         }
2562                         if (vport->load_flag & FC_UNLOADING)
2563                                 lpfc_nlp_put(ndlp);
2564                         pmb->ctx_ndlp = NULL;
2565                 }
2566         }
2567
2568         /* Check security permission status on INIT_LINK mailbox command */
2569         if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2570             (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2571                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
2572                                 "2860 SLI authentication is required "
2573                                 "for INIT_LINK but has not done yet\n");
2574
2575         if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2576                 lpfc_sli4_mbox_cmd_free(phba, pmb);
2577         else
2578                 mempool_free(pmb, phba->mbox_mem_pool);
2579 }
2580  /**
2581  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2582  * @phba: Pointer to HBA context object.
2583  * @pmb: Pointer to mailbox object.
2584  *
2585  * This function is the unreg rpi mailbox completion handler. It
2586  * frees the memory resources associated with the completed mailbox
2587  * command. An additional refrenece is put on the ndlp to prevent
2588  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2589  * the unreg mailbox command completes, this routine puts the
2590  * reference back.
2591  *
2592  **/
2593 void
2594 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2595 {
2596         struct lpfc_vport  *vport = pmb->vport;
2597         struct lpfc_nodelist *ndlp;
2598
2599         ndlp = pmb->ctx_ndlp;
2600         if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2601                 if (phba->sli_rev == LPFC_SLI_REV4 &&
2602                     (bf_get(lpfc_sli_intf_if_type,
2603                      &phba->sli4_hba.sli_intf) >=
2604                      LPFC_SLI_INTF_IF_TYPE_2)) {
2605                         if (ndlp) {
2606                                 lpfc_printf_vlog(
2607                                         vport, KERN_INFO, LOG_MBOX | LOG_SLI,
2608                                          "0010 UNREG_LOGIN vpi:%x "
2609                                          "rpi:%x DID:%x defer x%x flg x%x "
2610                                          "map:%x %px\n",
2611                                          vport->vpi, ndlp->nlp_rpi,
2612                                          ndlp->nlp_DID, ndlp->nlp_defer_did,
2613                                          ndlp->nlp_flag,
2614                                          ndlp->nlp_usg_map, ndlp);
2615                                 ndlp->nlp_flag &= ~NLP_LOGO_ACC;
2616                                 lpfc_nlp_put(ndlp);
2617
2618                                 /* Check to see if there are any deferred
2619                                  * events to process
2620                                  */
2621                                 if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2622                                     (ndlp->nlp_defer_did !=
2623                                     NLP_EVT_NOTHING_PENDING)) {
2624                                         lpfc_printf_vlog(
2625                                                 vport, KERN_INFO, LOG_DISCOVERY,
2626                                                 "4111 UNREG cmpl deferred "
2627                                                 "clr x%x on "
2628                                                 "NPort x%x Data: x%x x%px\n",
2629                                                 ndlp->nlp_rpi, ndlp->nlp_DID,
2630                                                 ndlp->nlp_defer_did, ndlp);
2631                                         ndlp->nlp_flag &= ~NLP_UNREG_INP;
2632                                         ndlp->nlp_defer_did =
2633                                                 NLP_EVT_NOTHING_PENDING;
2634                                         lpfc_issue_els_plogi(
2635                                                 vport, ndlp->nlp_DID, 0);
2636                                 } else {
2637                                         __lpfc_sli_rpi_release(vport, ndlp);
2638                                 }
2639                         }
2640                 }
2641         }
2642
2643         mempool_free(pmb, phba->mbox_mem_pool);
2644 }
2645
2646 /**
2647  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
2648  * @phba: Pointer to HBA context object.
2649  *
2650  * This function is called with no lock held. This function processes all
2651  * the completed mailbox commands and gives it to upper layers. The interrupt
2652  * service routine processes mailbox completion interrupt and adds completed
2653  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
2654  * Worker thread call lpfc_sli_handle_mb_event, which will return the
2655  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
2656  * function returns the mailbox commands to the upper layer by calling the
2657  * completion handler function of each mailbox.
2658  **/
2659 int
2660 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
2661 {
2662         MAILBOX_t *pmbox;
2663         LPFC_MBOXQ_t *pmb;
2664         int rc;
2665         LIST_HEAD(cmplq);
2666
2667         phba->sli.slistat.mbox_event++;
2668
2669         /* Get all completed mailboxe buffers into the cmplq */
2670         spin_lock_irq(&phba->hbalock);
2671         list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
2672         spin_unlock_irq(&phba->hbalock);
2673
2674         /* Get a Mailbox buffer to setup mailbox commands for callback */
2675         do {
2676                 list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
2677                 if (pmb == NULL)
2678                         break;
2679
2680                 pmbox = &pmb->u.mb;
2681
2682                 if (pmbox->mbxCommand != MBX_HEARTBEAT) {
2683                         if (pmb->vport) {
2684                                 lpfc_debugfs_disc_trc(pmb->vport,
2685                                         LPFC_DISC_TRC_MBOX_VPORT,
2686                                         "MBOX cmpl vport: cmd:x%x mb:x%x x%x",
2687                                         (uint32_t)pmbox->mbxCommand,
2688                                         pmbox->un.varWords[0],
2689                                         pmbox->un.varWords[1]);
2690                         }
2691                         else {
2692                                 lpfc_debugfs_disc_trc(phba->pport,
2693                                         LPFC_DISC_TRC_MBOX,
2694                                         "MBOX cmpl:       cmd:x%x mb:x%x x%x",
2695                                         (uint32_t)pmbox->mbxCommand,
2696                                         pmbox->un.varWords[0],
2697                                         pmbox->un.varWords[1]);
2698                         }
2699                 }
2700
2701                 /*
2702                  * It is a fatal error if unknown mbox command completion.
2703                  */
2704                 if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
2705                     MBX_SHUTDOWN) {
2706                         /* Unknown mailbox command compl */
2707                         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
2708                                         "(%d):0323 Unknown Mailbox command "
2709                                         "x%x (x%x/x%x) Cmpl\n",
2710                                         pmb->vport ? pmb->vport->vpi :
2711                                         LPFC_VPORT_UNKNOWN,
2712                                         pmbox->mbxCommand,
2713                                         lpfc_sli_config_mbox_subsys_get(phba,
2714                                                                         pmb),
2715                                         lpfc_sli_config_mbox_opcode_get(phba,
2716                                                                         pmb));
2717                         phba->link_state = LPFC_HBA_ERROR;
2718                         phba->work_hs = HS_FFER3;
2719                         lpfc_handle_eratt(phba);
2720                         continue;
2721                 }
2722
2723                 if (pmbox->mbxStatus) {
2724                         phba->sli.slistat.mbox_stat_err++;
2725                         if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
2726                                 /* Mbox cmd cmpl error - RETRYing */
2727                                 lpfc_printf_log(phba, KERN_INFO,
2728                                         LOG_MBOX | LOG_SLI,
2729                                         "(%d):0305 Mbox cmd cmpl "
2730                                         "error - RETRYing Data: x%x "
2731                                         "(x%x/x%x) x%x x%x x%x\n",
2732                                         pmb->vport ? pmb->vport->vpi :
2733                                         LPFC_VPORT_UNKNOWN,
2734                                         pmbox->mbxCommand,
2735                                         lpfc_sli_config_mbox_subsys_get(phba,
2736                                                                         pmb),
2737                                         lpfc_sli_config_mbox_opcode_get(phba,
2738                                                                         pmb),
2739                                         pmbox->mbxStatus,
2740                                         pmbox->un.varWords[0],
2741                                         pmb->vport ? pmb->vport->port_state :
2742                                         LPFC_VPORT_UNKNOWN);
2743                                 pmbox->mbxStatus = 0;
2744                                 pmbox->mbxOwner = OWN_HOST;
2745                                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2746                                 if (rc != MBX_NOT_FINISHED)
2747                                         continue;
2748                         }
2749                 }
2750
2751                 /* Mailbox cmd <cmd> Cmpl <cmpl> */
2752                 lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
2753                                 "(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
2754                                 "Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
2755                                 "x%x x%x x%x\n",
2756                                 pmb->vport ? pmb->vport->vpi : 0,
2757                                 pmbox->mbxCommand,
2758                                 lpfc_sli_config_mbox_subsys_get(phba, pmb),
2759                                 lpfc_sli_config_mbox_opcode_get(phba, pmb),
2760                                 pmb->mbox_cmpl,
2761                                 *((uint32_t *) pmbox),
2762                                 pmbox->un.varWords[0],
2763                                 pmbox->un.varWords[1],
2764                                 pmbox->un.varWords[2],
2765                                 pmbox->un.varWords[3],
2766                                 pmbox->un.varWords[4],
2767                                 pmbox->un.varWords[5],
2768                                 pmbox->un.varWords[6],
2769                                 pmbox->un.varWords[7],
2770                                 pmbox->un.varWords[8],
2771                                 pmbox->un.varWords[9],
2772                                 pmbox->un.varWords[10]);
2773
2774                 if (pmb->mbox_cmpl)
2775                         pmb->mbox_cmpl(phba,pmb);
2776         } while (1);
2777         return 0;
2778 }
2779
2780 /**
2781  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
2782  * @phba: Pointer to HBA context object.
2783  * @pring: Pointer to driver SLI ring object.
2784  * @tag: buffer tag.
2785  *
2786  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
2787  * is set in the tag the buffer is posted for a particular exchange,
2788  * the function will return the buffer without replacing the buffer.
2789  * If the buffer is for unsolicited ELS or CT traffic, this function
2790  * returns the buffer and also posts another buffer to the firmware.
2791  **/
2792 static struct lpfc_dmabuf *
2793 lpfc_sli_get_buff(struct lpfc_hba *phba,
2794                   struct lpfc_sli_ring *pring,
2795                   uint32_t tag)
2796 {
2797         struct hbq_dmabuf *hbq_entry;
2798
2799         if (tag & QUE_BUFTAG_BIT)
2800                 return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
2801         hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
2802         if (!hbq_entry)
2803                 return NULL;
2804         return &hbq_entry->dbuf;
2805 }
2806
2807 /**
2808  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
2809  * @phba: Pointer to HBA context object.
2810  * @pring: Pointer to driver SLI ring object.
2811  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
2812  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
2813  * @fch_type: the type for the first frame of the sequence.
2814  *
2815  * This function is called with no lock held. This function uses the r_ctl and
2816  * type of the received sequence to find the correct callback function to call
2817  * to process the sequence.
2818  **/
2819 static int
2820 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2821                          struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
2822                          uint32_t fch_type)
2823 {
2824         int i;
2825
2826         switch (fch_type) {
2827         case FC_TYPE_NVME:
2828                 lpfc_nvmet_unsol_ls_event(phba, pring, saveq);
2829                 return 1;
2830         default:
2831                 break;
2832         }
2833
2834         /* unSolicited Responses */
2835         if (pring->prt[0].profile) {
2836                 if (pring->prt[0].lpfc_sli_rcv_unsol_event)
2837                         (pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
2838                                                                         saveq);
2839                 return 1;
2840         }
2841         /* We must search, based on rctl / type
2842            for the right routine */
2843         for (i = 0; i < pring->num_mask; i++) {
2844                 if ((pring->prt[i].rctl == fch_r_ctl) &&
2845                     (pring->prt[i].type == fch_type)) {
2846                         if (pring->prt[i].lpfc_sli_rcv_unsol_event)
2847                                 (pring->prt[i].lpfc_sli_rcv_unsol_event)
2848                                                 (phba, pring, saveq);
2849                         return 1;
2850                 }
2851         }
2852         return 0;
2853 }
2854
2855 /**
2856  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
2857  * @phba: Pointer to HBA context object.
2858  * @pring: Pointer to driver SLI ring object.
2859  * @saveq: Pointer to the unsolicited iocb.
2860  *
2861  * This function is called with no lock held by the ring event handler
2862  * when there is an unsolicited iocb posted to the response ring by the
2863  * firmware. This function gets the buffer associated with the iocbs
2864  * and calls the event handler for the ring. This function handles both
2865  * qring buffers and hbq buffers.
2866  * When the function returns 1 the caller can free the iocb object otherwise
2867  * upper layer functions will free the iocb objects.
2868  **/
2869 static int
2870 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2871                             struct lpfc_iocbq *saveq)
2872 {
2873         IOCB_t           * irsp;
2874         WORD5            * w5p;
2875         uint32_t           Rctl, Type;
2876         struct lpfc_iocbq *iocbq;
2877         struct lpfc_dmabuf *dmzbuf;
2878
2879         irsp = &(saveq->iocb);
2880
2881         if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
2882                 if (pring->lpfc_sli_rcv_async_status)
2883                         pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
2884                 else
2885                         lpfc_printf_log(phba,
2886                                         KERN_WARNING,
2887                                         LOG_SLI,
2888                                         "0316 Ring %d handler: unexpected "
2889                                         "ASYNC_STATUS iocb received evt_code "
2890                                         "0x%x\n",
2891                                         pring->ringno,
2892                                         irsp->un.asyncstat.evt_code);
2893                 return 1;
2894         }
2895
2896         if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
2897                 (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
2898                 if (irsp->ulpBdeCount > 0) {
2899                         dmzbuf = lpfc_sli_get_buff(phba, pring,
2900                                         irsp->un.ulpWord[3]);
2901                         lpfc_in_buf_free(phba, dmzbuf);
2902                 }
2903
2904                 if (irsp->ulpBdeCount > 1) {
2905                         dmzbuf = lpfc_sli_get_buff(phba, pring,
2906                                         irsp->unsli3.sli3Words[3]);
2907                         lpfc_in_buf_free(phba, dmzbuf);
2908                 }
2909
2910                 if (irsp->ulpBdeCount > 2) {
2911                         dmzbuf = lpfc_sli_get_buff(phba, pring,
2912                                 irsp->unsli3.sli3Words[7]);
2913                         lpfc_in_buf_free(phba, dmzbuf);
2914                 }
2915
2916                 return 1;
2917         }
2918
2919         if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
2920                 if (irsp->ulpBdeCount != 0) {
2921                         saveq->context2 = lpfc_sli_get_buff(phba, pring,
2922                                                 irsp->un.ulpWord[3]);
2923                         if (!saveq->context2)
2924                                 lpfc_printf_log(phba,
2925                                         KERN_ERR,
2926                                         LOG_SLI,
2927                                         "0341 Ring %d Cannot find buffer for "
2928                                         "an unsolicited iocb. tag 0x%x\n",
2929                                         pring->ringno,
2930                                         irsp->un.ulpWord[3]);
2931                 }
2932                 if (irsp->ulpBdeCount == 2) {
2933                         saveq->context3 = lpfc_sli_get_buff(phba, pring,
2934                                                 irsp->unsli3.sli3Words[7]);
2935                         if (!saveq->context3)
2936                                 lpfc_printf_log(phba,
2937                                         KERN_ERR,
2938                                         LOG_SLI,
2939                                         "0342 Ring %d Cannot find buffer for an"
2940                                         " unsolicited iocb. tag 0x%x\n",
2941                                         pring->ringno,
2942                                         irsp->unsli3.sli3Words[7]);
2943                 }
2944                 list_for_each_entry(iocbq, &saveq->list, list) {
2945                         irsp = &(iocbq->iocb);
2946                         if (irsp->ulpBdeCount != 0) {
2947                                 iocbq->context2 = lpfc_sli_get_buff(phba, pring,
2948                                                         irsp->un.ulpWord[3]);
2949                                 if (!iocbq->context2)
2950                                         lpfc_printf_log(phba,
2951                                                 KERN_ERR,
2952                                                 LOG_SLI,
2953                                                 "0343 Ring %d Cannot find "
2954                                                 "buffer for an unsolicited iocb"
2955                                                 ". tag 0x%x\n", pring->ringno,
2956                                                 irsp->un.ulpWord[3]);
2957                         }
2958                         if (irsp->ulpBdeCount == 2) {
2959                                 iocbq->context3 = lpfc_sli_get_buff(phba, pring,
2960                                                 irsp->unsli3.sli3Words[7]);
2961                                 if (!iocbq->context3)
2962                                         lpfc_printf_log(phba,
2963                                                 KERN_ERR,
2964                                                 LOG_SLI,
2965                                                 "0344 Ring %d Cannot find "
2966                                                 "buffer for an unsolicited "
2967                                                 "iocb. tag 0x%x\n",
2968                                                 pring->ringno,
2969                                                 irsp->unsli3.sli3Words[7]);
2970                         }
2971                 }
2972         }
2973         if (irsp->ulpBdeCount != 0 &&
2974             (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
2975              irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
2976                 int found = 0;
2977
2978                 /* search continue save q for same XRI */
2979                 list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
2980                         if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
2981                                 saveq->iocb.unsli3.rcvsli3.ox_id) {
2982                                 list_add_tail(&saveq->list, &iocbq->list);
2983                                 found = 1;
2984                                 break;
2985                         }
2986                 }
2987                 if (!found)
2988                         list_add_tail(&saveq->clist,
2989                                       &pring->iocb_continue_saveq);
2990                 if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
2991                         list_del_init(&iocbq->clist);
2992                         saveq = iocbq;
2993                         irsp = &(saveq->iocb);
2994                 } else
2995                         return 0;
2996         }
2997         if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
2998             (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
2999             (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3000                 Rctl = FC_RCTL_ELS_REQ;
3001                 Type = FC_TYPE_ELS;
3002         } else {
3003                 w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3004                 Rctl = w5p->hcsw.Rctl;
3005                 Type = w5p->hcsw.Type;
3006
3007                 /* Firmware Workaround */
3008                 if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3009                         (irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3010                          irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3011                         Rctl = FC_RCTL_ELS_REQ;
3012                         Type = FC_TYPE_ELS;
3013                         w5p->hcsw.Rctl = Rctl;
3014                         w5p->hcsw.Type = Type;
3015                 }
3016         }
3017
3018         if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3019                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3020                                 "0313 Ring %d handler: unexpected Rctl x%x "
3021                                 "Type x%x received\n",
3022                                 pring->ringno, Rctl, Type);
3023
3024         return 1;
3025 }
3026
3027 /**
3028  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3029  * @phba: Pointer to HBA context object.
3030  * @pring: Pointer to driver SLI ring object.
3031  * @prspiocb: Pointer to response iocb object.
3032  *
3033  * This function looks up the iocb_lookup table to get the command iocb
3034  * corresponding to the given response iocb using the iotag of the
3035  * response iocb. The driver calls this function with the hbalock held
3036  * for SLI3 ports or the ring lock held for SLI4 ports.
3037  * This function returns the command iocb object if it finds the command
3038  * iocb else returns NULL.
3039  **/
3040 static struct lpfc_iocbq *
3041 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3042                       struct lpfc_sli_ring *pring,
3043                       struct lpfc_iocbq *prspiocb)
3044 {
3045         struct lpfc_iocbq *cmd_iocb = NULL;
3046         uint16_t iotag;
3047         spinlock_t *temp_lock = NULL;
3048         unsigned long iflag = 0;
3049
3050         if (phba->sli_rev == LPFC_SLI_REV4)
3051                 temp_lock = &pring->ring_lock;
3052         else
3053                 temp_lock = &phba->hbalock;
3054
3055         spin_lock_irqsave(temp_lock, iflag);
3056         iotag = prspiocb->iocb.ulpIoTag;
3057
3058         if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3059                 cmd_iocb = phba->sli.iocbq_lookup[iotag];
3060                 if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3061                         /* remove from txcmpl queue list */
3062                         list_del_init(&cmd_iocb->list);
3063                         cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3064                         pring->txcmplq_cnt--;
3065                         spin_unlock_irqrestore(temp_lock, iflag);
3066                         return cmd_iocb;
3067                 }
3068         }
3069
3070         spin_unlock_irqrestore(temp_lock, iflag);
3071         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3072                         "0317 iotag x%x is out of "
3073                         "range: max iotag x%x wd0 x%x\n",
3074                         iotag, phba->sli.last_iotag,
3075                         *(((uint32_t *) &prspiocb->iocb) + 7));
3076         return NULL;
3077 }
3078
3079 /**
3080  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3081  * @phba: Pointer to HBA context object.
3082  * @pring: Pointer to driver SLI ring object.
3083  * @iotag: IOCB tag.
3084  *
3085  * This function looks up the iocb_lookup table to get the command iocb
3086  * corresponding to the given iotag. The driver calls this function with
3087  * the ring lock held because this function is an SLI4 port only helper.
3088  * This function returns the command iocb object if it finds the command
3089  * iocb else returns NULL.
3090  **/
3091 static struct lpfc_iocbq *
3092 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3093                              struct lpfc_sli_ring *pring, uint16_t iotag)
3094 {
3095         struct lpfc_iocbq *cmd_iocb = NULL;
3096         spinlock_t *temp_lock = NULL;
3097         unsigned long iflag = 0;
3098
3099         if (phba->sli_rev == LPFC_SLI_REV4)
3100                 temp_lock = &pring->ring_lock;
3101         else
3102                 temp_lock = &phba->hbalock;
3103
3104         spin_lock_irqsave(temp_lock, iflag);
3105         if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3106                 cmd_iocb = phba->sli.iocbq_lookup[iotag];
3107                 if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3108                         /* remove from txcmpl queue list */
3109                         list_del_init(&cmd_iocb->list);
3110                         cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3111                         pring->txcmplq_cnt--;
3112                         spin_unlock_irqrestore(temp_lock, iflag);
3113                         return cmd_iocb;
3114                 }
3115         }
3116
3117         spin_unlock_irqrestore(temp_lock, iflag);
3118         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3119                         "0372 iotag x%x lookup error: max iotag (x%x) "
3120                         "iocb_flag x%x\n",
3121                         iotag, phba->sli.last_iotag,
3122                         cmd_iocb ? cmd_iocb->iocb_flag : 0xffff);
3123         return NULL;
3124 }
3125
3126 /**
3127  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3128  * @phba: Pointer to HBA context object.
3129  * @pring: Pointer to driver SLI ring object.
3130  * @saveq: Pointer to the response iocb to be processed.
3131  *
3132  * This function is called by the ring event handler for non-fcp
3133  * rings when there is a new response iocb in the response ring.
3134  * The caller is not required to hold any locks. This function
3135  * gets the command iocb associated with the response iocb and
3136  * calls the completion handler for the command iocb. If there
3137  * is no completion handler, the function will free the resources
3138  * associated with command iocb. If the response iocb is for
3139  * an already aborted command iocb, the status of the completion
3140  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3141  * This function always returns 1.
3142  **/
3143 static int
3144 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3145                           struct lpfc_iocbq *saveq)
3146 {
3147         struct lpfc_iocbq *cmdiocbp;
3148         int rc = 1;
3149         unsigned long iflag;
3150
3151         cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3152         if (cmdiocbp) {
3153                 if (cmdiocbp->iocb_cmpl) {
3154                         /*
3155                          * If an ELS command failed send an event to mgmt
3156                          * application.
3157                          */
3158                         if (saveq->iocb.ulpStatus &&
3159                              (pring->ringno == LPFC_ELS_RING) &&
3160                              (cmdiocbp->iocb.ulpCommand ==
3161                                 CMD_ELS_REQUEST64_CR))
3162                                 lpfc_send_els_failure_event(phba,
3163                                         cmdiocbp, saveq);
3164
3165                         /*
3166                          * Post all ELS completions to the worker thread.
3167                          * All other are passed to the completion callback.
3168                          */
3169                         if (pring->ringno == LPFC_ELS_RING) {
3170                                 if ((phba->sli_rev < LPFC_SLI_REV4) &&
3171                                     (cmdiocbp->iocb_flag &
3172                                                         LPFC_DRIVER_ABORTED)) {
3173                                         spin_lock_irqsave(&phba->hbalock,
3174                                                           iflag);
3175                                         cmdiocbp->iocb_flag &=
3176                                                 ~LPFC_DRIVER_ABORTED;
3177                                         spin_unlock_irqrestore(&phba->hbalock,
3178                                                                iflag);
3179                                         saveq->iocb.ulpStatus =
3180                                                 IOSTAT_LOCAL_REJECT;
3181                                         saveq->iocb.un.ulpWord[4] =
3182                                                 IOERR_SLI_ABORTED;
3183
3184                                         /* Firmware could still be in progress
3185                                          * of DMAing payload, so don't free data
3186                                          * buffer till after a hbeat.
3187                                          */
3188                                         spin_lock_irqsave(&phba->hbalock,
3189                                                           iflag);
3190                                         saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
3191                                         spin_unlock_irqrestore(&phba->hbalock,
3192                                                                iflag);
3193                                 }
3194                                 if (phba->sli_rev == LPFC_SLI_REV4) {
3195                                         if (saveq->iocb_flag &
3196                                             LPFC_EXCHANGE_BUSY) {
3197                                                 /* Set cmdiocb flag for the
3198                                                  * exchange busy so sgl (xri)
3199                                                  * will not be released until
3200                                                  * the abort xri is received
3201                                                  * from hba.
3202                                                  */
3203                                                 spin_lock_irqsave(
3204                                                         &phba->hbalock, iflag);
3205                                                 cmdiocbp->iocb_flag |=
3206                                                         LPFC_EXCHANGE_BUSY;
3207                                                 spin_unlock_irqrestore(
3208                                                         &phba->hbalock, iflag);
3209                                         }
3210                                         if (cmdiocbp->iocb_flag &
3211                                             LPFC_DRIVER_ABORTED) {
3212                                                 /*
3213                                                  * Clear LPFC_DRIVER_ABORTED
3214                                                  * bit in case it was driver
3215                                                  * initiated abort.
3216                                                  */
3217                                                 spin_lock_irqsave(
3218                                                         &phba->hbalock, iflag);
3219                                                 cmdiocbp->iocb_flag &=
3220                                                         ~LPFC_DRIVER_ABORTED;
3221                                                 spin_unlock_irqrestore(
3222                                                         &phba->hbalock, iflag);
3223                                                 cmdiocbp->iocb.ulpStatus =
3224                                                         IOSTAT_LOCAL_REJECT;
3225                                                 cmdiocbp->iocb.un.ulpWord[4] =
3226                                                         IOERR_ABORT_REQUESTED;
3227                                                 /*
3228                                                  * For SLI4, irsiocb contains
3229                                                  * NO_XRI in sli_xritag, it
3230                                                  * shall not affect releasing
3231                                                  * sgl (xri) process.
3232                                                  */
3233                                                 saveq->iocb.ulpStatus =
3234                                                         IOSTAT_LOCAL_REJECT;
3235                                                 saveq->iocb.un.ulpWord[4] =
3236                                                         IOERR_SLI_ABORTED;
3237                                                 spin_lock_irqsave(
3238                                                         &phba->hbalock, iflag);
3239                                                 saveq->iocb_flag |=
3240                                                         LPFC_DELAY_MEM_FREE;
3241                                                 spin_unlock_irqrestore(
3242                                                         &phba->hbalock, iflag);
3243                                         }
3244                                 }
3245                         }
3246                         (cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
3247                 } else
3248                         lpfc_sli_release_iocbq(phba, cmdiocbp);
3249         } else {
3250                 /*
3251                  * Unknown initiating command based on the response iotag.
3252                  * This could be the case on the ELS ring because of
3253                  * lpfc_els_abort().
3254                  */
3255                 if (pring->ringno != LPFC_ELS_RING) {
3256                         /*
3257                          * Ring <ringno> handler: unexpected completion IoTag
3258                          * <IoTag>
3259                          */
3260                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3261                                          "0322 Ring %d handler: "
3262                                          "unexpected completion IoTag x%x "
3263                                          "Data: x%x x%x x%x x%x\n",
3264                                          pring->ringno,
3265                                          saveq->iocb.ulpIoTag,
3266                                          saveq->iocb.ulpStatus,
3267                                          saveq->iocb.un.ulpWord[4],
3268                                          saveq->iocb.ulpCommand,
3269                                          saveq->iocb.ulpContext);
3270                 }
3271         }
3272
3273         return rc;
3274 }
3275
3276 /**
3277  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3278  * @phba: Pointer to HBA context object.
3279  * @pring: Pointer to driver SLI ring object.
3280  *
3281  * This function is called from the iocb ring event handlers when
3282  * put pointer is ahead of the get pointer for a ring. This function signal
3283  * an error attention condition to the worker thread and the worker
3284  * thread will transition the HBA to offline state.
3285  **/
3286 static void
3287 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3288 {
3289         struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3290         /*
3291          * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3292          * rsp ring <portRspMax>
3293          */
3294         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3295                         "0312 Ring %d handler: portRspPut %d "
3296                         "is bigger than rsp ring %d\n",
3297                         pring->ringno, le32_to_cpu(pgp->rspPutInx),
3298                         pring->sli.sli3.numRiocb);
3299
3300         phba->link_state = LPFC_HBA_ERROR;
3301
3302         /*
3303          * All error attention handlers are posted to
3304          * worker thread
3305          */
3306         phba->work_ha |= HA_ERATT;
3307         phba->work_hs = HS_FFER3;
3308
3309         lpfc_worker_wake_up(phba);
3310
3311         return;
3312 }
3313
3314 /**
3315  * lpfc_poll_eratt - Error attention polling timer timeout handler
3316  * @ptr: Pointer to address of HBA context object.
3317  *
3318  * This function is invoked by the Error Attention polling timer when the
3319  * timer times out. It will check the SLI Error Attention register for
3320  * possible attention events. If so, it will post an Error Attention event
3321  * and wake up worker thread to process it. Otherwise, it will set up the
3322  * Error Attention polling timer for the next poll.
3323  **/
3324 void lpfc_poll_eratt(struct timer_list *t)
3325 {
3326         struct lpfc_hba *phba;
3327         uint32_t eratt = 0;
3328         uint64_t sli_intr, cnt;
3329
3330         phba = from_timer(phba, t, eratt_poll);
3331
3332         /* Here we will also keep track of interrupts per sec of the hba */
3333         sli_intr = phba->sli.slistat.sli_intr;
3334
3335         if (phba->sli.slistat.sli_prev_intr > sli_intr)
3336                 cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3337                         sli_intr);
3338         else
3339                 cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3340
3341         /* 64-bit integer division not supported on 32-bit x86 - use do_div */
3342         do_div(cnt, phba->eratt_poll_interval);
3343         phba->sli.slistat.sli_ips = cnt;
3344
3345         phba->sli.slistat.sli_prev_intr = sli_intr;
3346
3347         /* Check chip HA register for error event */
3348         eratt = lpfc_sli_check_eratt(phba);
3349
3350         if (eratt)
3351                 /* Tell the worker thread there is work to do */
3352                 lpfc_worker_wake_up(phba);
3353         else
3354                 /* Restart the timer for next eratt poll */
3355                 mod_timer(&phba->eratt_poll,
3356                           jiffies +
3357                           msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3358         return;
3359 }
3360
3361
3362 /**
3363  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3364  * @phba: Pointer to HBA context object.
3365  * @pring: Pointer to driver SLI ring object.
3366  * @mask: Host attention register mask for this ring.
3367  *
3368  * This function is called from the interrupt context when there is a ring
3369  * event for the fcp ring. The caller does not hold any lock.
3370  * The function processes each response iocb in the response ring until it
3371  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3372  * LE bit set. The function will call the completion handler of the command iocb
3373  * if the response iocb indicates a completion for a command iocb or it is
3374  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3375  * function if this is an unsolicited iocb.
3376  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3377  * to check it explicitly.
3378  */
3379 int
3380 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3381                                 struct lpfc_sli_ring *pring, uint32_t mask)
3382 {
3383         struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3384         IOCB_t *irsp = NULL;
3385         IOCB_t *entry = NULL;
3386         struct lpfc_iocbq *cmdiocbq = NULL;
3387         struct lpfc_iocbq rspiocbq;
3388         uint32_t status;
3389         uint32_t portRspPut, portRspMax;
3390         int rc = 1;
3391         lpfc_iocb_type type;
3392         unsigned long iflag;
3393         uint32_t rsp_cmpl = 0;
3394
3395         spin_lock_irqsave(&phba->hbalock, iflag);
3396         pring->stats.iocb_event++;
3397
3398         /*
3399          * The next available response entry should never exceed the maximum
3400          * entries.  If it does, treat it as an adapter hardware error.
3401          */
3402         portRspMax = pring->sli.sli3.numRiocb;
3403         portRspPut = le32_to_cpu(pgp->rspPutInx);
3404         if (unlikely(portRspPut >= portRspMax)) {
3405                 lpfc_sli_rsp_pointers_error(phba, pring);
3406                 spin_unlock_irqrestore(&phba->hbalock, iflag);
3407                 return 1;
3408         }
3409         if (phba->fcp_ring_in_use) {
3410                 spin_unlock_irqrestore(&phba->hbalock, iflag);
3411                 return 1;
3412         } else
3413                 phba->fcp_ring_in_use = 1;
3414
3415         rmb();
3416         while (pring->sli.sli3.rspidx != portRspPut) {
3417                 /*
3418                  * Fetch an entry off the ring and copy it into a local data
3419                  * structure.  The copy involves a byte-swap since the
3420                  * network byte order and pci byte orders are different.
3421                  */
3422                 entry = lpfc_resp_iocb(phba, pring);
3423                 phba->last_completion_time = jiffies;
3424
3425                 if (++pring->sli.sli3.rspidx >= portRspMax)
3426                         pring->sli.sli3.rspidx = 0;
3427
3428                 lpfc_sli_pcimem_bcopy((uint32_t *) entry,
3429                                       (uint32_t *) &rspiocbq.iocb,
3430                                       phba->iocb_rsp_size);
3431                 INIT_LIST_HEAD(&(rspiocbq.list));
3432                 irsp = &rspiocbq.iocb;
3433
3434                 type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
3435                 pring->stats.iocb_rsp++;
3436                 rsp_cmpl++;
3437
3438                 if (unlikely(irsp->ulpStatus)) {
3439                         /*
3440                          * If resource errors reported from HBA, reduce
3441                          * queuedepths of the SCSI device.
3442                          */
3443                         if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3444                             ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3445                              IOERR_NO_RESOURCES)) {
3446                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
3447                                 phba->lpfc_rampdown_queue_depth(phba);
3448                                 spin_lock_irqsave(&phba->hbalock, iflag);
3449                         }
3450
3451                         /* Rsp ring <ringno> error: IOCB */
3452                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3453                                         "0336 Rsp Ring %d error: IOCB Data: "
3454                                         "x%x x%x x%x x%x x%x x%x x%x x%x\n",
3455                                         pring->ringno,
3456                                         irsp->un.ulpWord[0],
3457                                         irsp->un.ulpWord[1],
3458                                         irsp->un.ulpWord[2],
3459                                         irsp->un.ulpWord[3],
3460                                         irsp->un.ulpWord[4],
3461                                         irsp->un.ulpWord[5],
3462                                         *(uint32_t *)&irsp->un1,
3463                                         *((uint32_t *)&irsp->un1 + 1));
3464                 }
3465
3466                 switch (type) {
3467                 case LPFC_ABORT_IOCB:
3468                 case LPFC_SOL_IOCB:
3469                         /*
3470                          * Idle exchange closed via ABTS from port.  No iocb
3471                          * resources need to be recovered.
3472                          */
3473                         if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
3474                                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3475                                                 "0333 IOCB cmd 0x%x"
3476                                                 " processed. Skipping"
3477                                                 " completion\n",
3478                                                 irsp->ulpCommand);
3479                                 break;
3480                         }
3481
3482                         spin_unlock_irqrestore(&phba->hbalock, iflag);
3483                         cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
3484                                                          &rspiocbq);
3485                         spin_lock_irqsave(&phba->hbalock, iflag);
3486                         if (unlikely(!cmdiocbq))
3487                                 break;
3488                         if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
3489                                 cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
3490                         if (cmdiocbq->iocb_cmpl) {
3491                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
3492                                 (cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
3493                                                       &rspiocbq);
3494                                 spin_lock_irqsave(&phba->hbalock, iflag);
3495                         }
3496                         break;
3497                 case LPFC_UNSOL_IOCB:
3498                         spin_unlock_irqrestore(&phba->hbalock, iflag);
3499                         lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
3500                         spin_lock_irqsave(&phba->hbalock, iflag);
3501                         break;
3502                 default:
3503                         if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3504                                 char adaptermsg[LPFC_MAX_ADPTMSG];
3505                                 memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3506                                 memcpy(&adaptermsg[0], (uint8_t *) irsp,
3507                                        MAX_MSG_DATA);
3508                                 dev_warn(&((phba->pcidev)->dev),
3509                                          "lpfc%d: %s\n",
3510                                          phba->brd_no, adaptermsg);
3511                         } else {
3512                                 /* Unknown IOCB command */
3513                                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3514                                                 "0334 Unknown IOCB command "
3515                                                 "Data: x%x, x%x x%x x%x x%x\n",
3516                                                 type, irsp->ulpCommand,
3517                                                 irsp->ulpStatus,
3518                                                 irsp->ulpIoTag,
3519                                                 irsp->ulpContext);
3520                         }
3521                         break;
3522                 }
3523
3524                 /*
3525                  * The response IOCB has been processed.  Update the ring
3526                  * pointer in SLIM.  If the port response put pointer has not
3527                  * been updated, sync the pgp->rspPutInx and fetch the new port
3528                  * response put pointer.
3529                  */
3530                 writel(pring->sli.sli3.rspidx,
3531                         &phba->host_gp[pring->ringno].rspGetInx);
3532
3533                 if (pring->sli.sli3.rspidx == portRspPut)
3534                         portRspPut = le32_to_cpu(pgp->rspPutInx);
3535         }
3536
3537         if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
3538                 pring->stats.iocb_rsp_full++;
3539                 status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3540                 writel(status, phba->CAregaddr);
3541                 readl(phba->CAregaddr);
3542         }
3543         if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3544                 pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3545                 pring->stats.iocb_cmd_empty++;
3546
3547                 /* Force update of the local copy of cmdGetInx */
3548                 pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3549                 lpfc_sli_resume_iocb(phba, pring);
3550
3551                 if ((pring->lpfc_sli_cmd_available))
3552                         (pring->lpfc_sli_cmd_available) (phba, pring);
3553
3554         }
3555
3556         phba->fcp_ring_in_use = 0;
3557         spin_unlock_irqrestore(&phba->hbalock, iflag);
3558         return rc;
3559 }
3560
3561 /**
3562  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
3563  * @phba: Pointer to HBA context object.
3564  * @pring: Pointer to driver SLI ring object.
3565  * @rspiocbp: Pointer to driver response IOCB object.
3566  *
3567  * This function is called from the worker thread when there is a slow-path
3568  * response IOCB to process. This function chains all the response iocbs until
3569  * seeing the iocb with the LE bit set. The function will call
3570  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
3571  * completion of a command iocb. The function will call the
3572  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
3573  * The function frees the resources or calls the completion handler if this
3574  * iocb is an abort completion. The function returns NULL when the response
3575  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
3576  * this function shall chain the iocb on to the iocb_continueq and return the
3577  * response iocb passed in.
3578  **/
3579 static struct lpfc_iocbq *
3580 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3581                         struct lpfc_iocbq *rspiocbp)
3582 {
3583         struct lpfc_iocbq *saveq;
3584         struct lpfc_iocbq *cmdiocbp;
3585         struct lpfc_iocbq *next_iocb;
3586         IOCB_t *irsp = NULL;
3587         uint32_t free_saveq;
3588         uint8_t iocb_cmd_type;
3589         lpfc_iocb_type type;
3590         unsigned long iflag;
3591         int rc;
3592
3593         spin_lock_irqsave(&phba->hbalock, iflag);
3594         /* First add the response iocb to the countinueq list */
3595         list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
3596         pring->iocb_continueq_cnt++;
3597
3598         /* Now, determine whether the list is completed for processing */
3599         irsp = &rspiocbp->iocb;
3600         if (irsp->ulpLe) {
3601                 /*
3602                  * By default, the driver expects to free all resources
3603                  * associated with this iocb completion.
3604                  */
3605                 free_saveq = 1;
3606                 saveq = list_get_first(&pring->iocb_continueq,
3607                                        struct lpfc_iocbq, list);
3608                 irsp = &(saveq->iocb);
3609                 list_del_init(&pring->iocb_continueq);
3610                 pring->iocb_continueq_cnt = 0;
3611
3612                 pring->stats.iocb_rsp++;
3613
3614                 /*
3615                  * If resource errors reported from HBA, reduce
3616                  * queuedepths of the SCSI device.
3617                  */
3618                 if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3619                     ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3620                      IOERR_NO_RESOURCES)) {
3621                         spin_unlock_irqrestore(&phba->hbalock, iflag);
3622                         phba->lpfc_rampdown_queue_depth(phba);
3623                         spin_lock_irqsave(&phba->hbalock, iflag);
3624                 }
3625
3626                 if (irsp->ulpStatus) {
3627                         /* Rsp ring <ringno> error: IOCB */
3628                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3629                                         "0328 Rsp Ring %d error: "
3630                                         "IOCB Data: "
3631                                         "x%x x%x x%x x%x "
3632                                         "x%x x%x x%x x%x "
3633                                         "x%x x%x x%x x%x "
3634                                         "x%x x%x x%x x%x\n",
3635                                         pring->ringno,
3636                                         irsp->un.ulpWord[0],
3637                                         irsp->un.ulpWord[1],
3638                                         irsp->un.ulpWord[2],
3639                                         irsp->un.ulpWord[3],
3640                                         irsp->un.ulpWord[4],
3641                                         irsp->un.ulpWord[5],
3642                                         *(((uint32_t *) irsp) + 6),
3643                                         *(((uint32_t *) irsp) + 7),
3644                                         *(((uint32_t *) irsp) + 8),
3645                                         *(((uint32_t *) irsp) + 9),
3646                                         *(((uint32_t *) irsp) + 10),
3647                                         *(((uint32_t *) irsp) + 11),
3648                                         *(((uint32_t *) irsp) + 12),
3649                                         *(((uint32_t *) irsp) + 13),
3650                                         *(((uint32_t *) irsp) + 14),
3651                                         *(((uint32_t *) irsp) + 15));
3652                 }
3653
3654                 /*
3655                  * Fetch the IOCB command type and call the correct completion
3656                  * routine. Solicited and Unsolicited IOCBs on the ELS ring
3657                  * get freed back to the lpfc_iocb_list by the discovery
3658                  * kernel thread.
3659                  */
3660                 iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
3661                 type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
3662                 switch (type) {
3663                 case LPFC_SOL_IOCB:
3664                         spin_unlock_irqrestore(&phba->hbalock, iflag);
3665                         rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
3666                         spin_lock_irqsave(&phba->hbalock, iflag);
3667                         break;
3668
3669                 case LPFC_UNSOL_IOCB:
3670                         spin_unlock_irqrestore(&phba->hbalock, iflag);
3671                         rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
3672                         spin_lock_irqsave(&phba->hbalock, iflag);
3673                         if (!rc)
3674                                 free_saveq = 0;
3675                         break;
3676
3677                 case LPFC_ABORT_IOCB:
3678                         cmdiocbp = NULL;
3679                         if (irsp->ulpCommand != CMD_XRI_ABORTED_CX) {
3680                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
3681                                 cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
3682                                                                  saveq);
3683                                 spin_lock_irqsave(&phba->hbalock, iflag);
3684                         }
3685                         if (cmdiocbp) {
3686                                 /* Call the specified completion routine */
3687                                 if (cmdiocbp->iocb_cmpl) {
3688                                         spin_unlock_irqrestore(&phba->hbalock,
3689                                                                iflag);
3690                                         (cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
3691                                                               saveq);
3692                                         spin_lock_irqsave(&phba->hbalock,
3693                                                           iflag);
3694                                 } else
3695                                         __lpfc_sli_release_iocbq(phba,
3696                                                                  cmdiocbp);
3697                         }
3698                         break;
3699
3700                 case LPFC_UNKNOWN_IOCB:
3701                         if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
3702                                 char adaptermsg[LPFC_MAX_ADPTMSG];
3703                                 memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
3704                                 memcpy(&adaptermsg[0], (uint8_t *)irsp,
3705                                        MAX_MSG_DATA);
3706                                 dev_warn(&((phba->pcidev)->dev),
3707                                          "lpfc%d: %s\n",
3708                                          phba->brd_no, adaptermsg);
3709                         } else {
3710                                 /* Unknown IOCB command */
3711                                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3712                                                 "0335 Unknown IOCB "
3713                                                 "command Data: x%x "
3714                                                 "x%x x%x x%x\n",
3715                                                 irsp->ulpCommand,
3716                                                 irsp->ulpStatus,
3717                                                 irsp->ulpIoTag,
3718                                                 irsp->ulpContext);
3719                         }
3720                         break;
3721                 }
3722
3723                 if (free_saveq) {
3724                         list_for_each_entry_safe(rspiocbp, next_iocb,
3725                                                  &saveq->list, list) {
3726                                 list_del_init(&rspiocbp->list);
3727                                 __lpfc_sli_release_iocbq(phba, rspiocbp);
3728                         }
3729                         __lpfc_sli_release_iocbq(phba, saveq);
3730                 }
3731                 rspiocbp = NULL;
3732         }
3733         spin_unlock_irqrestore(&phba->hbalock, iflag);
3734         return rspiocbp;
3735 }
3736
3737 /**
3738  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
3739  * @phba: Pointer to HBA context object.
3740  * @pring: Pointer to driver SLI ring object.
3741  * @mask: Host attention register mask for this ring.
3742  *
3743  * This routine wraps the actual slow_ring event process routine from the
3744  * API jump table function pointer from the lpfc_hba struct.
3745  **/
3746 void
3747 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
3748                                 struct lpfc_sli_ring *pring, uint32_t mask)
3749 {
3750         phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
3751 }
3752
3753 /**
3754  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
3755  * @phba: Pointer to HBA context object.
3756  * @pring: Pointer to driver SLI ring object.
3757  * @mask: Host attention register mask for this ring.
3758  *
3759  * This function is called from the worker thread when there is a ring event
3760  * for non-fcp rings. The caller does not hold any lock. The function will
3761  * remove each response iocb in the response ring and calls the handle
3762  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3763  **/
3764 static void
3765 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
3766                                    struct lpfc_sli_ring *pring, uint32_t mask)
3767 {
3768         struct lpfc_pgp *pgp;
3769         IOCB_t *entry;
3770         IOCB_t *irsp = NULL;
3771         struct lpfc_iocbq *rspiocbp = NULL;
3772         uint32_t portRspPut, portRspMax;
3773         unsigned long iflag;
3774         uint32_t status;
3775
3776         pgp = &phba->port_gp[pring->ringno];
3777         spin_lock_irqsave(&phba->hbalock, iflag);
3778         pring->stats.iocb_event++;
3779
3780         /*
3781          * The next available response entry should never exceed the maximum
3782          * entries.  If it does, treat it as an adapter hardware error.
3783          */
3784         portRspMax = pring->sli.sli3.numRiocb;
3785         portRspPut = le32_to_cpu(pgp->rspPutInx);
3786         if (portRspPut >= portRspMax) {
3787                 /*
3788                  * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3789                  * rsp ring <portRspMax>
3790                  */
3791                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
3792                                 "0303 Ring %d handler: portRspPut %d "
3793                                 "is bigger than rsp ring %d\n",
3794                                 pring->ringno, portRspPut, portRspMax);
3795
3796                 phba->link_state = LPFC_HBA_ERROR;
3797                 spin_unlock_irqrestore(&phba->hbalock, iflag);
3798
3799                 phba->work_hs = HS_FFER3;
3800                 lpfc_handle_eratt(phba);
3801
3802                 return;
3803         }
3804
3805         rmb();
3806         while (pring->sli.sli3.rspidx != portRspPut) {
3807                 /*
3808                  * Build a completion list and call the appropriate handler.
3809                  * The process is to get the next available response iocb, get
3810                  * a free iocb from the list, copy the response data into the
3811                  * free iocb, insert to the continuation list, and update the
3812                  * next response index to slim.  This process makes response
3813                  * iocb's in the ring available to DMA as fast as possible but
3814                  * pays a penalty for a copy operation.  Since the iocb is
3815                  * only 32 bytes, this penalty is considered small relative to
3816                  * the PCI reads for register values and a slim write.  When
3817                  * the ulpLe field is set, the entire Command has been
3818                  * received.
3819                  */
3820                 entry = lpfc_resp_iocb(phba, pring);
3821
3822                 phba->last_completion_time = jiffies;
3823                 rspiocbp = __lpfc_sli_get_iocbq(phba);
3824                 if (rspiocbp == NULL) {
3825                         printk(KERN_ERR "%s: out of buffers! Failing "
3826                                "completion.\n", __func__);
3827                         break;
3828                 }
3829
3830                 lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
3831                                       phba->iocb_rsp_size);
3832                 irsp = &rspiocbp->iocb;
3833
3834                 if (++pring->sli.sli3.rspidx >= portRspMax)
3835                         pring->sli.sli3.rspidx = 0;
3836
3837                 if (pring->ringno == LPFC_ELS_RING) {
3838                         lpfc_debugfs_slow_ring_trc(phba,
3839                         "IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
3840                                 *(((uint32_t *) irsp) + 4),
3841                                 *(((uint32_t *) irsp) + 6),
3842                                 *(((uint32_t *) irsp) + 7));
3843                 }
3844
3845                 writel(pring->sli.sli3.rspidx,
3846                         &phba->host_gp[pring->ringno].rspGetInx);
3847
3848                 spin_unlock_irqrestore(&phba->hbalock, iflag);
3849                 /* Handle the response IOCB */
3850                 rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
3851                 spin_lock_irqsave(&phba->hbalock, iflag);
3852
3853                 /*
3854                  * If the port response put pointer has not been updated, sync
3855                  * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
3856                  * response put pointer.
3857                  */
3858                 if (pring->sli.sli3.rspidx == portRspPut) {
3859                         portRspPut = le32_to_cpu(pgp->rspPutInx);
3860                 }
3861         } /* while (pring->sli.sli3.rspidx != portRspPut) */
3862
3863         if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
3864                 /* At least one response entry has been freed */
3865                 pring->stats.iocb_rsp_full++;
3866                 /* SET RxRE_RSP in Chip Att register */
3867                 status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
3868                 writel(status, phba->CAregaddr);
3869                 readl(phba->CAregaddr); /* flush */
3870         }
3871         if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
3872                 pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
3873                 pring->stats.iocb_cmd_empty++;
3874
3875                 /* Force update of the local copy of cmdGetInx */
3876                 pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
3877                 lpfc_sli_resume_iocb(phba, pring);
3878
3879                 if ((pring->lpfc_sli_cmd_available))
3880                         (pring->lpfc_sli_cmd_available) (phba, pring);
3881
3882         }
3883
3884         spin_unlock_irqrestore(&phba->hbalock, iflag);
3885         return;
3886 }
3887
3888 /**
3889  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
3890  * @phba: Pointer to HBA context object.
3891  * @pring: Pointer to driver SLI ring object.
3892  * @mask: Host attention register mask for this ring.
3893  *
3894  * This function is called from the worker thread when there is a pending
3895  * ELS response iocb on the driver internal slow-path response iocb worker
3896  * queue. The caller does not hold any lock. The function will remove each
3897  * response iocb from the response worker queue and calls the handle
3898  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
3899  **/
3900 static void
3901 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
3902                                    struct lpfc_sli_ring *pring, uint32_t mask)
3903 {
3904         struct lpfc_iocbq *irspiocbq;
3905         struct hbq_dmabuf *dmabuf;
3906         struct lpfc_cq_event *cq_event;
3907         unsigned long iflag;
3908         int count = 0;
3909
3910         spin_lock_irqsave(&phba->hbalock, iflag);
3911         phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
3912         spin_unlock_irqrestore(&phba->hbalock, iflag);
3913         while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
3914                 /* Get the response iocb from the head of work queue */
3915                 spin_lock_irqsave(&phba->hbalock, iflag);
3916                 list_remove_head(&phba->sli4_hba.sp_queue_event,
3917                                  cq_event, struct lpfc_cq_event, list);
3918                 spin_unlock_irqrestore(&phba->hbalock, iflag);
3919
3920                 switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
3921                 case CQE_CODE_COMPL_WQE:
3922                         irspiocbq = container_of(cq_event, struct lpfc_iocbq,
3923                                                  cq_event);
3924                         /* Translate ELS WCQE to response IOCBQ */
3925                         irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
3926                                                                    irspiocbq);
3927                         if (irspiocbq)
3928                                 lpfc_sli_sp_handle_rspiocb(phba, pring,
3929                                                            irspiocbq);
3930                         count++;
3931                         break;
3932                 case CQE_CODE_RECEIVE:
3933                 case CQE_CODE_RECEIVE_V1:
3934                         dmabuf = container_of(cq_event, struct hbq_dmabuf,
3935                                               cq_event);
3936                         lpfc_sli4_handle_received_buffer(phba, dmabuf);
3937                         count++;
3938                         break;
3939                 default:
3940                         break;
3941                 }
3942
3943                 /* Limit the number of events to 64 to avoid soft lockups */
3944                 if (count == 64)
3945                         break;
3946         }
3947 }
3948
3949 /**
3950  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
3951  * @phba: Pointer to HBA context object.
3952  * @pring: Pointer to driver SLI ring object.
3953  *
3954  * This function aborts all iocbs in the given ring and frees all the iocb
3955  * objects in txq. This function issues an abort iocb for all the iocb commands
3956  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
3957  * the return of this function. The caller is not required to hold any locks.
3958  **/
3959 void
3960 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3961 {
3962         LIST_HEAD(completions);
3963         struct lpfc_iocbq *iocb, *next_iocb;
3964
3965         if (pring->ringno == LPFC_ELS_RING) {
3966                 lpfc_fabric_abort_hba(phba);
3967         }
3968
3969         /* Error everything on txq and txcmplq
3970          * First do the txq.
3971          */
3972         if (phba->sli_rev >= LPFC_SLI_REV4) {
3973                 spin_lock_irq(&pring->ring_lock);
3974                 list_splice_init(&pring->txq, &completions);
3975                 pring->txq_cnt = 0;
3976                 spin_unlock_irq(&pring->ring_lock);
3977
3978                 spin_lock_irq(&phba->hbalock);
3979                 /* Next issue ABTS for everything on the txcmplq */
3980                 list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3981                         lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3982                 spin_unlock_irq(&phba->hbalock);
3983         } else {
3984                 spin_lock_irq(&phba->hbalock);
3985                 list_splice_init(&pring->txq, &completions);
3986                 pring->txq_cnt = 0;
3987
3988                 /* Next issue ABTS for everything on the txcmplq */
3989                 list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
3990                         lpfc_sli_issue_abort_iotag(phba, pring, iocb);
3991                 spin_unlock_irq(&phba->hbalock);
3992         }
3993
3994         /* Cancel all the IOCBs from the completions list */
3995         lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
3996                               IOERR_SLI_ABORTED);
3997 }
3998
3999 /**
4000  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4001  * @phba: Pointer to HBA context object.
4002  * @pring: Pointer to driver SLI ring object.
4003  *
4004  * This function aborts all iocbs in FCP rings and frees all the iocb
4005  * objects in txq. This function issues an abort iocb for all the iocb commands
4006  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4007  * the return of this function. The caller is not required to hold any locks.
4008  **/
4009 void
4010 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4011 {
4012         struct lpfc_sli *psli = &phba->sli;
4013         struct lpfc_sli_ring  *pring;
4014         uint32_t i;
4015
4016         /* Look on all the FCP Rings for the iotag */
4017         if (phba->sli_rev >= LPFC_SLI_REV4) {
4018                 for (i = 0; i < phba->cfg_hdw_queue; i++) {
4019                         pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4020                         lpfc_sli_abort_iocb_ring(phba, pring);
4021                 }
4022         } else {
4023                 pring = &psli->sli3_ring[LPFC_FCP_RING];
4024                 lpfc_sli_abort_iocb_ring(phba, pring);
4025         }
4026 }
4027
4028 /**
4029  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4030  * @phba: Pointer to HBA context object.
4031  *
4032  * This function flushes all iocbs in the IO ring and frees all the iocb
4033  * objects in txq and txcmplq. This function will not issue abort iocbs
4034  * for all the iocb commands in txcmplq, they will just be returned with
4035  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4036  * slot has been permanently disabled.
4037  **/
4038 void
4039 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4040 {
4041         LIST_HEAD(txq);
4042         LIST_HEAD(txcmplq);
4043         struct lpfc_sli *psli = &phba->sli;
4044         struct lpfc_sli_ring  *pring;
4045         uint32_t i;
4046         struct lpfc_iocbq *piocb, *next_iocb;
4047
4048         spin_lock_irq(&phba->hbalock);
4049         if (phba->hba_flag & HBA_IOQ_FLUSH ||
4050             !phba->sli4_hba.hdwq) {
4051                 spin_unlock_irq(&phba->hbalock);
4052                 return;
4053         }
4054         /* Indicate the I/O queues are flushed */
4055         phba->hba_flag |= HBA_IOQ_FLUSH;
4056         spin_unlock_irq(&phba->hbalock);
4057
4058         /* Look on all the FCP Rings for the iotag */
4059         if (phba->sli_rev >= LPFC_SLI_REV4) {
4060                 for (i = 0; i < phba->cfg_hdw_queue; i++) {
4061                         pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4062
4063                         spin_lock_irq(&pring->ring_lock);
4064                         /* Retrieve everything on txq */
4065                         list_splice_init(&pring->txq, &txq);
4066                         list_for_each_entry_safe(piocb, next_iocb,
4067                                                  &pring->txcmplq, list)
4068                                 piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4069                         /* Retrieve everything on the txcmplq */
4070                         list_splice_init(&pring->txcmplq, &txcmplq);
4071                         pring->txq_cnt = 0;
4072                         pring->txcmplq_cnt = 0;
4073                         spin_unlock_irq(&pring->ring_lock);
4074
4075                         /* Flush the txq */
4076                         lpfc_sli_cancel_iocbs(phba, &txq,
4077                                               IOSTAT_LOCAL_REJECT,
4078                                               IOERR_SLI_DOWN);
4079                         /* Flush the txcmpq */
4080                         lpfc_sli_cancel_iocbs(phba, &txcmplq,
4081                                               IOSTAT_LOCAL_REJECT,
4082                                               IOERR_SLI_DOWN);
4083                 }
4084         } else {
4085                 pring = &psli->sli3_ring[LPFC_FCP_RING];
4086
4087                 spin_lock_irq(&phba->hbalock);
4088                 /* Retrieve everything on txq */
4089                 list_splice_init(&pring->txq, &txq);
4090                 list_for_each_entry_safe(piocb, next_iocb,
4091                                          &pring->txcmplq, list)
4092                         piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4093                 /* Retrieve everything on the txcmplq */
4094                 list_splice_init(&pring->txcmplq, &txcmplq);
4095                 pring->txq_cnt = 0;
4096                 pring->txcmplq_cnt = 0;
4097                 spin_unlock_irq(&phba->hbalock);
4098
4099                 /* Flush the txq */
4100                 lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4101                                       IOERR_SLI_DOWN);
4102                 /* Flush the txcmpq */
4103                 lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4104                                       IOERR_SLI_DOWN);
4105         }
4106 }
4107
4108 /**
4109  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4110  * @phba: Pointer to HBA context object.
4111  * @mask: Bit mask to be checked.
4112  *
4113  * This function reads the host status register and compares
4114  * with the provided bit mask to check if HBA completed
4115  * the restart. This function will wait in a loop for the
4116  * HBA to complete restart. If the HBA does not restart within
4117  * 15 iterations, the function will reset the HBA again. The
4118  * function returns 1 when HBA fail to restart otherwise returns
4119  * zero.
4120  **/
4121 static int
4122 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4123 {
4124         uint32_t status;
4125         int i = 0;
4126         int retval = 0;
4127
4128         /* Read the HBA Host Status Register */
4129         if (lpfc_readl(phba->HSregaddr, &status))
4130                 return 1;
4131
4132         /*
4133          * Check status register every 100ms for 5 retries, then every
4134          * 500ms for 5, then every 2.5 sec for 5, then reset board and
4135          * every 2.5 sec for 4.
4136          * Break our of the loop if errors occurred during init.
4137          */
4138         while (((status & mask) != mask) &&
4139                !(status & HS_FFERM) &&
4140                i++ < 20) {
4141
4142                 if (i <= 5)
4143                         msleep(10);
4144                 else if (i <= 10)
4145                         msleep(500);
4146                 else
4147                         msleep(2500);
4148
4149                 if (i == 15) {
4150                                 /* Do post */
4151                         phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4152                         lpfc_sli_brdrestart(phba);
4153                 }
4154                 /* Read the HBA Host Status Register */
4155                 if (lpfc_readl(phba->HSregaddr, &status)) {
4156                         retval = 1;
4157                         break;
4158                 }
4159         }
4160
4161         /* Check to see if any errors occurred during init */
4162         if ((status & HS_FFERM) || (i >= 20)) {
4163                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4164                                 "2751 Adapter failed to restart, "
4165                                 "status reg x%x, FW Data: A8 x%x AC x%x\n",
4166                                 status,
4167                                 readl(phba->MBslimaddr + 0xa8),
4168                                 readl(phba->MBslimaddr + 0xac));
4169                 phba->link_state = LPFC_HBA_ERROR;
4170                 retval = 1;
4171         }
4172
4173         return retval;
4174 }
4175
4176 /**
4177  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4178  * @phba: Pointer to HBA context object.
4179  * @mask: Bit mask to be checked.
4180  *
4181  * This function checks the host status register to check if HBA is
4182  * ready. This function will wait in a loop for the HBA to be ready
4183  * If the HBA is not ready , the function will will reset the HBA PCI
4184  * function again. The function returns 1 when HBA fail to be ready
4185  * otherwise returns zero.
4186  **/
4187 static int
4188 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4189 {
4190         uint32_t status;
4191         int retval = 0;
4192
4193         /* Read the HBA Host Status Register */
4194         status = lpfc_sli4_post_status_check(phba);
4195
4196         if (status) {
4197                 phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4198                 lpfc_sli_brdrestart(phba);
4199                 status = lpfc_sli4_post_status_check(phba);
4200         }
4201
4202         /* Check to see if any errors occurred during init */
4203         if (status) {
4204                 phba->link_state = LPFC_HBA_ERROR;
4205                 retval = 1;
4206         } else
4207                 phba->sli4_hba.intr_enable = 0;
4208
4209         return retval;
4210 }
4211
4212 /**
4213  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4214  * @phba: Pointer to HBA context object.
4215  * @mask: Bit mask to be checked.
4216  *
4217  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4218  * from the API jump table function pointer from the lpfc_hba struct.
4219  **/
4220 int
4221 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4222 {
4223         return phba->lpfc_sli_brdready(phba, mask);
4224 }
4225
4226 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4227
4228 /**
4229  * lpfc_reset_barrier - Make HBA ready for HBA reset
4230  * @phba: Pointer to HBA context object.
4231  *
4232  * This function is called before resetting an HBA. This function is called
4233  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4234  **/
4235 void lpfc_reset_barrier(struct lpfc_hba *phba)
4236 {
4237         uint32_t __iomem *resp_buf;
4238         uint32_t __iomem *mbox_buf;
4239         volatile uint32_t mbox;
4240         uint32_t hc_copy, ha_copy, resp_data;
4241         int  i;
4242         uint8_t hdrtype;
4243
4244         lockdep_assert_held(&phba->hbalock);
4245
4246         pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4247         if (hdrtype != 0x80 ||
4248             (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4249              FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4250                 return;
4251
4252         /*
4253          * Tell the other part of the chip to suspend temporarily all
4254          * its DMA activity.
4255          */
4256         resp_buf = phba->MBslimaddr;
4257
4258         /* Disable the error attention */
4259         if (lpfc_readl(phba->HCregaddr, &hc_copy))
4260                 return;
4261         writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4262         readl(phba->HCregaddr); /* flush */
4263         phba->link_flag |= LS_IGNORE_ERATT;
4264
4265         if (lpfc_readl(phba->HAregaddr, &ha_copy))
4266                 return;
4267         if (ha_copy & HA_ERATT) {
4268                 /* Clear Chip error bit */
4269                 writel(HA_ERATT, phba->HAregaddr);
4270                 phba->pport->stopped = 1;
4271         }
4272
4273         mbox = 0;
4274         ((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
4275         ((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
4276
4277         writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4278         mbox_buf = phba->MBslimaddr;
4279         writel(mbox, mbox_buf);
4280
4281         for (i = 0; i < 50; i++) {
4282                 if (lpfc_readl((resp_buf + 1), &resp_data))
4283                         return;
4284                 if (resp_data != ~(BARRIER_TEST_PATTERN))
4285                         mdelay(1);
4286                 else
4287                         break;
4288         }
4289         resp_data = 0;
4290         if (lpfc_readl((resp_buf + 1), &resp_data))
4291                 return;
4292         if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4293                 if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4294                     phba->pport->stopped)
4295                         goto restore_hc;
4296                 else
4297                         goto clear_errat;
4298         }
4299
4300         ((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
4301         resp_data = 0;
4302         for (i = 0; i < 500; i++) {
4303                 if (lpfc_readl(resp_buf, &resp_data))
4304                         return;
4305                 if (resp_data != mbox)
4306                         mdelay(1);
4307                 else
4308                         break;
4309         }
4310
4311 clear_errat:
4312
4313         while (++i < 500) {
4314                 if (lpfc_readl(phba->HAregaddr, &ha_copy))
4315                         return;
4316                 if (!(ha_copy & HA_ERATT))
4317                         mdelay(1);
4318                 else
4319                         break;
4320         }
4321
4322         if (readl(phba->HAregaddr) & HA_ERATT) {
4323                 writel(HA_ERATT, phba->HAregaddr);
4324                 phba->pport->stopped = 1;
4325         }
4326
4327 restore_hc:
4328         phba->link_flag &= ~LS_IGNORE_ERATT;
4329         writel(hc_copy, phba->HCregaddr);
4330         readl(phba->HCregaddr); /* flush */
4331 }
4332
4333 /**
4334  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4335  * @phba: Pointer to HBA context object.
4336  *
4337  * This function issues a kill_board mailbox command and waits for
4338  * the error attention interrupt. This function is called for stopping
4339  * the firmware processing. The caller is not required to hold any
4340  * locks. This function calls lpfc_hba_down_post function to free
4341  * any pending commands after the kill. The function will return 1 when it
4342  * fails to kill the board else will return 0.
4343  **/
4344 int
4345 lpfc_sli_brdkill(struct lpfc_hba *phba)
4346 {
4347         struct lpfc_sli *psli;
4348         LPFC_MBOXQ_t *pmb;
4349         uint32_t status;
4350         uint32_t ha_copy;
4351         int retval;
4352         int i = 0;
4353
4354         psli = &phba->sli;
4355
4356         /* Kill HBA */
4357         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4358                         "0329 Kill HBA Data: x%x x%x\n",
4359                         phba->pport->port_state, psli->sli_flag);
4360
4361         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4362         if (!pmb)
4363                 return 1;
4364
4365         /* Disable the error attention */
4366         spin_lock_irq(&phba->hbalock);
4367         if (lpfc_readl(phba->HCregaddr, &status)) {
4368                 spin_unlock_irq(&phba->hbalock);
4369                 mempool_free(pmb, phba->mbox_mem_pool);
4370                 return 1;
4371         }
4372         status &= ~HC_ERINT_ENA;
4373         writel(status, phba->HCregaddr);
4374         readl(phba->HCregaddr); /* flush */
4375         phba->link_flag |= LS_IGNORE_ERATT;
4376         spin_unlock_irq(&phba->hbalock);
4377
4378         lpfc_kill_board(phba, pmb);
4379         pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4380         retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
4381
4382         if (retval != MBX_SUCCESS) {
4383                 if (retval != MBX_BUSY)
4384                         mempool_free(pmb, phba->mbox_mem_pool);
4385                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4386                                 "2752 KILL_BOARD command failed retval %d\n",
4387                                 retval);
4388                 spin_lock_irq(&phba->hbalock);
4389                 phba->link_flag &= ~LS_IGNORE_ERATT;
4390                 spin_unlock_irq(&phba->hbalock);
4391                 return 1;
4392         }
4393
4394         spin_lock_irq(&phba->hbalock);
4395         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
4396         spin_unlock_irq(&phba->hbalock);
4397
4398         mempool_free(pmb, phba->mbox_mem_pool);
4399
4400         /* There is no completion for a KILL_BOARD mbox cmd. Check for an error
4401          * attention every 100ms for 3 seconds. If we don't get ERATT after
4402          * 3 seconds we still set HBA_ERROR state because the status of the
4403          * board is now undefined.
4404          */
4405         if (lpfc_readl(phba->HAregaddr, &ha_copy))
4406                 return 1;
4407         while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
4408                 mdelay(100);
4409                 if (lpfc_readl(phba->HAregaddr, &ha_copy))
4410                         return 1;
4411         }
4412
4413         del_timer_sync(&psli->mbox_tmo);
4414         if (ha_copy & HA_ERATT) {
4415                 writel(HA_ERATT, phba->HAregaddr);
4416                 phba->pport->stopped = 1;
4417         }
4418         spin_lock_irq(&phba->hbalock);
4419         psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4420         psli->mbox_active = NULL;
4421         phba->link_flag &= ~LS_IGNORE_ERATT;
4422         spin_unlock_irq(&phba->hbalock);
4423
4424         lpfc_hba_down_post(phba);
4425         phba->link_state = LPFC_HBA_ERROR;
4426
4427         return ha_copy & HA_ERATT ? 0 : 1;
4428 }
4429
4430 /**
4431  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
4432  * @phba: Pointer to HBA context object.
4433  *
4434  * This function resets the HBA by writing HC_INITFF to the control
4435  * register. After the HBA resets, this function resets all the iocb ring
4436  * indices. This function disables PCI layer parity checking during
4437  * the reset.
4438  * This function returns 0 always.
4439  * The caller is not required to hold any locks.
4440  **/
4441 int
4442 lpfc_sli_brdreset(struct lpfc_hba *phba)
4443 {
4444         struct lpfc_sli *psli;
4445         struct lpfc_sli_ring *pring;
4446         uint16_t cfg_value;
4447         int i;
4448
4449         psli = &phba->sli;
4450
4451         /* Reset HBA */
4452         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4453                         "0325 Reset HBA Data: x%x x%x\n",
4454                         (phba->pport) ? phba->pport->port_state : 0,
4455                         psli->sli_flag);
4456
4457         /* perform board reset */
4458         phba->fc_eventTag = 0;
4459         phba->link_events = 0;
4460         if (phba->pport) {
4461                 phba->pport->fc_myDID = 0;
4462                 phba->pport->fc_prevDID = 0;
4463         }
4464
4465         /* Turn off parity checking and serr during the physical reset */
4466         if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
4467                 return -EIO;
4468
4469         pci_write_config_word(phba->pcidev, PCI_COMMAND,
4470                               (cfg_value &
4471                                ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4472
4473         psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
4474
4475         /* Now toggle INITFF bit in the Host Control Register */
4476         writel(HC_INITFF, phba->HCregaddr);
4477         mdelay(1);
4478         readl(phba->HCregaddr); /* flush */
4479         writel(0, phba->HCregaddr);
4480         readl(phba->HCregaddr); /* flush */
4481
4482         /* Restore PCI cmd register */
4483         pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4484
4485         /* Initialize relevant SLI info */
4486         for (i = 0; i < psli->num_rings; i++) {
4487                 pring = &psli->sli3_ring[i];
4488                 pring->flag = 0;
4489                 pring->sli.sli3.rspidx = 0;
4490                 pring->sli.sli3.next_cmdidx  = 0;
4491                 pring->sli.sli3.local_getidx = 0;
4492                 pring->sli.sli3.cmdidx = 0;
4493                 pring->missbufcnt = 0;
4494         }
4495
4496         phba->link_state = LPFC_WARM_START;
4497         return 0;
4498 }
4499
4500 /**
4501  * lpfc_sli4_brdreset - Reset a sli-4 HBA
4502  * @phba: Pointer to HBA context object.
4503  *
4504  * This function resets a SLI4 HBA. This function disables PCI layer parity
4505  * checking during resets the device. The caller is not required to hold
4506  * any locks.
4507  *
4508  * This function returns 0 on success else returns negative error code.
4509  **/
4510 int
4511 lpfc_sli4_brdreset(struct lpfc_hba *phba)
4512 {
4513         struct lpfc_sli *psli = &phba->sli;
4514         uint16_t cfg_value;
4515         int rc = 0;
4516
4517         /* Reset HBA */
4518         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4519                         "0295 Reset HBA Data: x%x x%x x%x\n",
4520                         phba->pport->port_state, psli->sli_flag,
4521                         phba->hba_flag);
4522
4523         /* perform board reset */
4524         phba->fc_eventTag = 0;
4525         phba->link_events = 0;
4526         phba->pport->fc_myDID = 0;
4527         phba->pport->fc_prevDID = 0;
4528
4529         spin_lock_irq(&phba->hbalock);
4530         psli->sli_flag &= ~(LPFC_PROCESS_LA);
4531         phba->fcf.fcf_flag = 0;
4532         spin_unlock_irq(&phba->hbalock);
4533
4534         /* SLI4 INTF 2: if FW dump is being taken skip INIT_PORT */
4535         if (phba->hba_flag & HBA_FW_DUMP_OP) {
4536                 phba->hba_flag &= ~HBA_FW_DUMP_OP;
4537                 return rc;
4538         }
4539
4540         /* Now physically reset the device */
4541         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4542                         "0389 Performing PCI function reset!\n");
4543
4544         /* Turn off parity checking and serr during the physical reset */
4545         if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
4546                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
4547                                 "3205 PCI read Config failed\n");
4548                 return -EIO;
4549         }
4550
4551         pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
4552                               ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4553
4554         /* Perform FCoE PCI function reset before freeing queue memory */
4555         rc = lpfc_pci_function_reset(phba);
4556
4557         /* Restore PCI cmd register */
4558         pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4559
4560         return rc;
4561 }
4562
4563 /**
4564  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
4565  * @phba: Pointer to HBA context object.
4566  *
4567  * This function is called in the SLI initialization code path to
4568  * restart the HBA. The caller is not required to hold any lock.
4569  * This function writes MBX_RESTART mailbox command to the SLIM and
4570  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
4571  * function to free any pending commands. The function enables
4572  * POST only during the first initialization. The function returns zero.
4573  * The function does not guarantee completion of MBX_RESTART mailbox
4574  * command before the return of this function.
4575  **/
4576 static int
4577 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
4578 {
4579         MAILBOX_t *mb;
4580         struct lpfc_sli *psli;
4581         volatile uint32_t word0;
4582         void __iomem *to_slim;
4583         uint32_t hba_aer_enabled;
4584
4585         spin_lock_irq(&phba->hbalock);
4586
4587         /* Take PCIe device Advanced Error Reporting (AER) state */
4588         hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4589
4590         psli = &phba->sli;
4591
4592         /* Restart HBA */
4593         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4594                         "0337 Restart HBA Data: x%x x%x\n",
4595                         (phba->pport) ? phba->pport->port_state : 0,
4596                         psli->sli_flag);
4597
4598         word0 = 0;
4599         mb = (MAILBOX_t *) &word0;
4600         mb->mbxCommand = MBX_RESTART;
4601         mb->mbxHc = 1;
4602
4603         lpfc_reset_barrier(phba);
4604
4605         to_slim = phba->MBslimaddr;
4606         writel(*(uint32_t *) mb, to_slim);
4607         readl(to_slim); /* flush */
4608
4609         /* Only skip post after fc_ffinit is completed */
4610         if (phba->pport && phba->pport->port_state)
4611                 word0 = 1;      /* This is really setting up word1 */
4612         else
4613                 word0 = 0;      /* This is really setting up word1 */
4614         to_slim = phba->MBslimaddr + sizeof (uint32_t);
4615         writel(*(uint32_t *) mb, to_slim);
4616         readl(to_slim); /* flush */
4617
4618         lpfc_sli_brdreset(phba);
4619         if (phba->pport)
4620                 phba->pport->stopped = 0;
4621         phba->link_state = LPFC_INIT_START;
4622         phba->hba_flag = 0;
4623         spin_unlock_irq(&phba->hbalock);
4624
4625         memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4626         psli->stats_start = ktime_get_seconds();
4627
4628         /* Give the INITFF and Post time to settle. */
4629         mdelay(100);
4630
4631         /* Reset HBA AER if it was enabled, note hba_flag was reset above */
4632         if (hba_aer_enabled)
4633                 pci_disable_pcie_error_reporting(phba->pcidev);
4634
4635         lpfc_hba_down_post(phba);
4636
4637         return 0;
4638 }
4639
4640 /**
4641  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
4642  * @phba: Pointer to HBA context object.
4643  *
4644  * This function is called in the SLI initialization code path to restart
4645  * a SLI4 HBA. The caller is not required to hold any lock.
4646  * At the end of the function, it calls lpfc_hba_down_post function to
4647  * free any pending commands.
4648  **/
4649 static int
4650 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
4651 {
4652         struct lpfc_sli *psli = &phba->sli;
4653         uint32_t hba_aer_enabled;
4654         int rc;
4655
4656         /* Restart HBA */
4657         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4658                         "0296 Restart HBA Data: x%x x%x\n",
4659                         phba->pport->port_state, psli->sli_flag);
4660
4661         /* Take PCIe device Advanced Error Reporting (AER) state */
4662         hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
4663
4664         rc = lpfc_sli4_brdreset(phba);
4665         if (rc) {
4666                 phba->link_state = LPFC_HBA_ERROR;
4667                 goto hba_down_queue;
4668         }
4669
4670         spin_lock_irq(&phba->hbalock);
4671         phba->pport->stopped = 0;
4672         phba->link_state = LPFC_INIT_START;
4673         phba->hba_flag = 0;
4674         spin_unlock_irq(&phba->hbalock);
4675
4676         memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
4677         psli->stats_start = ktime_get_seconds();
4678
4679         /* Reset HBA AER if it was enabled, note hba_flag was reset above */
4680         if (hba_aer_enabled)
4681                 pci_disable_pcie_error_reporting(phba->pcidev);
4682
4683 hba_down_queue:
4684         lpfc_hba_down_post(phba);
4685         lpfc_sli4_queue_destroy(phba);
4686
4687         return rc;
4688 }
4689
4690 /**
4691  * lpfc_sli_brdrestart - Wrapper func for restarting hba
4692  * @phba: Pointer to HBA context object.
4693  *
4694  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
4695  * API jump table function pointer from the lpfc_hba struct.
4696 **/
4697 int
4698 lpfc_sli_brdrestart(struct lpfc_hba *phba)
4699 {
4700         return phba->lpfc_sli_brdrestart(phba);
4701 }
4702
4703 /**
4704  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
4705  * @phba: Pointer to HBA context object.
4706  *
4707  * This function is called after a HBA restart to wait for successful
4708  * restart of the HBA. Successful restart of the HBA is indicated by
4709  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
4710  * iteration, the function will restart the HBA again. The function returns
4711  * zero if HBA successfully restarted else returns negative error code.
4712  **/
4713 int
4714 lpfc_sli_chipset_init(struct lpfc_hba *phba)
4715 {
4716         uint32_t status, i = 0;
4717
4718         /* Read the HBA Host Status Register */
4719         if (lpfc_readl(phba->HSregaddr, &status))
4720                 return -EIO;
4721
4722         /* Check status register to see what current state is */
4723         i = 0;
4724         while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
4725
4726                 /* Check every 10ms for 10 retries, then every 100ms for 90
4727                  * retries, then every 1 sec for 50 retires for a total of
4728                  * ~60 seconds before reset the board again and check every
4729                  * 1 sec for 50 retries. The up to 60 seconds before the
4730                  * board ready is required by the Falcon FIPS zeroization
4731                  * complete, and any reset the board in between shall cause
4732                  * restart of zeroization, further delay the board ready.
4733                  */
4734                 if (i++ >= 200) {
4735                         /* Adapter failed to init, timeout, status reg
4736                            <status> */
4737                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4738                                         "0436 Adapter failed to init, "
4739                                         "timeout, status reg x%x, "
4740                                         "FW Data: A8 x%x AC x%x\n", status,
4741                                         readl(phba->MBslimaddr + 0xa8),
4742                                         readl(phba->MBslimaddr + 0xac));
4743                         phba->link_state = LPFC_HBA_ERROR;
4744                         return -ETIMEDOUT;
4745                 }
4746
4747                 /* Check to see if any errors occurred during init */
4748                 if (status & HS_FFERM) {
4749                         /* ERROR: During chipset initialization */
4750                         /* Adapter failed to init, chipset, status reg
4751                            <status> */
4752                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4753                                         "0437 Adapter failed to init, "
4754                                         "chipset, status reg x%x, "
4755                                         "FW Data: A8 x%x AC x%x\n", status,
4756                                         readl(phba->MBslimaddr + 0xa8),
4757                                         readl(phba->MBslimaddr + 0xac));
4758                         phba->link_state = LPFC_HBA_ERROR;
4759                         return -EIO;
4760                 }
4761
4762                 if (i <= 10)
4763                         msleep(10);
4764                 else if (i <= 100)
4765                         msleep(100);
4766                 else
4767                         msleep(1000);
4768
4769                 if (i == 150) {
4770                         /* Do post */
4771                         phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4772                         lpfc_sli_brdrestart(phba);
4773                 }
4774                 /* Read the HBA Host Status Register */
4775                 if (lpfc_readl(phba->HSregaddr, &status))
4776                         return -EIO;
4777         }
4778
4779         /* Check to see if any errors occurred during init */
4780         if (status & HS_FFERM) {
4781                 /* ERROR: During chipset initialization */
4782                 /* Adapter failed to init, chipset, status reg <status> */
4783                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
4784                                 "0438 Adapter failed to init, chipset, "
4785                                 "status reg x%x, "
4786                                 "FW Data: A8 x%x AC x%x\n", status,
4787                                 readl(phba->MBslimaddr + 0xa8),
4788                                 readl(phba->MBslimaddr + 0xac));
4789                 phba->link_state = LPFC_HBA_ERROR;
4790                 return -EIO;
4791         }
4792
4793         /* Clear all interrupt enable conditions */
4794         writel(0, phba->HCregaddr);
4795         readl(phba->HCregaddr); /* flush */
4796
4797         /* setup host attn register */
4798         writel(0xffffffff, phba->HAregaddr);
4799         readl(phba->HAregaddr); /* flush */
4800         return 0;
4801 }
4802
4803 /**
4804  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
4805  *
4806  * This function calculates and returns the number of HBQs required to be
4807  * configured.
4808  **/
4809 int
4810 lpfc_sli_hbq_count(void)
4811 {
4812         return ARRAY_SIZE(lpfc_hbq_defs);
4813 }
4814
4815 /**
4816  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
4817  *
4818  * This function adds the number of hbq entries in every HBQ to get
4819  * the total number of hbq entries required for the HBA and returns
4820  * the total count.
4821  **/
4822 static int
4823 lpfc_sli_hbq_entry_count(void)
4824 {
4825         int  hbq_count = lpfc_sli_hbq_count();
4826         int  count = 0;
4827         int  i;
4828
4829         for (i = 0; i < hbq_count; ++i)
4830                 count += lpfc_hbq_defs[i]->entry_count;
4831         return count;
4832 }
4833
4834 /**
4835  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
4836  *
4837  * This function calculates amount of memory required for all hbq entries
4838  * to be configured and returns the total memory required.
4839  **/
4840 int
4841 lpfc_sli_hbq_size(void)
4842 {
4843         return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
4844 }
4845
4846 /**
4847  * lpfc_sli_hbq_setup - configure and initialize HBQs
4848  * @phba: Pointer to HBA context object.
4849  *
4850  * This function is called during the SLI initialization to configure
4851  * all the HBQs and post buffers to the HBQ. The caller is not
4852  * required to hold any locks. This function will return zero if successful
4853  * else it will return negative error code.
4854  **/
4855 static int
4856 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
4857 {
4858         int  hbq_count = lpfc_sli_hbq_count();
4859         LPFC_MBOXQ_t *pmb;
4860         MAILBOX_t *pmbox;
4861         uint32_t hbqno;
4862         uint32_t hbq_entry_index;
4863
4864                                 /* Get a Mailbox buffer to setup mailbox
4865                                  * commands for HBA initialization
4866                                  */
4867         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4868
4869         if (!pmb)
4870                 return -ENOMEM;
4871
4872         pmbox = &pmb->u.mb;
4873
4874         /* Initialize the struct lpfc_sli_hbq structure for each hbq */
4875         phba->link_state = LPFC_INIT_MBX_CMDS;
4876         phba->hbq_in_use = 1;
4877
4878         hbq_entry_index = 0;
4879         for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
4880                 phba->hbqs[hbqno].next_hbqPutIdx = 0;
4881                 phba->hbqs[hbqno].hbqPutIdx      = 0;
4882                 phba->hbqs[hbqno].local_hbqGetIdx   = 0;
4883                 phba->hbqs[hbqno].entry_count =
4884                         lpfc_hbq_defs[hbqno]->entry_count;
4885                 lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
4886                         hbq_entry_index, pmb);
4887                 hbq_entry_index += phba->hbqs[hbqno].entry_count;
4888
4889                 if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
4890                         /* Adapter failed to init, mbxCmd <cmd> CFG_RING,
4891                            mbxStatus <status>, ring <num> */
4892
4893                         lpfc_printf_log(phba, KERN_ERR,
4894                                         LOG_SLI | LOG_VPORT,
4895                                         "1805 Adapter failed to init. "
4896                                         "Data: x%x x%x x%x\n",
4897                                         pmbox->mbxCommand,
4898                                         pmbox->mbxStatus, hbqno);
4899
4900                         phba->link_state = LPFC_HBA_ERROR;
4901                         mempool_free(pmb, phba->mbox_mem_pool);
4902                         return -ENXIO;
4903                 }
4904         }
4905         phba->hbq_count = hbq_count;
4906
4907         mempool_free(pmb, phba->mbox_mem_pool);
4908
4909         /* Initially populate or replenish the HBQs */
4910         for (hbqno = 0; hbqno < hbq_count; ++hbqno)
4911                 lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
4912         return 0;
4913 }
4914
4915 /**
4916  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
4917  * @phba: Pointer to HBA context object.
4918  *
4919  * This function is called during the SLI initialization to configure
4920  * all the HBQs and post buffers to the HBQ. The caller is not
4921  * required to hold any locks. This function will return zero if successful
4922  * else it will return negative error code.
4923  **/
4924 static int
4925 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
4926 {
4927         phba->hbq_in_use = 1;
4928         /**
4929          * Specific case when the MDS diagnostics is enabled and supported.
4930          * The receive buffer count is truncated to manage the incoming
4931          * traffic.
4932          **/
4933         if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
4934                 phba->hbqs[LPFC_ELS_HBQ].entry_count =
4935                         lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
4936         else
4937                 phba->hbqs[LPFC_ELS_HBQ].entry_count =
4938                         lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
4939         phba->hbq_count = 1;
4940         lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
4941         /* Initially populate or replenish the HBQs */
4942         return 0;
4943 }
4944
4945 /**
4946  * lpfc_sli_config_port - Issue config port mailbox command
4947  * @phba: Pointer to HBA context object.
4948  * @sli_mode: sli mode - 2/3
4949  *
4950  * This function is called by the sli initialization code path
4951  * to issue config_port mailbox command. This function restarts the
4952  * HBA firmware and issues a config_port mailbox command to configure
4953  * the SLI interface in the sli mode specified by sli_mode
4954  * variable. The caller is not required to hold any locks.
4955  * The function returns 0 if successful, else returns negative error
4956  * code.
4957  **/
4958 int
4959 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
4960 {
4961         LPFC_MBOXQ_t *pmb;
4962         uint32_t resetcount = 0, rc = 0, done = 0;
4963
4964         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4965         if (!pmb) {
4966                 phba->link_state = LPFC_HBA_ERROR;
4967                 return -ENOMEM;
4968         }
4969
4970         phba->sli_rev = sli_mode;
4971         while (resetcount < 2 && !done) {
4972                 spin_lock_irq(&phba->hbalock);
4973                 phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
4974                 spin_unlock_irq(&phba->hbalock);
4975                 phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4976                 lpfc_sli_brdrestart(phba);
4977                 rc = lpfc_sli_chipset_init(phba);
4978                 if (rc)
4979                         break;
4980
4981                 spin_lock_irq(&phba->hbalock);
4982                 phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4983                 spin_unlock_irq(&phba->hbalock);
4984                 resetcount++;
4985
4986                 /* Call pre CONFIG_PORT mailbox command initialization.  A
4987                  * value of 0 means the call was successful.  Any other
4988                  * nonzero value is a failure, but if ERESTART is returned,
4989                  * the driver may reset the HBA and try again.
4990                  */
4991                 rc = lpfc_config_port_prep(phba);
4992                 if (rc == -ERESTART) {
4993                         phba->link_state = LPFC_LINK_UNKNOWN;
4994                         continue;
4995                 } else if (rc)
4996                         break;
4997
4998                 phba->link_state = LPFC_INIT_MBX_CMDS;
4999                 lpfc_config_port(phba, pmb);
5000                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5001                 phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5002                                         LPFC_SLI3_HBQ_ENABLED |
5003                                         LPFC_SLI3_CRP_ENABLED |
5004                                         LPFC_SLI3_DSS_ENABLED);
5005                 if (rc != MBX_SUCCESS) {
5006                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5007                                 "0442 Adapter failed to init, mbxCmd x%x "
5008                                 "CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5009                                 pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5010                         spin_lock_irq(&phba->hbalock);
5011                         phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5012                         spin_unlock_irq(&phba->hbalock);
5013                         rc = -ENXIO;
5014                 } else {
5015                         /* Allow asynchronous mailbox command to go through */
5016                         spin_lock_irq(&phba->hbalock);
5017                         phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5018                         spin_unlock_irq(&phba->hbalock);
5019                         done = 1;
5020
5021                         if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5022                             (pmb->u.mb.un.varCfgPort.gasabt == 0))
5023                                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5024                                         "3110 Port did not grant ASABT\n");
5025                 }
5026         }
5027         if (!done) {
5028                 rc = -EINVAL;
5029                 goto do_prep_failed;
5030         }
5031         if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5032                 if (!pmb->u.mb.un.varCfgPort.cMA) {
5033                         rc = -ENXIO;
5034                         goto do_prep_failed;
5035                 }
5036                 if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5037                         phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5038                         phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5039                         phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5040                                 phba->max_vpi : phba->max_vports;
5041
5042                 } else
5043                         phba->max_vpi = 0;
5044                 phba->fips_level = 0;
5045                 phba->fips_spec_rev = 0;
5046                 if (pmb->u.mb.un.varCfgPort.gdss) {
5047                         phba->sli3_options |= LPFC_SLI3_DSS_ENABLED;
5048                         phba->fips_level = pmb->u.mb.un.varCfgPort.fips_level;
5049                         phba->fips_spec_rev = pmb->u.mb.un.varCfgPort.fips_rev;
5050                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5051                                         "2850 Security Crypto Active. FIPS x%d "
5052                                         "(Spec Rev: x%d)",
5053                                         phba->fips_level, phba->fips_spec_rev);
5054                 }
5055                 if (pmb->u.mb.un.varCfgPort.sec_err) {
5056                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5057                                         "2856 Config Port Security Crypto "
5058                                         "Error: x%x ",
5059                                         pmb->u.mb.un.varCfgPort.sec_err);
5060                 }
5061                 if (pmb->u.mb.un.varCfgPort.gerbm)
5062                         phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5063                 if (pmb->u.mb.un.varCfgPort.gcrp)
5064                         phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5065
5066                 phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5067                 phba->port_gp = phba->mbox->us.s3_pgp.port;
5068
5069                 if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5070                         if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5071                                 phba->cfg_enable_bg = 0;
5072                                 phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5073                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5074                                                 "0443 Adapter did not grant "
5075                                                 "BlockGuard\n");
5076                         }
5077                 }
5078         } else {
5079                 phba->hbq_get = NULL;
5080                 phba->port_gp = phba->mbox->us.s2.port;
5081                 phba->max_vpi = 0;
5082         }
5083 do_prep_failed:
5084         mempool_free(pmb, phba->mbox_mem_pool);
5085         return rc;
5086 }
5087
5088
5089 /**
5090  * lpfc_sli_hba_setup - SLI initialization function
5091  * @phba: Pointer to HBA context object.
5092  *
5093  * This function is the main SLI initialization function. This function
5094  * is called by the HBA initialization code, HBA reset code and HBA
5095  * error attention handler code. Caller is not required to hold any
5096  * locks. This function issues config_port mailbox command to configure
5097  * the SLI, setup iocb rings and HBQ rings. In the end the function
5098  * calls the config_port_post function to issue init_link mailbox
5099  * command and to start the discovery. The function will return zero
5100  * if successful, else it will return negative error code.
5101  **/
5102 int
5103 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5104 {
5105         uint32_t rc;
5106         int  mode = 3, i;
5107         int longs;
5108
5109         switch (phba->cfg_sli_mode) {
5110         case 2:
5111                 if (phba->cfg_enable_npiv) {
5112                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
5113                                 "1824 NPIV enabled: Override sli_mode "
5114                                 "parameter (%d) to auto (0).\n",
5115                                 phba->cfg_sli_mode);
5116                         break;
5117                 }
5118                 mode = 2;
5119                 break;
5120         case 0:
5121         case 3:
5122                 break;
5123         default:
5124                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
5125                                 "1819 Unrecognized sli_mode parameter: %d.\n",
5126                                 phba->cfg_sli_mode);
5127
5128                 break;
5129         }
5130         phba->fcp_embed_io = 0; /* SLI4 FC support only */
5131
5132         rc = lpfc_sli_config_port(phba, mode);
5133
5134         if (rc && phba->cfg_sli_mode == 3)
5135                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_VPORT,
5136                                 "1820 Unable to select SLI-3.  "
5137                                 "Not supported by adapter.\n");
5138         if (rc && mode != 2)
5139                 rc = lpfc_sli_config_port(phba, 2);
5140         else if (rc && mode == 2)
5141                 rc = lpfc_sli_config_port(phba, 3);
5142         if (rc)
5143                 goto lpfc_sli_hba_setup_error;
5144
5145         /* Enable PCIe device Advanced Error Reporting (AER) if configured */
5146         if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
5147                 rc = pci_enable_pcie_error_reporting(phba->pcidev);
5148                 if (!rc) {
5149                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5150                                         "2709 This device supports "
5151                                         "Advanced Error Reporting (AER)\n");
5152                         spin_lock_irq(&phba->hbalock);
5153                         phba->hba_flag |= HBA_AER_ENABLED;
5154                         spin_unlock_irq(&phba->hbalock);
5155                 } else {
5156                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5157                                         "2708 This device does not support "
5158                                         "Advanced Error Reporting (AER): %d\n",
5159                                         rc);
5160                         phba->cfg_aer_support = 0;
5161                 }
5162         }
5163
5164         if (phba->sli_rev == 3) {
5165                 phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5166                 phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5167         } else {
5168                 phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5169                 phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5170                 phba->sli3_options = 0;
5171         }
5172
5173         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5174                         "0444 Firmware in SLI %x mode. Max_vpi %d\n",
5175                         phba->sli_rev, phba->max_vpi);
5176         rc = lpfc_sli_ring_map(phba);
5177
5178         if (rc)
5179                 goto lpfc_sli_hba_setup_error;
5180
5181         /* Initialize VPIs. */
5182         if (phba->sli_rev == LPFC_SLI_REV3) {
5183                 /*
5184                  * The VPI bitmask and physical ID array are allocated
5185                  * and initialized once only - at driver load.  A port
5186                  * reset doesn't need to reinitialize this memory.
5187                  */
5188                 if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5189                         longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5190                         phba->vpi_bmask = kcalloc(longs,
5191                                                   sizeof(unsigned long),
5192                                                   GFP_KERNEL);
5193                         if (!phba->vpi_bmask) {
5194                                 rc = -ENOMEM;
5195                                 goto lpfc_sli_hba_setup_error;
5196                         }
5197
5198                         phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5199                                                 sizeof(uint16_t),
5200                                                 GFP_KERNEL);
5201                         if (!phba->vpi_ids) {
5202                                 kfree(phba->vpi_bmask);
5203                                 rc = -ENOMEM;
5204                                 goto lpfc_sli_hba_setup_error;
5205                         }
5206                         for (i = 0; i < phba->max_vpi; i++)
5207                                 phba->vpi_ids[i] = i;
5208                 }
5209         }
5210
5211         /* Init HBQs */
5212         if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5213                 rc = lpfc_sli_hbq_setup(phba);
5214                 if (rc)
5215                         goto lpfc_sli_hba_setup_error;
5216         }
5217         spin_lock_irq(&phba->hbalock);
5218         phba->sli.sli_flag |= LPFC_PROCESS_LA;
5219         spin_unlock_irq(&phba->hbalock);
5220
5221         rc = lpfc_config_port_post(phba);
5222         if (rc)
5223                 goto lpfc_sli_hba_setup_error;
5224
5225         return rc;
5226
5227 lpfc_sli_hba_setup_error:
5228         phba->link_state = LPFC_HBA_ERROR;
5229         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5230                         "0445 Firmware initialization failed\n");
5231         return rc;
5232 }
5233
5234 /**
5235  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5236  * @phba: Pointer to HBA context object.
5237  * @mboxq: mailbox pointer.
5238  * This function issue a dump mailbox command to read config region
5239  * 23 and parse the records in the region and populate driver
5240  * data structure.
5241  **/
5242 static int
5243 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5244 {
5245         LPFC_MBOXQ_t *mboxq;
5246         struct lpfc_dmabuf *mp;
5247         struct lpfc_mqe *mqe;
5248         uint32_t data_length;
5249         int rc;
5250
5251         /* Program the default value of vlan_id and fc_map */
5252         phba->valid_vlan = 0;
5253         phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5254         phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5255         phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5256
5257         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5258         if (!mboxq)
5259                 return -ENOMEM;
5260
5261         mqe = &mboxq->u.mqe;
5262         if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5263                 rc = -ENOMEM;
5264                 goto out_free_mboxq;
5265         }
5266
5267         mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5268         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5269
5270         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5271                         "(%d):2571 Mailbox cmd x%x Status x%x "
5272                         "Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5273                         "x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5274                         "CQ: x%x x%x x%x x%x\n",
5275                         mboxq->vport ? mboxq->vport->vpi : 0,
5276                         bf_get(lpfc_mqe_command, mqe),
5277                         bf_get(lpfc_mqe_status, mqe),
5278                         mqe->un.mb_words[0], mqe->un.mb_words[1],
5279                         mqe->un.mb_words[2], mqe->un.mb_words[3],
5280                         mqe->un.mb_words[4], mqe->un.mb_words[5],
5281                         mqe->un.mb_words[6], mqe->un.mb_words[7],
5282                         mqe->un.mb_words[8], mqe->un.mb_words[9],
5283                         mqe->un.mb_words[10], mqe->un.mb_words[11],
5284                         mqe->un.mb_words[12], mqe->un.mb_words[13],
5285                         mqe->un.mb_words[14], mqe->un.mb_words[15],
5286                         mqe->un.mb_words[16], mqe->un.mb_words[50],
5287                         mboxq->mcqe.word0,
5288                         mboxq->mcqe.mcqe_tag0,  mboxq->mcqe.mcqe_tag1,
5289                         mboxq->mcqe.trailer);
5290
5291         if (rc) {
5292                 lpfc_mbuf_free(phba, mp->virt, mp->phys);
5293                 kfree(mp);
5294                 rc = -EIO;
5295                 goto out_free_mboxq;
5296         }
5297         data_length = mqe->un.mb_words[5];
5298         if (data_length > DMP_RGN23_SIZE) {
5299                 lpfc_mbuf_free(phba, mp->virt, mp->phys);
5300                 kfree(mp);
5301                 rc = -EIO;
5302                 goto out_free_mboxq;
5303         }
5304
5305         lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5306         lpfc_mbuf_free(phba, mp->virt, mp->phys);
5307         kfree(mp);
5308         rc = 0;
5309
5310 out_free_mboxq:
5311         mempool_free(mboxq, phba->mbox_mem_pool);
5312         return rc;
5313 }
5314
5315 /**
5316  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5317  * @phba: pointer to lpfc hba data structure.
5318  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5319  * @vpd: pointer to the memory to hold resulting port vpd data.
5320  * @vpd_size: On input, the number of bytes allocated to @vpd.
5321  *            On output, the number of data bytes in @vpd.
5322  *
5323  * This routine executes a READ_REV SLI4 mailbox command.  In
5324  * addition, this routine gets the port vpd data.
5325  *
5326  * Return codes
5327  *      0 - successful
5328  *      -ENOMEM - could not allocated memory.
5329  **/
5330 static int
5331 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5332                     uint8_t *vpd, uint32_t *vpd_size)
5333 {
5334         int rc = 0;
5335         uint32_t dma_size;
5336         struct lpfc_dmabuf *dmabuf;
5337         struct lpfc_mqe *mqe;
5338
5339         dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5340         if (!dmabuf)
5341                 return -ENOMEM;
5342
5343         /*
5344          * Get a DMA buffer for the vpd data resulting from the READ_REV
5345          * mailbox command.
5346          */
5347         dma_size = *vpd_size;
5348         dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5349                                           &dmabuf->phys, GFP_KERNEL);
5350         if (!dmabuf->virt) {
5351                 kfree(dmabuf);
5352                 return -ENOMEM;
5353         }
5354
5355         /*
5356          * The SLI4 implementation of READ_REV conflicts at word1,
5357          * bits 31:16 and SLI4 adds vpd functionality not present
5358          * in SLI3.  This code corrects the conflicts.
5359          */
5360         lpfc_read_rev(phba, mboxq);
5361         mqe = &mboxq->u.mqe;
5362         mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5363         mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5364         mqe->un.read_rev.word1 &= 0x0000FFFF;
5365         bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5366         bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5367
5368         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5369         if (rc) {
5370                 dma_free_coherent(&phba->pcidev->dev, dma_size,
5371                                   dmabuf->virt, dmabuf->phys);
5372                 kfree(dmabuf);
5373                 return -EIO;
5374         }
5375
5376         /*
5377          * The available vpd length cannot be bigger than the
5378          * DMA buffer passed to the port.  Catch the less than
5379          * case and update the caller's size.
5380          */
5381         if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5382                 *vpd_size = mqe->un.read_rev.avail_vpd_len;
5383
5384         memcpy(vpd, dmabuf->virt, *vpd_size);
5385
5386         dma_free_coherent(&phba->pcidev->dev, dma_size,
5387                           dmabuf->virt, dmabuf->phys);
5388         kfree(dmabuf);
5389         return 0;
5390 }
5391
5392 /**
5393  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5394  * @phba: pointer to lpfc hba data structure.
5395  *
5396  * This routine retrieves SLI4 device physical port name this PCI function
5397  * is attached to.
5398  *
5399  * Return codes
5400  *      0 - successful
5401  *      otherwise - failed to retrieve controller attributes
5402  **/
5403 static int
5404 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5405 {
5406         LPFC_MBOXQ_t *mboxq;
5407         struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5408         struct lpfc_controller_attribute *cntl_attr;
5409         void *virtaddr = NULL;
5410         uint32_t alloclen, reqlen;
5411         uint32_t shdr_status, shdr_add_status;
5412         union lpfc_sli4_cfg_shdr *shdr;
5413         int rc;
5414
5415         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5416         if (!mboxq)
5417                 return -ENOMEM;
5418
5419         /* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5420         reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5421         alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5422                         LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5423                         LPFC_SLI4_MBX_NEMBED);
5424
5425         if (alloclen < reqlen) {
5426                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
5427                                 "3084 Allocated DMA memory size (%d) is "
5428                                 "less than the requested DMA memory size "
5429                                 "(%d)\n", alloclen, reqlen);
5430                 rc = -ENOMEM;
5431                 goto out_free_mboxq;
5432         }
5433         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5434         virtaddr = mboxq->sge_array->addr[0];
5435         mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5436         shdr = &mbx_cntl_attr->cfg_shdr;
5437         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5438         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5439         if (shdr_status || shdr_add_status || rc) {
5440                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5441                                 "3085 Mailbox x%x (x%x/x%x) failed, "
5442                                 "rc:x%x, status:x%x, add_status:x%x\n",
5443                                 bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5444                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5445                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5446                                 rc, shdr_status, shdr_add_status);
5447                 rc = -ENXIO;
5448                 goto out_free_mboxq;
5449         }
5450
5451         cntl_attr = &mbx_cntl_attr->cntl_attr;
5452         phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5453         phba->sli4_hba.lnk_info.lnk_tp =
5454                 bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5455         phba->sli4_hba.lnk_info.lnk_no =
5456                 bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5457
5458         memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
5459         strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
5460                 sizeof(phba->BIOSVersion));
5461
5462         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5463                         "3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s\n",
5464                         phba->sli4_hba.lnk_info.lnk_tp,
5465                         phba->sli4_hba.lnk_info.lnk_no,
5466                         phba->BIOSVersion);
5467 out_free_mboxq:
5468         if (rc != MBX_TIMEOUT) {
5469                 if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5470                         lpfc_sli4_mbox_cmd_free(phba, mboxq);
5471                 else
5472                         mempool_free(mboxq, phba->mbox_mem_pool);
5473         }
5474         return rc;
5475 }
5476
5477 /**
5478  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
5479  * @phba: pointer to lpfc hba data structure.
5480  *
5481  * This routine retrieves SLI4 device physical port name this PCI function
5482  * is attached to.
5483  *
5484  * Return codes
5485  *      0 - successful
5486  *      otherwise - failed to retrieve physical port name
5487  **/
5488 static int
5489 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
5490 {
5491         LPFC_MBOXQ_t *mboxq;
5492         struct lpfc_mbx_get_port_name *get_port_name;
5493         uint32_t shdr_status, shdr_add_status;
5494         union lpfc_sli4_cfg_shdr *shdr;
5495         char cport_name = 0;
5496         int rc;
5497
5498         /* We assume nothing at this point */
5499         phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5500         phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
5501
5502         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5503         if (!mboxq)
5504                 return -ENOMEM;
5505         /* obtain link type and link number via READ_CONFIG */
5506         phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5507         lpfc_sli4_read_config(phba);
5508         if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
5509                 goto retrieve_ppname;
5510
5511         /* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
5512         rc = lpfc_sli4_get_ctl_attr(phba);
5513         if (rc)
5514                 goto out_free_mboxq;
5515
5516 retrieve_ppname:
5517         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5518                 LPFC_MBOX_OPCODE_GET_PORT_NAME,
5519                 sizeof(struct lpfc_mbx_get_port_name) -
5520                 sizeof(struct lpfc_sli4_cfg_mhdr),
5521                 LPFC_SLI4_MBX_EMBED);
5522         get_port_name = &mboxq->u.mqe.un.get_port_name;
5523         shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5524         bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
5525         bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
5526                 phba->sli4_hba.lnk_info.lnk_tp);
5527         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5528         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5529         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5530         if (shdr_status || shdr_add_status || rc) {
5531                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5532                                 "3087 Mailbox x%x (x%x/x%x) failed: "
5533                                 "rc:x%x, status:x%x, add_status:x%x\n",
5534                                 bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5535                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5536                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5537                                 rc, shdr_status, shdr_add_status);
5538                 rc = -ENXIO;
5539                 goto out_free_mboxq;
5540         }
5541         switch (phba->sli4_hba.lnk_info.lnk_no) {
5542         case LPFC_LINK_NUMBER_0:
5543                 cport_name = bf_get(lpfc_mbx_get_port_name_name0,
5544                                 &get_port_name->u.response);
5545                 phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5546                 break;
5547         case LPFC_LINK_NUMBER_1:
5548                 cport_name = bf_get(lpfc_mbx_get_port_name_name1,
5549                                 &get_port_name->u.response);
5550                 phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5551                 break;
5552         case LPFC_LINK_NUMBER_2:
5553                 cport_name = bf_get(lpfc_mbx_get_port_name_name2,
5554                                 &get_port_name->u.response);
5555                 phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5556                 break;
5557         case LPFC_LINK_NUMBER_3:
5558                 cport_name = bf_get(lpfc_mbx_get_port_name_name3,
5559                                 &get_port_name->u.response);
5560                 phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
5561                 break;
5562         default:
5563                 break;
5564         }
5565
5566         if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
5567                 phba->Port[0] = cport_name;
5568                 phba->Port[1] = '\0';
5569                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5570                                 "3091 SLI get port name: %s\n", phba->Port);
5571         }
5572
5573 out_free_mboxq:
5574         if (rc != MBX_TIMEOUT) {
5575                 if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5576                         lpfc_sli4_mbox_cmd_free(phba, mboxq);
5577                 else
5578                         mempool_free(mboxq, phba->mbox_mem_pool);
5579         }
5580         return rc;
5581 }
5582
5583 /**
5584  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
5585  * @phba: pointer to lpfc hba data structure.
5586  *
5587  * This routine is called to explicitly arm the SLI4 device's completion and
5588  * event queues
5589  **/
5590 static void
5591 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
5592 {
5593         int qidx;
5594         struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
5595         struct lpfc_sli4_hdw_queue *qp;
5596         struct lpfc_queue *eq;
5597
5598         sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
5599         sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
5600         if (sli4_hba->nvmels_cq)
5601                 sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
5602                                            LPFC_QUEUE_REARM);
5603
5604         if (sli4_hba->hdwq) {
5605                 /* Loop thru all Hardware Queues */
5606                 for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
5607                         qp = &sli4_hba->hdwq[qidx];
5608                         /* ARM the corresponding CQ */
5609                         sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
5610                                                 LPFC_QUEUE_REARM);
5611                 }
5612
5613                 /* Loop thru all IRQ vectors */
5614                 for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
5615                         eq = sli4_hba->hba_eq_hdl[qidx].eq;
5616                         /* ARM the corresponding EQ */
5617                         sli4_hba->sli4_write_eq_db(phba, eq,
5618                                                    0, LPFC_QUEUE_REARM);
5619                 }
5620         }
5621
5622         if (phba->nvmet_support) {
5623                 for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
5624                         sli4_hba->sli4_write_cq_db(phba,
5625                                 sli4_hba->nvmet_cqset[qidx], 0,
5626                                 LPFC_QUEUE_REARM);
5627                 }
5628         }
5629 }
5630
5631 /**
5632  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
5633  * @phba: Pointer to HBA context object.
5634  * @type: The resource extent type.
5635  * @extnt_count: buffer to hold port available extent count.
5636  * @extnt_size: buffer to hold element count per extent.
5637  *
5638  * This function calls the port and retrievs the number of available
5639  * extents and their size for a particular extent type.
5640  *
5641  * Returns: 0 if successful.  Nonzero otherwise.
5642  **/
5643 int
5644 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
5645                                uint16_t *extnt_count, uint16_t *extnt_size)
5646 {
5647         int rc = 0;
5648         uint32_t length;
5649         uint32_t mbox_tmo;
5650         struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
5651         LPFC_MBOXQ_t *mbox;
5652
5653         mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5654         if (!mbox)
5655                 return -ENOMEM;
5656
5657         /* Find out how many extents are available for this resource type */
5658         length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
5659                   sizeof(struct lpfc_sli4_cfg_mhdr));
5660         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5661                          LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
5662                          length, LPFC_SLI4_MBX_EMBED);
5663
5664         /* Send an extents count of 0 - the GET doesn't use it. */
5665         rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
5666                                         LPFC_SLI4_MBX_EMBED);
5667         if (unlikely(rc)) {
5668                 rc = -EIO;
5669                 goto err_exit;
5670         }
5671
5672         if (!phba->sli4_hba.intr_enable)
5673                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5674         else {
5675                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5676                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5677         }
5678         if (unlikely(rc)) {
5679                 rc = -EIO;
5680                 goto err_exit;
5681         }
5682
5683         rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
5684         if (bf_get(lpfc_mbox_hdr_status,
5685                    &rsrc_info->header.cfg_shdr.response)) {
5686                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5687                                 "2930 Failed to get resource extents "
5688                                 "Status 0x%x Add'l Status 0x%x\n",
5689                                 bf_get(lpfc_mbox_hdr_status,
5690                                        &rsrc_info->header.cfg_shdr.response),
5691                                 bf_get(lpfc_mbox_hdr_add_status,
5692                                        &rsrc_info->header.cfg_shdr.response));
5693                 rc = -EIO;
5694                 goto err_exit;
5695         }
5696
5697         *extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
5698                               &rsrc_info->u.rsp);
5699         *extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
5700                              &rsrc_info->u.rsp);
5701
5702         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5703                         "3162 Retrieved extents type-%d from port: count:%d, "
5704                         "size:%d\n", type, *extnt_count, *extnt_size);
5705
5706 err_exit:
5707         mempool_free(mbox, phba->mbox_mem_pool);
5708         return rc;
5709 }
5710
5711 /**
5712  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
5713  * @phba: Pointer to HBA context object.
5714  * @type: The extent type to check.
5715  *
5716  * This function reads the current available extents from the port and checks
5717  * if the extent count or extent size has changed since the last access.
5718  * Callers use this routine post port reset to understand if there is a
5719  * extent reprovisioning requirement.
5720  *
5721  * Returns:
5722  *   -Error: error indicates problem.
5723  *   1: Extent count or size has changed.
5724  *   0: No changes.
5725  **/
5726 static int
5727 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
5728 {
5729         uint16_t curr_ext_cnt, rsrc_ext_cnt;
5730         uint16_t size_diff, rsrc_ext_size;
5731         int rc = 0;
5732         struct lpfc_rsrc_blks *rsrc_entry;
5733         struct list_head *rsrc_blk_list = NULL;
5734
5735         size_diff = 0;
5736         curr_ext_cnt = 0;
5737         rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5738                                             &rsrc_ext_cnt,
5739                                             &rsrc_ext_size);
5740         if (unlikely(rc))
5741                 return -EIO;
5742
5743         switch (type) {
5744         case LPFC_RSC_TYPE_FCOE_RPI:
5745                 rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5746                 break;
5747         case LPFC_RSC_TYPE_FCOE_VPI:
5748                 rsrc_blk_list = &phba->lpfc_vpi_blk_list;
5749                 break;
5750         case LPFC_RSC_TYPE_FCOE_XRI:
5751                 rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5752                 break;
5753         case LPFC_RSC_TYPE_FCOE_VFI:
5754                 rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
5755                 break;
5756         default:
5757                 break;
5758         }
5759
5760         list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
5761                 curr_ext_cnt++;
5762                 if (rsrc_entry->rsrc_size != rsrc_ext_size)
5763                         size_diff++;
5764         }
5765
5766         if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
5767                 rc = 1;
5768
5769         return rc;
5770 }
5771
5772 /**
5773  * lpfc_sli4_cfg_post_extnts -
5774  * @phba: Pointer to HBA context object.
5775  * @extnt_cnt - number of available extents.
5776  * @type - the extent type (rpi, xri, vfi, vpi).
5777  * @emb - buffer to hold either MBX_EMBED or MBX_NEMBED operation.
5778  * @mbox - pointer to the caller's allocated mailbox structure.
5779  *
5780  * This function executes the extents allocation request.  It also
5781  * takes care of the amount of memory needed to allocate or get the
5782  * allocated extents. It is the caller's responsibility to evaluate
5783  * the response.
5784  *
5785  * Returns:
5786  *   -Error:  Error value describes the condition found.
5787  *   0: if successful
5788  **/
5789 static int
5790 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
5791                           uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
5792 {
5793         int rc = 0;
5794         uint32_t req_len;
5795         uint32_t emb_len;
5796         uint32_t alloc_len, mbox_tmo;
5797
5798         /* Calculate the total requested length of the dma memory */
5799         req_len = extnt_cnt * sizeof(uint16_t);
5800
5801         /*
5802          * Calculate the size of an embedded mailbox.  The uint32_t
5803          * accounts for extents-specific word.
5804          */
5805         emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
5806                 sizeof(uint32_t);
5807
5808         /*
5809          * Presume the allocation and response will fit into an embedded
5810          * mailbox.  If not true, reconfigure to a non-embedded mailbox.
5811          */
5812         *emb = LPFC_SLI4_MBX_EMBED;
5813         if (req_len > emb_len) {
5814                 req_len = extnt_cnt * sizeof(uint16_t) +
5815                         sizeof(union lpfc_sli4_cfg_shdr) +
5816                         sizeof(uint32_t);
5817                 *emb = LPFC_SLI4_MBX_NEMBED;
5818         }
5819
5820         alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
5821                                      LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
5822                                      req_len, *emb);
5823         if (alloc_len < req_len) {
5824                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
5825                         "2982 Allocated DMA memory size (x%x) is "
5826                         "less than the requested DMA memory "
5827                         "size (x%x)\n", alloc_len, req_len);
5828                 return -ENOMEM;
5829         }
5830         rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
5831         if (unlikely(rc))
5832                 return -EIO;
5833
5834         if (!phba->sli4_hba.intr_enable)
5835                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
5836         else {
5837                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
5838                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
5839         }
5840
5841         if (unlikely(rc))
5842                 rc = -EIO;
5843         return rc;
5844 }
5845
5846 /**
5847  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
5848  * @phba: Pointer to HBA context object.
5849  * @type:  The resource extent type to allocate.
5850  *
5851  * This function allocates the number of elements for the specified
5852  * resource type.
5853  **/
5854 static int
5855 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
5856 {
5857         bool emb = false;
5858         uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
5859         uint16_t rsrc_id, rsrc_start, j, k;
5860         uint16_t *ids;
5861         int i, rc;
5862         unsigned long longs;
5863         unsigned long *bmask;
5864         struct lpfc_rsrc_blks *rsrc_blks;
5865         LPFC_MBOXQ_t *mbox;
5866         uint32_t length;
5867         struct lpfc_id_range *id_array = NULL;
5868         void *virtaddr = NULL;
5869         struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
5870         struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
5871         struct list_head *ext_blk_list;
5872
5873         rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
5874                                             &rsrc_cnt,
5875                                             &rsrc_size);
5876         if (unlikely(rc))
5877                 return -EIO;
5878
5879         if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
5880                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
5881                         "3009 No available Resource Extents "
5882                         "for resource type 0x%x: Count: 0x%x, "
5883                         "Size 0x%x\n", type, rsrc_cnt,
5884                         rsrc_size);
5885                 return -ENOMEM;
5886         }
5887
5888         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
5889                         "2903 Post resource extents type-0x%x: "
5890                         "count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
5891
5892         mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5893         if (!mbox)
5894                 return -ENOMEM;
5895
5896         rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
5897         if (unlikely(rc)) {
5898                 rc = -EIO;
5899                 goto err_exit;
5900         }
5901
5902         /*
5903          * Figure out where the response is located.  Then get local pointers
5904          * to the response data.  The port does not guarantee to respond to
5905          * all extents counts request so update the local variable with the
5906          * allocated count from the port.
5907          */
5908         if (emb == LPFC_SLI4_MBX_EMBED) {
5909                 rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
5910                 id_array = &rsrc_ext->u.rsp.id[0];
5911                 rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
5912         } else {
5913                 virtaddr = mbox->sge_array->addr[0];
5914                 n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
5915                 rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
5916                 id_array = &n_rsrc->id;
5917         }
5918
5919         longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
5920         rsrc_id_cnt = rsrc_cnt * rsrc_size;
5921
5922         /*
5923          * Based on the resource size and count, correct the base and max
5924          * resource values.
5925          */
5926         length = sizeof(struct lpfc_rsrc_blks);
5927         switch (type) {
5928         case LPFC_RSC_TYPE_FCOE_RPI:
5929                 phba->sli4_hba.rpi_bmask = kcalloc(longs,
5930                                                    sizeof(unsigned long),
5931                                                    GFP_KERNEL);
5932                 if (unlikely(!phba->sli4_hba.rpi_bmask)) {
5933                         rc = -ENOMEM;
5934                         goto err_exit;
5935                 }
5936                 phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
5937                                                  sizeof(uint16_t),
5938                                                  GFP_KERNEL);
5939                 if (unlikely(!phba->sli4_hba.rpi_ids)) {
5940                         kfree(phba->sli4_hba.rpi_bmask);
5941                         rc = -ENOMEM;
5942                         goto err_exit;
5943                 }
5944
5945                 /*
5946                  * The next_rpi was initialized with the maximum available
5947                  * count but the port may allocate a smaller number.  Catch
5948                  * that case and update the next_rpi.
5949                  */
5950                 phba->sli4_hba.next_rpi = rsrc_id_cnt;
5951
5952                 /* Initialize local ptrs for common extent processing later. */
5953                 bmask = phba->sli4_hba.rpi_bmask;
5954                 ids = phba->sli4_hba.rpi_ids;
5955                 ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
5956                 break;
5957         case LPFC_RSC_TYPE_FCOE_VPI:
5958                 phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
5959                                           GFP_KERNEL);
5960                 if (unlikely(!phba->vpi_bmask)) {
5961                         rc = -ENOMEM;
5962                         goto err_exit;
5963                 }
5964                 phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
5965                                          GFP_KERNEL);
5966                 if (unlikely(!phba->vpi_ids)) {
5967                         kfree(phba->vpi_bmask);
5968                         rc = -ENOMEM;
5969                         goto err_exit;
5970                 }
5971
5972                 /* Initialize local ptrs for common extent processing later. */
5973                 bmask = phba->vpi_bmask;
5974                 ids = phba->vpi_ids;
5975                 ext_blk_list = &phba->lpfc_vpi_blk_list;
5976                 break;
5977         case LPFC_RSC_TYPE_FCOE_XRI:
5978                 phba->sli4_hba.xri_bmask = kcalloc(longs,
5979                                                    sizeof(unsigned long),
5980                                                    GFP_KERNEL);
5981                 if (unlikely(!phba->sli4_hba.xri_bmask)) {
5982                         rc = -ENOMEM;
5983                         goto err_exit;
5984                 }
5985                 phba->sli4_hba.max_cfg_param.xri_used = 0;
5986                 phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
5987                                                  sizeof(uint16_t),
5988                                                  GFP_KERNEL);
5989                 if (unlikely(!phba->sli4_hba.xri_ids)) {
5990                         kfree(phba->sli4_hba.xri_bmask);
5991                         rc = -ENOMEM;
5992                         goto err_exit;
5993                 }
5994
5995                 /* Initialize local ptrs for common extent processing later. */
5996                 bmask = phba->sli4_hba.xri_bmask;
5997                 ids = phba->sli4_hba.xri_ids;
5998                 ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
5999                 break;
6000         case LPFC_RSC_TYPE_FCOE_VFI:
6001                 phba->sli4_hba.vfi_bmask = kcalloc(longs,
6002                                                    sizeof(unsigned long),
6003                                                    GFP_KERNEL);
6004                 if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6005                         rc = -ENOMEM;
6006                         goto err_exit;
6007                 }
6008                 phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6009                                                  sizeof(uint16_t),
6010                                                  GFP_KERNEL);
6011                 if (unlikely(!phba->sli4_hba.vfi_ids)) {
6012                         kfree(phba->sli4_hba.vfi_bmask);
6013                         rc = -ENOMEM;
6014                         goto err_exit;
6015                 }
6016
6017                 /* Initialize local ptrs for common extent processing later. */
6018                 bmask = phba->sli4_hba.vfi_bmask;
6019                 ids = phba->sli4_hba.vfi_ids;
6020                 ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6021                 break;
6022         default:
6023                 /* Unsupported Opcode.  Fail call. */
6024                 id_array = NULL;
6025                 bmask = NULL;
6026                 ids = NULL;
6027                 ext_blk_list = NULL;
6028                 goto err_exit;
6029         }
6030
6031         /*
6032          * Complete initializing the extent configuration with the
6033          * allocated ids assigned to this function.  The bitmask serves
6034          * as an index into the array and manages the available ids.  The
6035          * array just stores the ids communicated to the port via the wqes.
6036          */
6037         for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6038                 if ((i % 2) == 0)
6039                         rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6040                                          &id_array[k]);
6041                 else
6042                         rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6043                                          &id_array[k]);
6044
6045                 rsrc_blks = kzalloc(length, GFP_KERNEL);
6046                 if (unlikely(!rsrc_blks)) {
6047                         rc = -ENOMEM;
6048                         kfree(bmask);
6049                         kfree(ids);
6050                         goto err_exit;
6051                 }
6052                 rsrc_blks->rsrc_start = rsrc_id;
6053                 rsrc_blks->rsrc_size = rsrc_size;
6054                 list_add_tail(&rsrc_blks->list, ext_blk_list);
6055                 rsrc_start = rsrc_id;
6056                 if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6057                         phba->sli4_hba.io_xri_start = rsrc_start +
6058                                 lpfc_sli4_get_iocb_cnt(phba);
6059                 }
6060
6061                 while (rsrc_id < (rsrc_start + rsrc_size)) {
6062                         ids[j] = rsrc_id;
6063                         rsrc_id++;
6064                         j++;
6065                 }
6066                 /* Entire word processed.  Get next word.*/
6067                 if ((i % 2) == 1)
6068                         k++;
6069         }
6070  err_exit:
6071         lpfc_sli4_mbox_cmd_free(phba, mbox);
6072         return rc;
6073 }
6074
6075
6076
6077 /**
6078  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6079  * @phba: Pointer to HBA context object.
6080  * @type: the extent's type.
6081  *
6082  * This function deallocates all extents of a particular resource type.
6083  * SLI4 does not allow for deallocating a particular extent range.  It
6084  * is the caller's responsibility to release all kernel memory resources.
6085  **/
6086 static int
6087 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6088 {
6089         int rc;
6090         uint32_t length, mbox_tmo = 0;
6091         LPFC_MBOXQ_t *mbox;
6092         struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6093         struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6094
6095         mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6096         if (!mbox)
6097                 return -ENOMEM;
6098
6099         /*
6100          * This function sends an embedded mailbox because it only sends the
6101          * the resource type.  All extents of this type are released by the
6102          * port.
6103          */
6104         length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6105                   sizeof(struct lpfc_sli4_cfg_mhdr));
6106         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6107                          LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6108                          length, LPFC_SLI4_MBX_EMBED);
6109
6110         /* Send an extents count of 0 - the dealloc doesn't use it. */
6111         rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6112                                         LPFC_SLI4_MBX_EMBED);
6113         if (unlikely(rc)) {
6114                 rc = -EIO;
6115                 goto out_free_mbox;
6116         }
6117         if (!phba->sli4_hba.intr_enable)
6118                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6119         else {
6120                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6121                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6122         }
6123         if (unlikely(rc)) {
6124                 rc = -EIO;
6125                 goto out_free_mbox;
6126         }
6127
6128         dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6129         if (bf_get(lpfc_mbox_hdr_status,
6130                    &dealloc_rsrc->header.cfg_shdr.response)) {
6131                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
6132                                 "2919 Failed to release resource extents "
6133                                 "for type %d - Status 0x%x Add'l Status 0x%x. "
6134                                 "Resource memory not released.\n",
6135                                 type,
6136                                 bf_get(lpfc_mbox_hdr_status,
6137                                     &dealloc_rsrc->header.cfg_shdr.response),
6138                                 bf_get(lpfc_mbox_hdr_add_status,
6139                                     &dealloc_rsrc->header.cfg_shdr.response));
6140                 rc = -EIO;
6141                 goto out_free_mbox;
6142         }
6143
6144         /* Release kernel memory resources for the specific type. */
6145         switch (type) {
6146         case LPFC_RSC_TYPE_FCOE_VPI:
6147                 kfree(phba->vpi_bmask);
6148                 kfree(phba->vpi_ids);
6149                 bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6150                 list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6151                                     &phba->lpfc_vpi_blk_list, list) {
6152                         list_del_init(&rsrc_blk->list);
6153                         kfree(rsrc_blk);
6154                 }
6155                 phba->sli4_hba.max_cfg_param.vpi_used = 0;
6156                 break;
6157         case LPFC_RSC_TYPE_FCOE_XRI:
6158                 kfree(phba->sli4_hba.xri_bmask);
6159                 kfree(phba->sli4_hba.xri_ids);
6160                 list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6161                                     &phba->sli4_hba.lpfc_xri_blk_list, list) {
6162                         list_del_init(&rsrc_blk->list);
6163                         kfree(rsrc_blk);
6164                 }
6165                 break;
6166         case LPFC_RSC_TYPE_FCOE_VFI:
6167                 kfree(phba->sli4_hba.vfi_bmask);
6168                 kfree(phba->sli4_hba.vfi_ids);
6169                 bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6170                 list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6171                                     &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6172                         list_del_init(&rsrc_blk->list);
6173                         kfree(rsrc_blk);
6174                 }
6175                 break;
6176         case LPFC_RSC_TYPE_FCOE_RPI:
6177                 /* RPI bitmask and physical id array are cleaned up earlier. */
6178                 list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6179                                     &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6180                         list_del_init(&rsrc_blk->list);
6181                         kfree(rsrc_blk);
6182                 }
6183                 break;
6184         default:
6185                 break;
6186         }
6187
6188         bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6189
6190  out_free_mbox:
6191         mempool_free(mbox, phba->mbox_mem_pool);
6192         return rc;
6193 }
6194
6195 static void
6196 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6197                   uint32_t feature)
6198 {
6199         uint32_t len;
6200
6201         len = sizeof(struct lpfc_mbx_set_feature) -
6202                 sizeof(struct lpfc_sli4_cfg_mhdr);
6203         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6204                          LPFC_MBOX_OPCODE_SET_FEATURES, len,
6205                          LPFC_SLI4_MBX_EMBED);
6206
6207         switch (feature) {
6208         case LPFC_SET_UE_RECOVERY:
6209                 bf_set(lpfc_mbx_set_feature_UER,
6210                        &mbox->u.mqe.un.set_feature, 1);
6211                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6212                 mbox->u.mqe.un.set_feature.param_len = 8;
6213                 break;
6214         case LPFC_SET_MDS_DIAGS:
6215                 bf_set(lpfc_mbx_set_feature_mds,
6216                        &mbox->u.mqe.un.set_feature, 1);
6217                 bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6218                        &mbox->u.mqe.un.set_feature, 1);
6219                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6220                 mbox->u.mqe.un.set_feature.param_len = 8;
6221                 break;
6222         case LPFC_SET_DUAL_DUMP:
6223                 bf_set(lpfc_mbx_set_feature_dd,
6224                        &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6225                 bf_set(lpfc_mbx_set_feature_ddquery,
6226                        &mbox->u.mqe.un.set_feature, 0);
6227                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6228                 mbox->u.mqe.un.set_feature.param_len = 4;
6229                 break;
6230         }
6231
6232         return;
6233 }
6234
6235 /**
6236  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6237  * @phba: Pointer to HBA context object.
6238  *
6239  * Disable FW logging into host memory on the adapter. To
6240  * be done before reading logs from the host memory.
6241  **/
6242 void
6243 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6244 {
6245         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6246
6247         spin_lock_irq(&phba->hbalock);
6248         ras_fwlog->state = INACTIVE;
6249         spin_unlock_irq(&phba->hbalock);
6250
6251         /* Disable FW logging to host memory */
6252         writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6253                phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6254
6255         /* Wait 10ms for firmware to stop using DMA buffer */
6256         usleep_range(10 * 1000, 20 * 1000);
6257 }
6258
6259 /**
6260  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6261  * @phba: Pointer to HBA context object.
6262  *
6263  * This function is called to free memory allocated for RAS FW logging
6264  * support in the driver.
6265  **/
6266 void
6267 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6268 {
6269         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6270         struct lpfc_dmabuf *dmabuf, *next;
6271
6272         if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6273                 list_for_each_entry_safe(dmabuf, next,
6274                                     &ras_fwlog->fwlog_buff_list,
6275                                     list) {
6276                         list_del(&dmabuf->list);
6277                         dma_free_coherent(&phba->pcidev->dev,
6278                                           LPFC_RAS_MAX_ENTRY_SIZE,
6279                                           dmabuf->virt, dmabuf->phys);
6280                         kfree(dmabuf);
6281                 }
6282         }
6283
6284         if (ras_fwlog->lwpd.virt) {
6285                 dma_free_coherent(&phba->pcidev->dev,
6286                                   sizeof(uint32_t) * 2,
6287                                   ras_fwlog->lwpd.virt,
6288                                   ras_fwlog->lwpd.phys);
6289                 ras_fwlog->lwpd.virt = NULL;
6290         }
6291
6292         spin_lock_irq(&phba->hbalock);
6293         ras_fwlog->state = INACTIVE;
6294         spin_unlock_irq(&phba->hbalock);
6295 }
6296
6297 /**
6298  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6299  * @phba: Pointer to HBA context object.
6300  * @fwlog_buff_count: Count of buffers to be created.
6301  *
6302  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6303  * to update FW log is posted to the adapter.
6304  * Buffer count is calculated based on module param ras_fwlog_buffsize
6305  * Size of each buffer posted to FW is 64K.
6306  **/
6307
6308 static int
6309 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6310                         uint32_t fwlog_buff_count)
6311 {
6312         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6313         struct lpfc_dmabuf *dmabuf;
6314         int rc = 0, i = 0;
6315
6316         /* Initialize List */
6317         INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6318
6319         /* Allocate memory for the LWPD */
6320         ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6321                                             sizeof(uint32_t) * 2,
6322                                             &ras_fwlog->lwpd.phys,
6323                                             GFP_KERNEL);
6324         if (!ras_fwlog->lwpd.virt) {
6325                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6326                                 "6185 LWPD Memory Alloc Failed\n");
6327
6328                 return -ENOMEM;
6329         }
6330
6331         ras_fwlog->fw_buffcount = fwlog_buff_count;
6332         for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6333                 dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6334                                  GFP_KERNEL);
6335                 if (!dmabuf) {
6336                         rc = -ENOMEM;
6337                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6338                                         "6186 Memory Alloc failed FW logging");
6339                         goto free_mem;
6340                 }
6341
6342                 dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6343                                                   LPFC_RAS_MAX_ENTRY_SIZE,
6344                                                   &dmabuf->phys, GFP_KERNEL);
6345                 if (!dmabuf->virt) {
6346                         kfree(dmabuf);
6347                         rc = -ENOMEM;
6348                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6349                                         "6187 DMA Alloc Failed FW logging");
6350                         goto free_mem;
6351                 }
6352                 dmabuf->buffer_tag = i;
6353                 list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6354         }
6355
6356 free_mem:
6357         if (rc)
6358                 lpfc_sli4_ras_dma_free(phba);
6359
6360         return rc;
6361 }
6362
6363 /**
6364  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6365  * @phba: pointer to lpfc hba data structure.
6366  * @pmboxq: pointer to the driver internal queue element for mailbox command.
6367  *
6368  * Completion handler for driver's RAS MBX command to the device.
6369  **/
6370 static void
6371 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6372 {
6373         MAILBOX_t *mb;
6374         union lpfc_sli4_cfg_shdr *shdr;
6375         uint32_t shdr_status, shdr_add_status;
6376         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6377
6378         mb = &pmb->u.mb;
6379
6380         shdr = (union lpfc_sli4_cfg_shdr *)
6381                 &pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6382         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6383         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6384
6385         if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6386                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
6387                                 "6188 FW LOG mailbox "
6388                                 "completed with status x%x add_status x%x,"
6389                                 " mbx status x%x\n",
6390                                 shdr_status, shdr_add_status, mb->mbxStatus);
6391
6392                 ras_fwlog->ras_hwsupport = false;
6393                 goto disable_ras;
6394         }
6395
6396         spin_lock_irq(&phba->hbalock);
6397         ras_fwlog->state = ACTIVE;
6398         spin_unlock_irq(&phba->hbalock);
6399         mempool_free(pmb, phba->mbox_mem_pool);
6400
6401         return;
6402
6403 disable_ras:
6404         /* Free RAS DMA memory */
6405         lpfc_sli4_ras_dma_free(phba);
6406         mempool_free(pmb, phba->mbox_mem_pool);
6407 }
6408
6409 /**
6410  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
6411  * @phba: pointer to lpfc hba data structure.
6412  * @fwlog_level: Logging verbosity level.
6413  * @fwlog_enable: Enable/Disable logging.
6414  *
6415  * Initialize memory and post mailbox command to enable FW logging in host
6416  * memory.
6417  **/
6418 int
6419 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
6420                          uint32_t fwlog_level,
6421                          uint32_t fwlog_enable)
6422 {
6423         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6424         struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
6425         struct lpfc_dmabuf *dmabuf;
6426         LPFC_MBOXQ_t *mbox;
6427         uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
6428         int rc = 0;
6429
6430         spin_lock_irq(&phba->hbalock);
6431         ras_fwlog->state = INACTIVE;
6432         spin_unlock_irq(&phba->hbalock);
6433
6434         fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
6435                           phba->cfg_ras_fwlog_buffsize);
6436         fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
6437
6438         /*
6439          * If re-enabling FW logging support use earlier allocated
6440          * DMA buffers while posting MBX command.
6441          **/
6442         if (!ras_fwlog->lwpd.virt) {
6443                 rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
6444                 if (rc) {
6445                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6446                                         "6189 FW Log Memory Allocation Failed");
6447                         return rc;
6448                 }
6449         }
6450
6451         /* Setup Mailbox command */
6452         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6453         if (!mbox) {
6454                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6455                                 "6190 RAS MBX Alloc Failed");
6456                 rc = -ENOMEM;
6457                 goto mem_free;
6458         }
6459
6460         ras_fwlog->fw_loglevel = fwlog_level;
6461         len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
6462                 sizeof(struct lpfc_sli4_cfg_mhdr));
6463
6464         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
6465                          LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
6466                          len, LPFC_SLI4_MBX_EMBED);
6467
6468         mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
6469         bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
6470                fwlog_enable);
6471         bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
6472                ras_fwlog->fw_loglevel);
6473         bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
6474                ras_fwlog->fw_buffcount);
6475         bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
6476                LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
6477
6478         /* Update DMA buffer address */
6479         list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
6480                 memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
6481
6482                 mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
6483                         putPaddrLow(dmabuf->phys);
6484
6485                 mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
6486                         putPaddrHigh(dmabuf->phys);
6487         }
6488
6489         /* Update LPWD address */
6490         mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
6491         mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
6492
6493         spin_lock_irq(&phba->hbalock);
6494         ras_fwlog->state = REG_INPROGRESS;
6495         spin_unlock_irq(&phba->hbalock);
6496         mbox->vport = phba->pport;
6497         mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
6498
6499         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
6500
6501         if (rc == MBX_NOT_FINISHED) {
6502                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6503                                 "6191 FW-Log Mailbox failed. "
6504                                 "status %d mbxStatus : x%x", rc,
6505                                 bf_get(lpfc_mqe_status, &mbox->u.mqe));
6506                 mempool_free(mbox, phba->mbox_mem_pool);
6507                 rc = -EIO;
6508                 goto mem_free;
6509         } else
6510                 rc = 0;
6511 mem_free:
6512         if (rc)
6513                 lpfc_sli4_ras_dma_free(phba);
6514
6515         return rc;
6516 }
6517
6518 /**
6519  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
6520  * @phba: Pointer to HBA context object.
6521  *
6522  * Check if RAS is supported on the adapter and initialize it.
6523  **/
6524 void
6525 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
6526 {
6527         /* Check RAS FW Log needs to be enabled or not */
6528         if (lpfc_check_fwlog_support(phba))
6529                 return;
6530
6531         lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
6532                                  LPFC_RAS_ENABLE_LOGGING);
6533 }
6534
6535 /**
6536  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
6537  * @phba: Pointer to HBA context object.
6538  *
6539  * This function allocates all SLI4 resource identifiers.
6540  **/
6541 int
6542 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
6543 {
6544         int i, rc, error = 0;
6545         uint16_t count, base;
6546         unsigned long longs;
6547
6548         if (!phba->sli4_hba.rpi_hdrs_in_use)
6549                 phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
6550         if (phba->sli4_hba.extents_in_use) {
6551                 /*
6552                  * The port supports resource extents. The XRI, VPI, VFI, RPI
6553                  * resource extent count must be read and allocated before
6554                  * provisioning the resource id arrays.
6555                  */
6556                 if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6557                     LPFC_IDX_RSRC_RDY) {
6558                         /*
6559                          * Extent-based resources are set - the driver could
6560                          * be in a port reset. Figure out if any corrective
6561                          * actions need to be taken.
6562                          */
6563                         rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6564                                                  LPFC_RSC_TYPE_FCOE_VFI);
6565                         if (rc != 0)
6566                                 error++;
6567                         rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6568                                                  LPFC_RSC_TYPE_FCOE_VPI);
6569                         if (rc != 0)
6570                                 error++;
6571                         rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6572                                                  LPFC_RSC_TYPE_FCOE_XRI);
6573                         if (rc != 0)
6574                                 error++;
6575                         rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
6576                                                  LPFC_RSC_TYPE_FCOE_RPI);
6577                         if (rc != 0)
6578                                 error++;
6579
6580                         /*
6581                          * It's possible that the number of resources
6582                          * provided to this port instance changed between
6583                          * resets.  Detect this condition and reallocate
6584                          * resources.  Otherwise, there is no action.
6585                          */
6586                         if (error) {
6587                                 lpfc_printf_log(phba, KERN_INFO,
6588                                                 LOG_MBOX | LOG_INIT,
6589                                                 "2931 Detected extent resource "
6590                                                 "change.  Reallocating all "
6591                                                 "extents.\n");
6592                                 rc = lpfc_sli4_dealloc_extent(phba,
6593                                                  LPFC_RSC_TYPE_FCOE_VFI);
6594                                 rc = lpfc_sli4_dealloc_extent(phba,
6595                                                  LPFC_RSC_TYPE_FCOE_VPI);
6596                                 rc = lpfc_sli4_dealloc_extent(phba,
6597                                                  LPFC_RSC_TYPE_FCOE_XRI);
6598                                 rc = lpfc_sli4_dealloc_extent(phba,
6599                                                  LPFC_RSC_TYPE_FCOE_RPI);
6600                         } else
6601                                 return 0;
6602                 }
6603
6604                 rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
6605                 if (unlikely(rc))
6606                         goto err_exit;
6607
6608                 rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
6609                 if (unlikely(rc))
6610                         goto err_exit;
6611
6612                 rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
6613                 if (unlikely(rc))
6614                         goto err_exit;
6615
6616                 rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
6617                 if (unlikely(rc))
6618                         goto err_exit;
6619                 bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6620                        LPFC_IDX_RSRC_RDY);
6621                 return rc;
6622         } else {
6623                 /*
6624                  * The port does not support resource extents.  The XRI, VPI,
6625                  * VFI, RPI resource ids were determined from READ_CONFIG.
6626                  * Just allocate the bitmasks and provision the resource id
6627                  * arrays.  If a port reset is active, the resources don't
6628                  * need any action - just exit.
6629                  */
6630                 if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
6631                     LPFC_IDX_RSRC_RDY) {
6632                         lpfc_sli4_dealloc_resource_identifiers(phba);
6633                         lpfc_sli4_remove_rpis(phba);
6634                 }
6635                 /* RPIs. */
6636                 count = phba->sli4_hba.max_cfg_param.max_rpi;
6637                 if (count <= 0) {
6638                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6639                                         "3279 Invalid provisioning of "
6640                                         "rpi:%d\n", count);
6641                         rc = -EINVAL;
6642                         goto err_exit;
6643                 }
6644                 base = phba->sli4_hba.max_cfg_param.rpi_base;
6645                 longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6646                 phba->sli4_hba.rpi_bmask = kcalloc(longs,
6647                                                    sizeof(unsigned long),
6648                                                    GFP_KERNEL);
6649                 if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6650                         rc = -ENOMEM;
6651                         goto err_exit;
6652                 }
6653                 phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
6654                                                  GFP_KERNEL);
6655                 if (unlikely(!phba->sli4_hba.rpi_ids)) {
6656                         rc = -ENOMEM;
6657                         goto free_rpi_bmask;
6658                 }
6659
6660                 for (i = 0; i < count; i++)
6661                         phba->sli4_hba.rpi_ids[i] = base + i;
6662
6663                 /* VPIs. */
6664                 count = phba->sli4_hba.max_cfg_param.max_vpi;
6665                 if (count <= 0) {
6666                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6667                                         "3280 Invalid provisioning of "
6668                                         "vpi:%d\n", count);
6669                         rc = -EINVAL;
6670                         goto free_rpi_ids;
6671                 }
6672                 base = phba->sli4_hba.max_cfg_param.vpi_base;
6673                 longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6674                 phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6675                                           GFP_KERNEL);
6676                 if (unlikely(!phba->vpi_bmask)) {
6677                         rc = -ENOMEM;
6678                         goto free_rpi_ids;
6679                 }
6680                 phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
6681                                         GFP_KERNEL);
6682                 if (unlikely(!phba->vpi_ids)) {
6683                         rc = -ENOMEM;
6684                         goto free_vpi_bmask;
6685                 }
6686
6687                 for (i = 0; i < count; i++)
6688                         phba->vpi_ids[i] = base + i;
6689
6690                 /* XRIs. */
6691                 count = phba->sli4_hba.max_cfg_param.max_xri;
6692                 if (count <= 0) {
6693                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6694                                         "3281 Invalid provisioning of "
6695                                         "xri:%d\n", count);
6696                         rc = -EINVAL;
6697                         goto free_vpi_ids;
6698                 }
6699                 base = phba->sli4_hba.max_cfg_param.xri_base;
6700                 longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6701                 phba->sli4_hba.xri_bmask = kcalloc(longs,
6702                                                    sizeof(unsigned long),
6703                                                    GFP_KERNEL);
6704                 if (unlikely(!phba->sli4_hba.xri_bmask)) {
6705                         rc = -ENOMEM;
6706                         goto free_vpi_ids;
6707                 }
6708                 phba->sli4_hba.max_cfg_param.xri_used = 0;
6709                 phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
6710                                                  GFP_KERNEL);
6711                 if (unlikely(!phba->sli4_hba.xri_ids)) {
6712                         rc = -ENOMEM;
6713                         goto free_xri_bmask;
6714                 }
6715
6716                 for (i = 0; i < count; i++)
6717                         phba->sli4_hba.xri_ids[i] = base + i;
6718
6719                 /* VFIs. */
6720                 count = phba->sli4_hba.max_cfg_param.max_vfi;
6721                 if (count <= 0) {
6722                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
6723                                         "3282 Invalid provisioning of "
6724                                         "vfi:%d\n", count);
6725                         rc = -EINVAL;
6726                         goto free_xri_ids;
6727                 }
6728                 base = phba->sli4_hba.max_cfg_param.vfi_base;
6729                 longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
6730                 phba->sli4_hba.vfi_bmask = kcalloc(longs,
6731                                                    sizeof(unsigned long),
6732                                                    GFP_KERNEL);
6733                 if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6734                         rc = -ENOMEM;
6735                         goto free_xri_ids;
6736                 }
6737                 phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
6738                                                  GFP_KERNEL);
6739                 if (unlikely(!phba->sli4_hba.vfi_ids)) {
6740                         rc = -ENOMEM;
6741                         goto free_vfi_bmask;
6742                 }
6743
6744                 for (i = 0; i < count; i++)
6745                         phba->sli4_hba.vfi_ids[i] = base + i;
6746
6747                 /*
6748                  * Mark all resources ready.  An HBA reset doesn't need
6749                  * to reset the initialization.
6750                  */
6751                 bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
6752                        LPFC_IDX_RSRC_RDY);
6753                 return 0;
6754         }
6755
6756  free_vfi_bmask:
6757         kfree(phba->sli4_hba.vfi_bmask);
6758         phba->sli4_hba.vfi_bmask = NULL;
6759  free_xri_ids:
6760         kfree(phba->sli4_hba.xri_ids);
6761         phba->sli4_hba.xri_ids = NULL;
6762  free_xri_bmask:
6763         kfree(phba->sli4_hba.xri_bmask);
6764         phba->sli4_hba.xri_bmask = NULL;
6765  free_vpi_ids:
6766         kfree(phba->vpi_ids);
6767         phba->vpi_ids = NULL;
6768  free_vpi_bmask:
6769         kfree(phba->vpi_bmask);
6770         phba->vpi_bmask = NULL;
6771  free_rpi_ids:
6772         kfree(phba->sli4_hba.rpi_ids);
6773         phba->sli4_hba.rpi_ids = NULL;
6774  free_rpi_bmask:
6775         kfree(phba->sli4_hba.rpi_bmask);
6776         phba->sli4_hba.rpi_bmask = NULL;
6777  err_exit:
6778         return rc;
6779 }
6780
6781 /**
6782  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
6783  * @phba: Pointer to HBA context object.
6784  *
6785  * This function allocates the number of elements for the specified
6786  * resource type.
6787  **/
6788 int
6789 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
6790 {
6791         if (phba->sli4_hba.extents_in_use) {
6792                 lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
6793                 lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
6794                 lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
6795                 lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
6796         } else {
6797                 kfree(phba->vpi_bmask);
6798                 phba->sli4_hba.max_cfg_param.vpi_used = 0;
6799                 kfree(phba->vpi_ids);
6800                 bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6801                 kfree(phba->sli4_hba.xri_bmask);
6802                 kfree(phba->sli4_hba.xri_ids);
6803                 kfree(phba->sli4_hba.vfi_bmask);
6804                 kfree(phba->sli4_hba.vfi_ids);
6805                 bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6806                 bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6807         }
6808
6809         return 0;
6810 }
6811
6812 /**
6813  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
6814  * @phba: Pointer to HBA context object.
6815  * @type: The resource extent type.
6816  * @extnt_count: buffer to hold port extent count response
6817  * @extnt_size: buffer to hold port extent size response.
6818  *
6819  * This function calls the port to read the host allocated extents
6820  * for a particular type.
6821  **/
6822 int
6823 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
6824                                uint16_t *extnt_cnt, uint16_t *extnt_size)
6825 {
6826         bool emb;
6827         int rc = 0;
6828         uint16_t curr_blks = 0;
6829         uint32_t req_len, emb_len;
6830         uint32_t alloc_len, mbox_tmo;
6831         struct list_head *blk_list_head;
6832         struct lpfc_rsrc_blks *rsrc_blk;
6833         LPFC_MBOXQ_t *mbox;
6834         void *virtaddr = NULL;
6835         struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6836         struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6837         union  lpfc_sli4_cfg_shdr *shdr;
6838
6839         switch (type) {
6840         case LPFC_RSC_TYPE_FCOE_VPI:
6841                 blk_list_head = &phba->lpfc_vpi_blk_list;
6842                 break;
6843         case LPFC_RSC_TYPE_FCOE_XRI:
6844                 blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
6845                 break;
6846         case LPFC_RSC_TYPE_FCOE_VFI:
6847                 blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
6848                 break;
6849         case LPFC_RSC_TYPE_FCOE_RPI:
6850                 blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
6851                 break;
6852         default:
6853                 return -EIO;
6854         }
6855
6856         /* Count the number of extents currently allocatd for this type. */
6857         list_for_each_entry(rsrc_blk, blk_list_head, list) {
6858                 if (curr_blks == 0) {
6859                         /*
6860                          * The GET_ALLOCATED mailbox does not return the size,
6861                          * just the count.  The size should be just the size
6862                          * stored in the current allocated block and all sizes
6863                          * for an extent type are the same so set the return
6864                          * value now.
6865                          */
6866                         *extnt_size = rsrc_blk->rsrc_size;
6867                 }
6868                 curr_blks++;
6869         }
6870
6871         /*
6872          * Calculate the size of an embedded mailbox.  The uint32_t
6873          * accounts for extents-specific word.
6874          */
6875         emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6876                 sizeof(uint32_t);
6877
6878         /*
6879          * Presume the allocation and response will fit into an embedded
6880          * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6881          */
6882         emb = LPFC_SLI4_MBX_EMBED;
6883         req_len = emb_len;
6884         if (req_len > emb_len) {
6885                 req_len = curr_blks * sizeof(uint16_t) +
6886                         sizeof(union lpfc_sli4_cfg_shdr) +
6887                         sizeof(uint32_t);
6888                 emb = LPFC_SLI4_MBX_NEMBED;
6889         }
6890
6891         mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6892         if (!mbox)
6893                 return -ENOMEM;
6894         memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
6895
6896         alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6897                                      LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
6898                                      req_len, emb);
6899         if (alloc_len < req_len) {
6900                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
6901                         "2983 Allocated DMA memory size (x%x) is "
6902                         "less than the requested DMA memory "
6903                         "size (x%x)\n", alloc_len, req_len);
6904                 rc = -ENOMEM;
6905                 goto err_exit;
6906         }
6907         rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
6908         if (unlikely(rc)) {
6909                 rc = -EIO;
6910                 goto err_exit;
6911         }
6912
6913         if (!phba->sli4_hba.intr_enable)
6914                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6915         else {
6916                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6917                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6918         }
6919
6920         if (unlikely(rc)) {
6921                 rc = -EIO;
6922                 goto err_exit;
6923         }
6924
6925         /*
6926          * Figure out where the response is located.  Then get local pointers
6927          * to the response data.  The port does not guarantee to respond to
6928          * all extents counts request so update the local variable with the
6929          * allocated count from the port.
6930          */
6931         if (emb == LPFC_SLI4_MBX_EMBED) {
6932                 rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6933                 shdr = &rsrc_ext->header.cfg_shdr;
6934                 *extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6935         } else {
6936                 virtaddr = mbox->sge_array->addr[0];
6937                 n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6938                 shdr = &n_rsrc->cfg_shdr;
6939                 *extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6940         }
6941
6942         if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
6943                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
6944                         "2984 Failed to read allocated resources "
6945                         "for type %d - Status 0x%x Add'l Status 0x%x.\n",
6946                         type,
6947                         bf_get(lpfc_mbox_hdr_status, &shdr->response),
6948                         bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
6949                 rc = -EIO;
6950                 goto err_exit;
6951         }
6952  err_exit:
6953         lpfc_sli4_mbox_cmd_free(phba, mbox);
6954         return rc;
6955 }
6956
6957 /**
6958  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
6959  * @phba: pointer to lpfc hba data structure.
6960  * @pring: Pointer to driver SLI ring object.
6961  * @sgl_list: linked link of sgl buffers to post
6962  * @cnt: number of linked list buffers
6963  *
6964  * This routine walks the list of buffers that have been allocated and
6965  * repost them to the port by using SGL block post. This is needed after a
6966  * pci_function_reset/warm_start or start. It attempts to construct blocks
6967  * of buffer sgls which contains contiguous xris and uses the non-embedded
6968  * SGL block post mailbox commands to post them to the port. For single
6969  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
6970  * mailbox command for posting.
6971  *
6972  * Returns: 0 = success, non-zero failure.
6973  **/
6974 static int
6975 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
6976                           struct list_head *sgl_list, int cnt)
6977 {
6978         struct lpfc_sglq *sglq_entry = NULL;
6979         struct lpfc_sglq *sglq_entry_next = NULL;
6980         struct lpfc_sglq *sglq_entry_first = NULL;
6981         int status, total_cnt;
6982         int post_cnt = 0, num_posted = 0, block_cnt = 0;
6983         int last_xritag = NO_XRI;
6984         LIST_HEAD(prep_sgl_list);
6985         LIST_HEAD(blck_sgl_list);
6986         LIST_HEAD(allc_sgl_list);
6987         LIST_HEAD(post_sgl_list);
6988         LIST_HEAD(free_sgl_list);
6989
6990         spin_lock_irq(&phba->hbalock);
6991         spin_lock(&phba->sli4_hba.sgl_list_lock);
6992         list_splice_init(sgl_list, &allc_sgl_list);
6993         spin_unlock(&phba->sli4_hba.sgl_list_lock);
6994         spin_unlock_irq(&phba->hbalock);
6995
6996         total_cnt = cnt;
6997         list_for_each_entry_safe(sglq_entry, sglq_entry_next,
6998                                  &allc_sgl_list, list) {
6999                 list_del_init(&sglq_entry->list);
7000                 block_cnt++;
7001                 if ((last_xritag != NO_XRI) &&
7002                     (sglq_entry->sli4_xritag != last_xritag + 1)) {
7003                         /* a hole in xri block, form a sgl posting block */
7004                         list_splice_init(&prep_sgl_list, &blck_sgl_list);
7005                         post_cnt = block_cnt - 1;
7006                         /* prepare list for next posting block */
7007                         list_add_tail(&sglq_entry->list, &prep_sgl_list);
7008                         block_cnt = 1;
7009                 } else {
7010                         /* prepare list for next posting block */
7011                         list_add_tail(&sglq_entry->list, &prep_sgl_list);
7012                         /* enough sgls for non-embed sgl mbox command */
7013                         if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7014                                 list_splice_init(&prep_sgl_list,
7015                                                  &blck_sgl_list);
7016                                 post_cnt = block_cnt;
7017                                 block_cnt = 0;
7018                         }
7019                 }
7020                 num_posted++;
7021
7022                 /* keep track of last sgl's xritag */
7023                 last_xritag = sglq_entry->sli4_xritag;
7024
7025                 /* end of repost sgl list condition for buffers */
7026                 if (num_posted == total_cnt) {
7027                         if (post_cnt == 0) {
7028                                 list_splice_init(&prep_sgl_list,
7029                                                  &blck_sgl_list);
7030                                 post_cnt = block_cnt;
7031                         } else if (block_cnt == 1) {
7032                                 status = lpfc_sli4_post_sgl(phba,
7033                                                 sglq_entry->phys, 0,
7034                                                 sglq_entry->sli4_xritag);
7035                                 if (!status) {
7036                                         /* successful, put sgl to posted list */
7037                                         list_add_tail(&sglq_entry->list,
7038                                                       &post_sgl_list);
7039                                 } else {
7040                                         /* Failure, put sgl to free list */
7041                                         lpfc_printf_log(phba, KERN_WARNING,
7042                                                 LOG_SLI,
7043                                                 "3159 Failed to post "
7044                                                 "sgl, xritag:x%x\n",
7045                                                 sglq_entry->sli4_xritag);
7046                                         list_add_tail(&sglq_entry->list,
7047                                                       &free_sgl_list);
7048                                         total_cnt--;
7049                                 }
7050                         }
7051                 }
7052
7053                 /* continue until a nembed page worth of sgls */
7054                 if (post_cnt == 0)
7055                         continue;
7056
7057                 /* post the buffer list sgls as a block */
7058                 status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7059                                                  post_cnt);
7060
7061                 if (!status) {
7062                         /* success, put sgl list to posted sgl list */
7063                         list_splice_init(&blck_sgl_list, &post_sgl_list);
7064                 } else {
7065                         /* Failure, put sgl list to free sgl list */
7066                         sglq_entry_first = list_first_entry(&blck_sgl_list,
7067                                                             struct lpfc_sglq,
7068                                                             list);
7069                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7070                                         "3160 Failed to post sgl-list, "
7071                                         "xritag:x%x-x%x\n",
7072                                         sglq_entry_first->sli4_xritag,
7073                                         (sglq_entry_first->sli4_xritag +
7074                                          post_cnt - 1));
7075                         list_splice_init(&blck_sgl_list, &free_sgl_list);
7076                         total_cnt -= post_cnt;
7077                 }
7078
7079                 /* don't reset xirtag due to hole in xri block */
7080                 if (block_cnt == 0)
7081                         last_xritag = NO_XRI;
7082
7083                 /* reset sgl post count for next round of posting */
7084                 post_cnt = 0;
7085         }
7086
7087         /* free the sgls failed to post */
7088         lpfc_free_sgl_list(phba, &free_sgl_list);
7089
7090         /* push sgls posted to the available list */
7091         if (!list_empty(&post_sgl_list)) {
7092                 spin_lock_irq(&phba->hbalock);
7093                 spin_lock(&phba->sli4_hba.sgl_list_lock);
7094                 list_splice_init(&post_sgl_list, sgl_list);
7095                 spin_unlock(&phba->sli4_hba.sgl_list_lock);
7096                 spin_unlock_irq(&phba->hbalock);
7097         } else {
7098                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7099                                 "3161 Failure to post sgl to port.\n");
7100                 return -EIO;
7101         }
7102
7103         /* return the number of XRIs actually posted */
7104         return total_cnt;
7105 }
7106
7107 /**
7108  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7109  * @phba: pointer to lpfc hba data structure.
7110  *
7111  * This routine walks the list of nvme buffers that have been allocated and
7112  * repost them to the port by using SGL block post. This is needed after a
7113  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7114  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7115  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7116  *
7117  * Returns: 0 = success, non-zero failure.
7118  **/
7119 static int
7120 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7121 {
7122         LIST_HEAD(post_nblist);
7123         int num_posted, rc = 0;
7124
7125         /* get all NVME buffers need to repost to a local list */
7126         lpfc_io_buf_flush(phba, &post_nblist);
7127
7128         /* post the list of nvme buffer sgls to port if available */
7129         if (!list_empty(&post_nblist)) {
7130                 num_posted = lpfc_sli4_post_io_sgl_list(
7131                         phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7132                 /* failed to post any nvme buffer, return error */
7133                 if (num_posted == 0)
7134                         rc = -EIO;
7135         }
7136         return rc;
7137 }
7138
7139 static void
7140 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7141 {
7142         uint32_t len;
7143
7144         len = sizeof(struct lpfc_mbx_set_host_data) -
7145                 sizeof(struct lpfc_sli4_cfg_mhdr);
7146         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7147                          LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7148                          LPFC_SLI4_MBX_EMBED);
7149
7150         mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7151         mbox->u.mqe.un.set_host_data.param_len =
7152                                         LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7153         snprintf(mbox->u.mqe.un.set_host_data.data,
7154                  LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7155                  "Linux %s v"LPFC_DRIVER_VERSION,
7156                  (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7157 }
7158
7159 int
7160 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7161                     struct lpfc_queue *drq, int count, int idx)
7162 {
7163         int rc, i;
7164         struct lpfc_rqe hrqe;
7165         struct lpfc_rqe drqe;
7166         struct lpfc_rqb *rqbp;
7167         unsigned long flags;
7168         struct rqb_dmabuf *rqb_buffer;
7169         LIST_HEAD(rqb_buf_list);
7170
7171         spin_lock_irqsave(&phba->hbalock, flags);
7172         rqbp = hrq->rqbp;
7173         for (i = 0; i < count; i++) {
7174                 /* IF RQ is already full, don't bother */
7175                 if (rqbp->buffer_count + i >= rqbp->entry_count - 1)
7176                         break;
7177                 rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7178                 if (!rqb_buffer)
7179                         break;
7180                 rqb_buffer->hrq = hrq;
7181                 rqb_buffer->drq = drq;
7182                 rqb_buffer->idx = idx;
7183                 list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7184         }
7185         while (!list_empty(&rqb_buf_list)) {
7186                 list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7187                                  hbuf.list);
7188
7189                 hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7190                 hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7191                 drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7192                 drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7193                 rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7194                 if (rc < 0) {
7195                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7196                                         "6421 Cannot post to HRQ %d: %x %x %x "
7197                                         "DRQ %x %x\n",
7198                                         hrq->queue_id,
7199                                         hrq->host_index,
7200                                         hrq->hba_index,
7201                                         hrq->entry_count,
7202                                         drq->host_index,
7203                                         drq->hba_index);
7204                         rqbp->rqb_free_buffer(phba, rqb_buffer);
7205                 } else {
7206                         list_add_tail(&rqb_buffer->hbuf.list,
7207                                       &rqbp->rqb_buffer_list);
7208                         rqbp->buffer_count++;
7209                 }
7210         }
7211         spin_unlock_irqrestore(&phba->hbalock, flags);
7212         return 1;
7213 }
7214
7215 /**
7216  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
7217  * @phba: Pointer to HBA context object.
7218  *
7219  * This function is the main SLI4 device initialization PCI function. This
7220  * function is called by the HBA initialization code, HBA reset code and
7221  * HBA error attention handler code. Caller is not required to hold any
7222  * locks.
7223  **/
7224 int
7225 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
7226 {
7227         int rc, i, cnt, len, dd;
7228         LPFC_MBOXQ_t *mboxq;
7229         struct lpfc_mqe *mqe;
7230         uint8_t *vpd;
7231         uint32_t vpd_size;
7232         uint32_t ftr_rsp = 0;
7233         struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
7234         struct lpfc_vport *vport = phba->pport;
7235         struct lpfc_dmabuf *mp;
7236         struct lpfc_rqb *rqbp;
7237
7238         /* Perform a PCI function reset to start from clean */
7239         rc = lpfc_pci_function_reset(phba);
7240         if (unlikely(rc))
7241                 return -ENODEV;
7242
7243         /* Check the HBA Host Status Register for readyness */
7244         rc = lpfc_sli4_post_status_check(phba);
7245         if (unlikely(rc))
7246                 return -ENODEV;
7247         else {
7248                 spin_lock_irq(&phba->hbalock);
7249                 phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
7250                 spin_unlock_irq(&phba->hbalock);
7251         }
7252
7253         /*
7254          * Allocate a single mailbox container for initializing the
7255          * port.
7256          */
7257         mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7258         if (!mboxq)
7259                 return -ENOMEM;
7260
7261         /* Issue READ_REV to collect vpd and FW information. */
7262         vpd_size = SLI4_PAGE_SIZE;
7263         vpd = kzalloc(vpd_size, GFP_KERNEL);
7264         if (!vpd) {
7265                 rc = -ENOMEM;
7266                 goto out_free_mbox;
7267         }
7268
7269         rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
7270         if (unlikely(rc)) {
7271                 kfree(vpd);
7272                 goto out_free_mbox;
7273         }
7274
7275         mqe = &mboxq->u.mqe;
7276         phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
7277         if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
7278                 phba->hba_flag |= HBA_FCOE_MODE;
7279                 phba->fcp_embed_io = 0; /* SLI4 FC support only */
7280         } else {
7281                 phba->hba_flag &= ~HBA_FCOE_MODE;
7282         }
7283
7284         if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
7285                 LPFC_DCBX_CEE_MODE)
7286                 phba->hba_flag |= HBA_FIP_SUPPORT;
7287         else
7288                 phba->hba_flag &= ~HBA_FIP_SUPPORT;
7289
7290         phba->hba_flag &= ~HBA_IOQ_FLUSH;
7291
7292         if (phba->sli_rev != LPFC_SLI_REV4) {
7293                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7294                         "0376 READ_REV Error. SLI Level %d "
7295                         "FCoE enabled %d\n",
7296                         phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
7297                 rc = -EIO;
7298                 kfree(vpd);
7299                 goto out_free_mbox;
7300         }
7301
7302         /*
7303          * Continue initialization with default values even if driver failed
7304          * to read FCoE param config regions, only read parameters if the
7305          * board is FCoE
7306          */
7307         if (phba->hba_flag & HBA_FCOE_MODE &&
7308             lpfc_sli4_read_fcoe_params(phba))
7309                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
7310                         "2570 Failed to read FCoE parameters\n");
7311
7312         /*
7313          * Retrieve sli4 device physical port name, failure of doing it
7314          * is considered as non-fatal.
7315          */
7316         rc = lpfc_sli4_retrieve_pport_name(phba);
7317         if (!rc)
7318                 lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7319                                 "3080 Successful retrieving SLI4 device "
7320                                 "physical port name: %s.\n", phba->Port);
7321
7322         rc = lpfc_sli4_get_ctl_attr(phba);
7323         if (!rc)
7324                 lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7325                                 "8351 Successful retrieving SLI4 device "
7326                                 "CTL ATTR\n");
7327
7328         /*
7329          * Evaluate the read rev and vpd data. Populate the driver
7330          * state with the results. If this routine fails, the failure
7331          * is not fatal as the driver will use generic values.
7332          */
7333         rc = lpfc_parse_vpd(phba, vpd, vpd_size);
7334         if (unlikely(!rc)) {
7335                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7336                                 "0377 Error %d parsing vpd. "
7337                                 "Using defaults.\n", rc);
7338                 rc = 0;
7339         }
7340         kfree(vpd);
7341
7342         /* Save information as VPD data */
7343         phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
7344         phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
7345
7346         /*
7347          * This is because first G7 ASIC doesn't support the standard
7348          * 0x5a NVME cmd descriptor type/subtype
7349          */
7350         if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7351                         LPFC_SLI_INTF_IF_TYPE_6) &&
7352             (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
7353             (phba->vpd.rev.smRev == 0) &&
7354             (phba->cfg_nvme_embed_cmd == 1))
7355                 phba->cfg_nvme_embed_cmd = 0;
7356
7357         phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
7358         phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
7359                                          &mqe->un.read_rev);
7360         phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
7361                                        &mqe->un.read_rev);
7362         phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
7363                                             &mqe->un.read_rev);
7364         phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
7365                                            &mqe->un.read_rev);
7366         phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
7367         memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
7368         phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
7369         memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
7370         phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
7371         memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
7372         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
7373                         "(%d):0380 READ_REV Status x%x "
7374                         "fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
7375                         mboxq->vport ? mboxq->vport->vpi : 0,
7376                         bf_get(lpfc_mqe_status, mqe),
7377                         phba->vpd.rev.opFwName,
7378                         phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
7379                         phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
7380
7381         if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
7382             LPFC_SLI_INTF_IF_TYPE_0) {
7383                 lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
7384                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7385                 if (rc == MBX_SUCCESS) {
7386                         phba->hba_flag |= HBA_RECOVERABLE_UE;
7387                         /* Set 1Sec interval to detect UE */
7388                         phba->eratt_poll_interval = 1;
7389                         phba->sli4_hba.ue_to_sr = bf_get(
7390                                         lpfc_mbx_set_feature_UESR,
7391                                         &mboxq->u.mqe.un.set_feature);
7392                         phba->sli4_hba.ue_to_rp = bf_get(
7393                                         lpfc_mbx_set_feature_UERP,
7394                                         &mboxq->u.mqe.un.set_feature);
7395                 }
7396         }
7397
7398         if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
7399                 /* Enable MDS Diagnostics only if the SLI Port supports it */
7400                 lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
7401                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7402                 if (rc != MBX_SUCCESS)
7403                         phba->mds_diags_support = 0;
7404         }
7405
7406         /*
7407          * Discover the port's supported feature set and match it against the
7408          * hosts requests.
7409          */
7410         lpfc_request_features(phba, mboxq);
7411         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7412         if (unlikely(rc)) {
7413                 rc = -EIO;
7414                 goto out_free_mbox;
7415         }
7416
7417         /*
7418          * The port must support FCP initiator mode as this is the
7419          * only mode running in the host.
7420          */
7421         if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
7422                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7423                                 "0378 No support for fcpi mode.\n");
7424                 ftr_rsp++;
7425         }
7426
7427         /* Performance Hints are ONLY for FCoE */
7428         if (phba->hba_flag & HBA_FCOE_MODE) {
7429                 if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
7430                         phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
7431                 else
7432                         phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
7433         }
7434
7435         /*
7436          * If the port cannot support the host's requested features
7437          * then turn off the global config parameters to disable the
7438          * feature in the driver.  This is not a fatal error.
7439          */
7440         if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
7441                 if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
7442                         phba->cfg_enable_bg = 0;
7443                         phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
7444                         ftr_rsp++;
7445                 }
7446         }
7447
7448         if (phba->max_vpi && phba->cfg_enable_npiv &&
7449             !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7450                 ftr_rsp++;
7451
7452         if (ftr_rsp) {
7453                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7454                                 "0379 Feature Mismatch Data: x%08x %08x "
7455                                 "x%x x%x x%x\n", mqe->un.req_ftrs.word2,
7456                                 mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
7457                                 phba->cfg_enable_npiv, phba->max_vpi);
7458                 if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
7459                         phba->cfg_enable_bg = 0;
7460                 if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
7461                         phba->cfg_enable_npiv = 0;
7462         }
7463
7464         /* These SLI3 features are assumed in SLI4 */
7465         spin_lock_irq(&phba->hbalock);
7466         phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
7467         spin_unlock_irq(&phba->hbalock);
7468
7469         /* Always try to enable dual dump feature if we can */
7470         lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
7471         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7472         dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
7473         if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
7474                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_INIT,
7475                                 "6448 Dual Dump is enabled\n");
7476         else
7477                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
7478                                 "6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
7479                                 "rc:x%x dd:x%x\n",
7480                                 bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7481                                 lpfc_sli_config_mbox_subsys_get(
7482                                         phba, mboxq),
7483                                 lpfc_sli_config_mbox_opcode_get(
7484                                         phba, mboxq),
7485                                 rc, dd);
7486         /*
7487          * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
7488          * calls depends on these resources to complete port setup.
7489          */
7490         rc = lpfc_sli4_alloc_resource_identifiers(phba);
7491         if (rc) {
7492                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7493                                 "2920 Failed to alloc Resource IDs "
7494                                 "rc = x%x\n", rc);
7495                 goto out_free_mbox;
7496         }
7497
7498         lpfc_set_host_data(phba, mboxq);
7499
7500         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7501         if (rc) {
7502                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
7503                                 "2134 Failed to set host os driver version %x",
7504                                 rc);
7505         }
7506
7507         /* Read the port's service parameters. */
7508         rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
7509         if (rc) {
7510                 phba->link_state = LPFC_HBA_ERROR;
7511                 rc = -ENOMEM;
7512                 goto out_free_mbox;
7513         }
7514
7515         mboxq->vport = vport;
7516         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7517         mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
7518         if (rc == MBX_SUCCESS) {
7519                 memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
7520                 rc = 0;
7521         }
7522
7523         /*
7524          * This memory was allocated by the lpfc_read_sparam routine. Release
7525          * it to the mbuf pool.
7526          */
7527         lpfc_mbuf_free(phba, mp->virt, mp->phys);
7528         kfree(mp);
7529         mboxq->ctx_buf = NULL;
7530         if (unlikely(rc)) {
7531                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7532                                 "0382 READ_SPARAM command failed "
7533                                 "status %d, mbxStatus x%x\n",
7534                                 rc, bf_get(lpfc_mqe_status, mqe));
7535                 phba->link_state = LPFC_HBA_ERROR;
7536                 rc = -EIO;
7537                 goto out_free_mbox;
7538         }
7539
7540         lpfc_update_vport_wwn(vport);
7541
7542         /* Update the fc_host data structures with new wwn. */
7543         fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
7544         fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
7545
7546         /* Create all the SLI4 queues */
7547         rc = lpfc_sli4_queue_create(phba);
7548         if (rc) {
7549                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7550                                 "3089 Failed to allocate queues\n");
7551                 rc = -ENODEV;
7552                 goto out_free_mbox;
7553         }
7554         /* Set up all the queues to the device */
7555         rc = lpfc_sli4_queue_setup(phba);
7556         if (unlikely(rc)) {
7557                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7558                                 "0381 Error %d during queue setup.\n ", rc);
7559                 goto out_stop_timers;
7560         }
7561         /* Initialize the driver internal SLI layer lists. */
7562         lpfc_sli4_setup(phba);
7563         lpfc_sli4_queue_init(phba);
7564
7565         /* update host els xri-sgl sizes and mappings */
7566         rc = lpfc_sli4_els_sgl_update(phba);
7567         if (unlikely(rc)) {
7568                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7569                                 "1400 Failed to update xri-sgl size and "
7570                                 "mapping: %d\n", rc);
7571                 goto out_destroy_queue;
7572         }
7573
7574         /* register the els sgl pool to the port */
7575         rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
7576                                        phba->sli4_hba.els_xri_cnt);
7577         if (unlikely(rc < 0)) {
7578                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7579                                 "0582 Error %d during els sgl post "
7580                                 "operation\n", rc);
7581                 rc = -ENODEV;
7582                 goto out_destroy_queue;
7583         }
7584         phba->sli4_hba.els_xri_cnt = rc;
7585
7586         if (phba->nvmet_support) {
7587                 /* update host nvmet xri-sgl sizes and mappings */
7588                 rc = lpfc_sli4_nvmet_sgl_update(phba);
7589                 if (unlikely(rc)) {
7590                         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7591                                         "6308 Failed to update nvmet-sgl size "
7592                                         "and mapping: %d\n", rc);
7593                         goto out_destroy_queue;
7594                 }
7595
7596                 /* register the nvmet sgl pool to the port */
7597                 rc = lpfc_sli4_repost_sgl_list(
7598                         phba,
7599                         &phba->sli4_hba.lpfc_nvmet_sgl_list,
7600                         phba->sli4_hba.nvmet_xri_cnt);
7601                 if (unlikely(rc < 0)) {
7602                         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7603                                         "3117 Error %d during nvmet "
7604                                         "sgl post\n", rc);
7605                         rc = -ENODEV;
7606                         goto out_destroy_queue;
7607                 }
7608                 phba->sli4_hba.nvmet_xri_cnt = rc;
7609
7610                 /* We allocate an iocbq for every receive context SGL.
7611                  * The additional allocation is for abort and ls handling.
7612                  */
7613                 cnt = phba->sli4_hba.nvmet_xri_cnt +
7614                         phba->sli4_hba.max_cfg_param.max_xri;
7615         } else {
7616                 /* update host common xri-sgl sizes and mappings */
7617                 rc = lpfc_sli4_io_sgl_update(phba);
7618                 if (unlikely(rc)) {
7619                         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7620                                         "6082 Failed to update nvme-sgl size "
7621                                         "and mapping: %d\n", rc);
7622                         goto out_destroy_queue;
7623                 }
7624
7625                 /* register the allocated common sgl pool to the port */
7626                 rc = lpfc_sli4_repost_io_sgl_list(phba);
7627                 if (unlikely(rc)) {
7628                         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7629                                         "6116 Error %d during nvme sgl post "
7630                                         "operation\n", rc);
7631                         /* Some NVME buffers were moved to abort nvme list */
7632                         /* A pci function reset will repost them */
7633                         rc = -ENODEV;
7634                         goto out_destroy_queue;
7635                 }
7636                 /* Each lpfc_io_buf job structure has an iocbq element.
7637                  * This cnt provides for abort, els, ct and ls requests.
7638                  */
7639                 cnt = phba->sli4_hba.max_cfg_param.max_xri;
7640         }
7641
7642         if (!phba->sli.iocbq_lookup) {
7643                 /* Initialize and populate the iocb list per host */
7644                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7645                                 "2821 initialize iocb list with %d entries\n",
7646                                 cnt);
7647                 rc = lpfc_init_iocb_list(phba, cnt);
7648                 if (rc) {
7649                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7650                                         "1413 Failed to init iocb list.\n");
7651                         goto out_destroy_queue;
7652                 }
7653         }
7654
7655         if (phba->nvmet_support)
7656                 lpfc_nvmet_create_targetport(phba);
7657
7658         if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
7659                 /* Post initial buffers to all RQs created */
7660                 for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
7661                         rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
7662                         INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
7663                         rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
7664                         rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
7665                         rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
7666                         rqbp->buffer_count = 0;
7667
7668                         lpfc_post_rq_buffer(
7669                                 phba, phba->sli4_hba.nvmet_mrq_hdr[i],
7670                                 phba->sli4_hba.nvmet_mrq_data[i],
7671                                 phba->cfg_nvmet_mrq_post, i);
7672                 }
7673         }
7674
7675         /* Post the rpi header region to the device. */
7676         rc = lpfc_sli4_post_all_rpi_hdrs(phba);
7677         if (unlikely(rc)) {
7678                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
7679                                 "0393 Error %d during rpi post operation\n",
7680                                 rc);
7681                 rc = -ENODEV;
7682                 goto out_destroy_queue;
7683         }
7684         lpfc_sli4_node_prep(phba);
7685
7686         if (!(phba->hba_flag & HBA_FCOE_MODE)) {
7687                 if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
7688                         /*
7689                          * The FC Port needs to register FCFI (index 0)
7690                          */
7691                         lpfc_reg_fcfi(phba, mboxq);
7692                         mboxq->vport = phba->pport;
7693                         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7694                         if (rc != MBX_SUCCESS)
7695                                 goto out_unset_queue;
7696                         rc = 0;
7697                         phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
7698                                                 &mboxq->u.mqe.un.reg_fcfi);
7699                 } else {
7700                         /* We are a NVME Target mode with MRQ > 1 */
7701
7702                         /* First register the FCFI */
7703                         lpfc_reg_fcfi_mrq(phba, mboxq, 0);
7704                         mboxq->vport = phba->pport;
7705                         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7706                         if (rc != MBX_SUCCESS)
7707                                 goto out_unset_queue;
7708                         rc = 0;
7709                         phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
7710                                                 &mboxq->u.mqe.un.reg_fcfi_mrq);
7711
7712                         /* Next register the MRQs */
7713                         lpfc_reg_fcfi_mrq(phba, mboxq, 1);
7714                         mboxq->vport = phba->pport;
7715                         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7716                         if (rc != MBX_SUCCESS)
7717                                 goto out_unset_queue;
7718                         rc = 0;
7719                 }
7720                 /* Check if the port is configured to be disabled */
7721                 lpfc_sli_read_link_ste(phba);
7722         }
7723
7724         /* Don't post more new bufs if repost already recovered
7725          * the nvme sgls.
7726          */
7727         if (phba->nvmet_support == 0) {
7728                 if (phba->sli4_hba.io_xri_cnt == 0) {
7729                         len = lpfc_new_io_buf(
7730                                               phba, phba->sli4_hba.io_xri_max);
7731                         if (len == 0) {
7732                                 rc = -ENOMEM;
7733                                 goto out_unset_queue;
7734                         }
7735
7736                         if (phba->cfg_xri_rebalancing)
7737                                 lpfc_create_multixri_pools(phba);
7738                 }
7739         } else {
7740                 phba->cfg_xri_rebalancing = 0;
7741         }
7742
7743         /* Allow asynchronous mailbox command to go through */
7744         spin_lock_irq(&phba->hbalock);
7745         phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
7746         spin_unlock_irq(&phba->hbalock);
7747
7748         /* Post receive buffers to the device */
7749         lpfc_sli4_rb_setup(phba);
7750
7751         /* Reset HBA FCF states after HBA reset */
7752         phba->fcf.fcf_flag = 0;
7753         phba->fcf.current_rec.flag = 0;
7754
7755         /* Start the ELS watchdog timer */
7756         mod_timer(&vport->els_tmofunc,
7757                   jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
7758
7759         /* Start heart beat timer */
7760         mod_timer(&phba->hb_tmofunc,
7761                   jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
7762         phba->hb_outstanding = 0;
7763         phba->last_completion_time = jiffies;
7764
7765         /* start eq_delay heartbeat */
7766         if (phba->cfg_auto_imax)
7767                 queue_delayed_work(phba->wq, &phba->eq_delay_work,
7768                                    msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
7769
7770         /* Start error attention (ERATT) polling timer */
7771         mod_timer(&phba->eratt_poll,
7772                   jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
7773
7774         /* Enable PCIe device Advanced Error Reporting (AER) if configured */
7775         if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
7776                 rc = pci_enable_pcie_error_reporting(phba->pcidev);
7777                 if (!rc) {
7778                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7779                                         "2829 This device supports "
7780                                         "Advanced Error Reporting (AER)\n");
7781                         spin_lock_irq(&phba->hbalock);
7782                         phba->hba_flag |= HBA_AER_ENABLED;
7783                         spin_unlock_irq(&phba->hbalock);
7784                 } else {
7785                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
7786                                         "2830 This device does not support "
7787                                         "Advanced Error Reporting (AER)\n");
7788                         phba->cfg_aer_support = 0;
7789                 }
7790                 rc = 0;
7791         }
7792
7793         /*
7794          * The port is ready, set the host's link state to LINK_DOWN
7795          * in preparation for link interrupts.
7796          */
7797         spin_lock_irq(&phba->hbalock);
7798         phba->link_state = LPFC_LINK_DOWN;
7799
7800         /* Check if physical ports are trunked */
7801         if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
7802                 phba->trunk_link.link0.state = LPFC_LINK_DOWN;
7803         if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
7804                 phba->trunk_link.link1.state = LPFC_LINK_DOWN;
7805         if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
7806                 phba->trunk_link.link2.state = LPFC_LINK_DOWN;
7807         if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
7808                 phba->trunk_link.link3.state = LPFC_LINK_DOWN;
7809         spin_unlock_irq(&phba->hbalock);
7810
7811         /* Arm the CQs and then EQs on device */
7812         lpfc_sli4_arm_cqeq_intr(phba);
7813
7814         /* Indicate device interrupt mode */
7815         phba->sli4_hba.intr_enable = 1;
7816
7817         if (!(phba->hba_flag & HBA_FCOE_MODE) &&
7818             (phba->hba_flag & LINK_DISABLED)) {
7819                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
7820                                 "3103 Adapter Link is disabled.\n");
7821                 lpfc_down_link(phba, mboxq);
7822                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7823                 if (rc != MBX_SUCCESS) {
7824                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_SLI,
7825                                         "3104 Adapter failed to issue "
7826                                         "DOWN_LINK mbox cmd, rc:x%x\n", rc);
7827                         goto out_io_buff_free;
7828                 }
7829         } else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
7830                 /* don't perform init_link on SLI4 FC port loopback test */
7831                 if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
7832                         rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
7833                         if (rc)
7834                                 goto out_io_buff_free;
7835                 }
7836         }
7837         mempool_free(mboxq, phba->mbox_mem_pool);
7838         return rc;
7839 out_io_buff_free:
7840         /* Free allocated IO Buffers */
7841         lpfc_io_free(phba);
7842 out_unset_queue:
7843         /* Unset all the queues set up in this routine when error out */
7844         lpfc_sli4_queue_unset(phba);
7845 out_destroy_queue:
7846         lpfc_free_iocb_list(phba);
7847         lpfc_sli4_queue_destroy(phba);
7848 out_stop_timers:
7849         lpfc_stop_hba_timers(phba);
7850 out_free_mbox:
7851         mempool_free(mboxq, phba->mbox_mem_pool);
7852         return rc;
7853 }
7854
7855 /**
7856  * lpfc_mbox_timeout - Timeout call back function for mbox timer
7857  * @ptr: context object - pointer to hba structure.
7858  *
7859  * This is the callback function for mailbox timer. The mailbox
7860  * timer is armed when a new mailbox command is issued and the timer
7861  * is deleted when the mailbox complete. The function is called by
7862  * the kernel timer code when a mailbox does not complete within
7863  * expected time. This function wakes up the worker thread to
7864  * process the mailbox timeout and returns. All the processing is
7865  * done by the worker thread function lpfc_mbox_timeout_handler.
7866  **/
7867 void
7868 lpfc_mbox_timeout(struct timer_list *t)
7869 {
7870         struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
7871         unsigned long iflag;
7872         uint32_t tmo_posted;
7873
7874         spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
7875         tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
7876         if (!tmo_posted)
7877                 phba->pport->work_port_events |= WORKER_MBOX_TMO;
7878         spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
7879
7880         if (!tmo_posted)
7881                 lpfc_worker_wake_up(phba);
7882         return;
7883 }
7884
7885 /**
7886  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
7887  *                                    are pending
7888  * @phba: Pointer to HBA context object.
7889  *
7890  * This function checks if any mailbox completions are present on the mailbox
7891  * completion queue.
7892  **/
7893 static bool
7894 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
7895 {
7896
7897         uint32_t idx;
7898         struct lpfc_queue *mcq;
7899         struct lpfc_mcqe *mcqe;
7900         bool pending_completions = false;
7901         uint8_t qe_valid;
7902
7903         if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
7904                 return false;
7905
7906         /* Check for completions on mailbox completion queue */
7907
7908         mcq = phba->sli4_hba.mbx_cq;
7909         idx = mcq->hba_index;
7910         qe_valid = mcq->qe_valid;
7911         while (bf_get_le32(lpfc_cqe_valid,
7912                (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
7913                 mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
7914                 if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
7915                     (!bf_get_le32(lpfc_trailer_async, mcqe))) {
7916                         pending_completions = true;
7917                         break;
7918                 }
7919                 idx = (idx + 1) % mcq->entry_count;
7920                 if (mcq->hba_index == idx)
7921                         break;
7922
7923                 /* if the index wrapped around, toggle the valid bit */
7924                 if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
7925                         qe_valid = (qe_valid) ? 0 : 1;
7926         }
7927         return pending_completions;
7928
7929 }
7930
7931 /**
7932  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
7933  *                                            that were missed.
7934  * @phba: Pointer to HBA context object.
7935  *
7936  * For sli4, it is possible to miss an interrupt. As such mbox completions
7937  * maybe missed causing erroneous mailbox timeouts to occur. This function
7938  * checks to see if mbox completions are on the mailbox completion queue
7939  * and will process all the completions associated with the eq for the
7940  * mailbox completion queue.
7941  **/
7942 static bool
7943 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
7944 {
7945         struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
7946         uint32_t eqidx;
7947         struct lpfc_queue *fpeq = NULL;
7948         struct lpfc_queue *eq;
7949         bool mbox_pending;
7950
7951         if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
7952                 return false;
7953
7954         /* Find the EQ associated with the mbox CQ */
7955         if (sli4_hba->hdwq) {
7956                 for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
7957                         eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
7958                         if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
7959                                 fpeq = eq;
7960                                 break;
7961                         }
7962                 }
7963         }
7964         if (!fpeq)
7965                 return false;
7966
7967         /* Turn off interrupts from this EQ */
7968
7969         sli4_hba->sli4_eq_clr_intr(fpeq);
7970
7971         /* Check to see if a mbox completion is pending */
7972
7973         mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
7974
7975         /*
7976          * If a mbox completion is pending, process all the events on EQ
7977          * associated with the mbox completion queue (this could include
7978          * mailbox commands, async events, els commands, receive queue data
7979          * and fcp commands)
7980          */
7981
7982         if (mbox_pending)
7983                 /* process and rearm the EQ */
7984                 lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
7985         else
7986                 /* Always clear and re-arm the EQ */
7987                 sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
7988
7989         return mbox_pending;
7990
7991 }
7992
7993 /**
7994  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
7995  * @phba: Pointer to HBA context object.
7996  *
7997  * This function is called from worker thread when a mailbox command times out.
7998  * The caller is not required to hold any locks. This function will reset the
7999  * HBA and recover all the pending commands.
8000  **/
8001 void
8002 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
8003 {
8004         LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
8005         MAILBOX_t *mb = NULL;
8006
8007         struct lpfc_sli *psli = &phba->sli;
8008
8009         /* If the mailbox completed, process the completion and return */
8010         if (lpfc_sli4_process_missed_mbox_completions(phba))
8011                 return;
8012
8013         if (pmbox != NULL)
8014                 mb = &pmbox->u.mb;
8015         /* Check the pmbox pointer first.  There is a race condition
8016          * between the mbox timeout handler getting executed in the
8017          * worklist and the mailbox actually completing. When this
8018          * race condition occurs, the mbox_active will be NULL.
8019          */
8020         spin_lock_irq(&phba->hbalock);
8021         if (pmbox == NULL) {
8022                 lpfc_printf_log(phba, KERN_WARNING,
8023                                 LOG_MBOX | LOG_SLI,
8024                                 "0353 Active Mailbox cleared - mailbox timeout "
8025                                 "exiting\n");
8026                 spin_unlock_irq(&phba->hbalock);
8027                 return;
8028         }
8029
8030         /* Mbox cmd <mbxCommand> timeout */
8031         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8032                         "0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
8033                         mb->mbxCommand,
8034                         phba->pport->port_state,
8035                         phba->sli.sli_flag,
8036                         phba->sli.mbox_active);
8037         spin_unlock_irq(&phba->hbalock);
8038
8039         /* Setting state unknown so lpfc_sli_abort_iocb_ring
8040          * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
8041          * it to fail all outstanding SCSI IO.
8042          */
8043         spin_lock_irq(&phba->pport->work_port_lock);
8044         phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
8045         spin_unlock_irq(&phba->pport->work_port_lock);
8046         spin_lock_irq(&phba->hbalock);
8047         phba->link_state = LPFC_LINK_UNKNOWN;
8048         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
8049         spin_unlock_irq(&phba->hbalock);
8050
8051         lpfc_sli_abort_fcp_rings(phba);
8052
8053         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8054                         "0345 Resetting board due to mailbox timeout\n");
8055
8056         /* Reset the HBA device */
8057         lpfc_reset_hba(phba);
8058 }
8059
8060 /**
8061  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
8062  * @phba: Pointer to HBA context object.
8063  * @pmbox: Pointer to mailbox object.
8064  * @flag: Flag indicating how the mailbox need to be processed.
8065  *
8066  * This function is called by discovery code and HBA management code
8067  * to submit a mailbox command to firmware with SLI-3 interface spec. This
8068  * function gets the hbalock to protect the data structures.
8069  * The mailbox command can be submitted in polling mode, in which case
8070  * this function will wait in a polling loop for the completion of the
8071  * mailbox.
8072  * If the mailbox is submitted in no_wait mode (not polling) the
8073  * function will submit the command and returns immediately without waiting
8074  * for the mailbox completion. The no_wait is supported only when HBA
8075  * is in SLI2/SLI3 mode - interrupts are enabled.
8076  * The SLI interface allows only one mailbox pending at a time. If the
8077  * mailbox is issued in polling mode and there is already a mailbox
8078  * pending, then the function will return an error. If the mailbox is issued
8079  * in NO_WAIT mode and there is a mailbox pending already, the function
8080  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
8081  * The sli layer owns the mailbox object until the completion of mailbox
8082  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
8083  * return codes the caller owns the mailbox command after the return of
8084  * the function.
8085  **/
8086 static int
8087 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
8088                        uint32_t flag)
8089 {
8090         MAILBOX_t *mbx;
8091         struct lpfc_sli *psli = &phba->sli;
8092         uint32_t status, evtctr;
8093         uint32_t ha_copy, hc_copy;
8094         int i;
8095         unsigned long timeout;
8096         unsigned long drvr_flag = 0;
8097         uint32_t word0, ldata;
8098         void __iomem *to_slim;
8099         int processing_queue = 0;
8100
8101         spin_lock_irqsave(&phba->hbalock, drvr_flag);
8102         if (!pmbox) {
8103                 phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8104                 /* processing mbox queue from intr_handler */
8105                 if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8106                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8107                         return MBX_SUCCESS;
8108                 }
8109                 processing_queue = 1;
8110                 pmbox = lpfc_mbox_get(phba);
8111                 if (!pmbox) {
8112                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8113                         return MBX_SUCCESS;
8114                 }
8115         }
8116
8117         if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
8118                 pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
8119                 if(!pmbox->vport) {
8120                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8121                         lpfc_printf_log(phba, KERN_ERR,
8122                                         LOG_MBOX | LOG_VPORT,
8123                                         "1806 Mbox x%x failed. No vport\n",
8124                                         pmbox->u.mb.mbxCommand);
8125                         dump_stack();
8126                         goto out_not_finished;
8127                 }
8128         }
8129
8130         /* If the PCI channel is in offline state, do not post mbox. */
8131         if (unlikely(pci_channel_offline(phba->pcidev))) {
8132                 spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8133                 goto out_not_finished;
8134         }
8135
8136         /* If HBA has a deferred error attention, fail the iocb. */
8137         if (unlikely(phba->hba_flag & DEFER_ERATT)) {
8138                 spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8139                 goto out_not_finished;
8140         }
8141
8142         psli = &phba->sli;
8143
8144         mbx = &pmbox->u.mb;
8145         status = MBX_SUCCESS;
8146
8147         if (phba->link_state == LPFC_HBA_ERROR) {
8148                 spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8149
8150                 /* Mbox command <mbxCommand> cannot issue */
8151                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8152                                 "(%d):0311 Mailbox command x%x cannot "
8153                                 "issue Data: x%x x%x\n",
8154                                 pmbox->vport ? pmbox->vport->vpi : 0,
8155                                 pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8156                 goto out_not_finished;
8157         }
8158
8159         if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
8160                 if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
8161                         !(hc_copy & HC_MBINT_ENA)) {
8162                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8163                         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8164                                 "(%d):2528 Mailbox command x%x cannot "
8165                                 "issue Data: x%x x%x\n",
8166                                 pmbox->vport ? pmbox->vport->vpi : 0,
8167                                 pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
8168                         goto out_not_finished;
8169                 }
8170         }
8171
8172         if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8173                 /* Polling for a mbox command when another one is already active
8174                  * is not allowed in SLI. Also, the driver must have established
8175                  * SLI2 mode to queue and process multiple mbox commands.
8176                  */
8177
8178                 if (flag & MBX_POLL) {
8179                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8180
8181                         /* Mbox command <mbxCommand> cannot issue */
8182                         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8183                                         "(%d):2529 Mailbox command x%x "
8184                                         "cannot issue Data: x%x x%x\n",
8185                                         pmbox->vport ? pmbox->vport->vpi : 0,
8186                                         pmbox->u.mb.mbxCommand,
8187                                         psli->sli_flag, flag);
8188                         goto out_not_finished;
8189                 }
8190
8191                 if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
8192                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8193                         /* Mbox command <mbxCommand> cannot issue */
8194                         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8195                                         "(%d):2530 Mailbox command x%x "
8196                                         "cannot issue Data: x%x x%x\n",
8197                                         pmbox->vport ? pmbox->vport->vpi : 0,
8198                                         pmbox->u.mb.mbxCommand,
8199                                         psli->sli_flag, flag);
8200                         goto out_not_finished;
8201                 }
8202
8203                 /* Another mailbox command is still being processed, queue this
8204                  * command to be processed later.
8205                  */
8206                 lpfc_mbox_put(phba, pmbox);
8207
8208                 /* Mbox cmd issue - BUSY */
8209                 lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8210                                 "(%d):0308 Mbox cmd issue - BUSY Data: "
8211                                 "x%x x%x x%x x%x\n",
8212                                 pmbox->vport ? pmbox->vport->vpi : 0xffffff,
8213                                 mbx->mbxCommand,
8214                                 phba->pport ? phba->pport->port_state : 0xff,
8215                                 psli->sli_flag, flag);
8216
8217                 psli->slistat.mbox_busy++;
8218                 spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8219
8220                 if (pmbox->vport) {
8221                         lpfc_debugfs_disc_trc(pmbox->vport,
8222                                 LPFC_DISC_TRC_MBOX_VPORT,
8223                                 "MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
8224                                 (uint32_t)mbx->mbxCommand,
8225                                 mbx->un.varWords[0], mbx->un.varWords[1]);
8226                 }
8227                 else {
8228                         lpfc_debugfs_disc_trc(phba->pport,
8229                                 LPFC_DISC_TRC_MBOX,
8230                                 "MBOX Bsy:        cmd:x%x mb:x%x x%x",
8231                                 (uint32_t)mbx->mbxCommand,
8232                                 mbx->un.varWords[0], mbx->un.varWords[1]);
8233                 }
8234
8235                 return MBX_BUSY;
8236         }
8237
8238         psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8239
8240         /* If we are not polling, we MUST be in SLI2 mode */
8241         if (flag != MBX_POLL) {
8242                 if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
8243                     (mbx->mbxCommand != MBX_KILL_BOARD)) {
8244                         psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8245                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8246                         /* Mbox command <mbxCommand> cannot issue */
8247                         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8248                                         "(%d):2531 Mailbox command x%x "
8249                                         "cannot issue Data: x%x x%x\n",
8250                                         pmbox->vport ? pmbox->vport->vpi : 0,
8251                                         pmbox->u.mb.mbxCommand,
8252                                         psli->sli_flag, flag);
8253                         goto out_not_finished;
8254                 }
8255                 /* timeout active mbox command */
8256                 timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8257                                            1000);
8258                 mod_timer(&psli->mbox_tmo, jiffies + timeout);
8259         }
8260
8261         /* Mailbox cmd <cmd> issue */
8262         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8263                         "(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
8264                         "x%x\n",
8265                         pmbox->vport ? pmbox->vport->vpi : 0,
8266                         mbx->mbxCommand,
8267                         phba->pport ? phba->pport->port_state : 0xff,
8268                         psli->sli_flag, flag);
8269
8270         if (mbx->mbxCommand != MBX_HEARTBEAT) {
8271                 if (pmbox->vport) {
8272                         lpfc_debugfs_disc_trc(pmbox->vport,
8273                                 LPFC_DISC_TRC_MBOX_VPORT,
8274                                 "MBOX Send vport: cmd:x%x mb:x%x x%x",
8275                                 (uint32_t)mbx->mbxCommand,
8276                                 mbx->un.varWords[0], mbx->un.varWords[1]);
8277                 }
8278                 else {
8279                         lpfc_debugfs_disc_trc(phba->pport,
8280                                 LPFC_DISC_TRC_MBOX,
8281                                 "MBOX Send:       cmd:x%x mb:x%x x%x",
8282                                 (uint32_t)mbx->mbxCommand,
8283                                 mbx->un.varWords[0], mbx->un.varWords[1]);
8284                 }
8285         }
8286
8287         psli->slistat.mbox_cmd++;
8288         evtctr = psli->slistat.mbox_event;
8289
8290         /* next set own bit for the adapter and copy over command word */
8291         mbx->mbxOwner = OWN_CHIP;
8292
8293         if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8294                 /* Populate mbox extension offset word. */
8295                 if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
8296                         *(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8297                                 = (uint8_t *)phba->mbox_ext
8298                                   - (uint8_t *)phba->mbox;
8299                 }
8300
8301                 /* Copy the mailbox extension data */
8302                 if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
8303                         lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
8304                                               (uint8_t *)phba->mbox_ext,
8305                                               pmbox->in_ext_byte_len);
8306                 }
8307                 /* Copy command data to host SLIM area */
8308                 lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
8309         } else {
8310                 /* Populate mbox extension offset word. */
8311                 if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
8312                         *(((uint32_t *)mbx) + pmbox->mbox_offset_word)
8313                                 = MAILBOX_HBA_EXT_OFFSET;
8314
8315                 /* Copy the mailbox extension data */
8316                 if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
8317                         lpfc_memcpy_to_slim(phba->MBslimaddr +
8318                                 MAILBOX_HBA_EXT_OFFSET,
8319                                 pmbox->ctx_buf, pmbox->in_ext_byte_len);
8320
8321                 if (mbx->mbxCommand == MBX_CONFIG_PORT)
8322                         /* copy command data into host mbox for cmpl */
8323                         lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
8324                                               MAILBOX_CMD_SIZE);
8325
8326                 /* First copy mbox command data to HBA SLIM, skip past first
8327                    word */
8328                 to_slim = phba->MBslimaddr + sizeof (uint32_t);
8329                 lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
8330                             MAILBOX_CMD_SIZE - sizeof (uint32_t));
8331
8332                 /* Next copy over first word, with mbxOwner set */
8333                 ldata = *((uint32_t *)mbx);
8334                 to_slim = phba->MBslimaddr;
8335                 writel(ldata, to_slim);
8336                 readl(to_slim); /* flush */
8337
8338                 if (mbx->mbxCommand == MBX_CONFIG_PORT)
8339                         /* switch over to host mailbox */
8340                         psli->sli_flag |= LPFC_SLI_ACTIVE;
8341         }
8342
8343         wmb();
8344
8345         switch (flag) {
8346         case MBX_NOWAIT:
8347                 /* Set up reference to mailbox command */
8348                 psli->mbox_active = pmbox;
8349                 /* Interrupt board to do it */
8350                 writel(CA_MBATT, phba->CAregaddr);
8351                 readl(phba->CAregaddr); /* flush */
8352                 /* Don't wait for it to finish, just return */
8353                 break;
8354
8355         case MBX_POLL:
8356                 /* Set up null reference to mailbox command */
8357                 psli->mbox_active = NULL;
8358                 /* Interrupt board to do it */
8359                 writel(CA_MBATT, phba->CAregaddr);
8360                 readl(phba->CAregaddr); /* flush */
8361
8362                 if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8363                         /* First read mbox status word */
8364                         word0 = *((uint32_t *)phba->mbox);
8365                         word0 = le32_to_cpu(word0);
8366                 } else {
8367                         /* First read mbox status word */
8368                         if (lpfc_readl(phba->MBslimaddr, &word0)) {
8369                                 spin_unlock_irqrestore(&phba->hbalock,
8370                                                        drvr_flag);
8371                                 goto out_not_finished;
8372                         }
8373                 }
8374
8375                 /* Read the HBA Host Attention Register */
8376                 if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8377                         spin_unlock_irqrestore(&phba->hbalock,
8378                                                        drvr_flag);
8379                         goto out_not_finished;
8380                 }
8381                 timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
8382                                                         1000) + jiffies;
8383                 i = 0;
8384                 /* Wait for command to complete */
8385                 while (((word0 & OWN_CHIP) == OWN_CHIP) ||
8386                        (!(ha_copy & HA_MBATT) &&
8387                         (phba->link_state > LPFC_WARM_START))) {
8388                         if (time_after(jiffies, timeout)) {
8389                                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8390                                 spin_unlock_irqrestore(&phba->hbalock,
8391                                                        drvr_flag);
8392                                 goto out_not_finished;
8393                         }
8394
8395                         /* Check if we took a mbox interrupt while we were
8396                            polling */
8397                         if (((word0 & OWN_CHIP) != OWN_CHIP)
8398                             && (evtctr != psli->slistat.mbox_event))
8399                                 break;
8400
8401                         if (i++ > 10) {
8402                                 spin_unlock_irqrestore(&phba->hbalock,
8403                                                        drvr_flag);
8404                                 msleep(1);
8405                                 spin_lock_irqsave(&phba->hbalock, drvr_flag);
8406                         }
8407
8408                         if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8409                                 /* First copy command data */
8410                                 word0 = *((uint32_t *)phba->mbox);
8411                                 word0 = le32_to_cpu(word0);
8412                                 if (mbx->mbxCommand == MBX_CONFIG_PORT) {
8413                                         MAILBOX_t *slimmb;
8414                                         uint32_t slimword0;
8415                                         /* Check real SLIM for any errors */
8416                                         slimword0 = readl(phba->MBslimaddr);
8417                                         slimmb = (MAILBOX_t *) & slimword0;
8418                                         if (((slimword0 & OWN_CHIP) != OWN_CHIP)
8419                                             && slimmb->mbxStatus) {
8420                                                 psli->sli_flag &=
8421                                                     ~LPFC_SLI_ACTIVE;
8422                                                 word0 = slimword0;
8423                                         }
8424                                 }
8425                         } else {
8426                                 /* First copy command data */
8427                                 word0 = readl(phba->MBslimaddr);
8428                         }
8429                         /* Read the HBA Host Attention Register */
8430                         if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
8431                                 spin_unlock_irqrestore(&phba->hbalock,
8432                                                        drvr_flag);
8433                                 goto out_not_finished;
8434                         }
8435                 }
8436
8437                 if (psli->sli_flag & LPFC_SLI_ACTIVE) {
8438                         /* copy results back to user */
8439                         lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
8440                                                 MAILBOX_CMD_SIZE);
8441                         /* Copy the mailbox extension data */
8442                         if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8443                                 lpfc_sli_pcimem_bcopy(phba->mbox_ext,
8444                                                       pmbox->ctx_buf,
8445                                                       pmbox->out_ext_byte_len);
8446                         }
8447                 } else {
8448                         /* First copy command data */
8449                         lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
8450                                                 MAILBOX_CMD_SIZE);
8451                         /* Copy the mailbox extension data */
8452                         if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
8453                                 lpfc_memcpy_from_slim(
8454                                         pmbox->ctx_buf,
8455                                         phba->MBslimaddr +
8456                                         MAILBOX_HBA_EXT_OFFSET,
8457                                         pmbox->out_ext_byte_len);
8458                         }
8459                 }
8460
8461                 writel(HA_MBATT, phba->HAregaddr);
8462                 readl(phba->HAregaddr); /* flush */
8463
8464                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8465                 status = mbx->mbxStatus;
8466         }
8467
8468         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
8469         return status;
8470
8471 out_not_finished:
8472         if (processing_queue) {
8473                 pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
8474                 lpfc_mbox_cmpl_put(phba, pmbox);
8475         }
8476         return MBX_NOT_FINISHED;
8477 }
8478
8479 /**
8480  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
8481  * @phba: Pointer to HBA context object.
8482  *
8483  * The function blocks the posting of SLI4 asynchronous mailbox commands from
8484  * the driver internal pending mailbox queue. It will then try to wait out the
8485  * possible outstanding mailbox command before return.
8486  *
8487  * Returns:
8488  *      0 - the outstanding mailbox command completed; otherwise, the wait for
8489  *      the outstanding mailbox command timed out.
8490  **/
8491 static int
8492 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
8493 {
8494         struct lpfc_sli *psli = &phba->sli;
8495         int rc = 0;
8496         unsigned long timeout = 0;
8497
8498         /* Mark the asynchronous mailbox command posting as blocked */
8499         spin_lock_irq(&phba->hbalock);
8500         psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
8501         /* Determine how long we might wait for the active mailbox
8502          * command to be gracefully completed by firmware.
8503          */
8504         if (phba->sli.mbox_active)
8505                 timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
8506                                                 phba->sli.mbox_active) *
8507                                                 1000) + jiffies;
8508         spin_unlock_irq(&phba->hbalock);
8509
8510         /* Make sure the mailbox is really active */
8511         if (timeout)
8512                 lpfc_sli4_process_missed_mbox_completions(phba);
8513
8514         /* Wait for the outstnading mailbox command to complete */
8515         while (phba->sli.mbox_active) {
8516                 /* Check active mailbox complete status every 2ms */
8517                 msleep(2);
8518                 if (time_after(jiffies, timeout)) {
8519                         /* Timeout, marked the outstanding cmd not complete */
8520                         rc = 1;
8521                         break;
8522                 }
8523         }
8524
8525         /* Can not cleanly block async mailbox command, fails it */
8526         if (rc) {
8527                 spin_lock_irq(&phba->hbalock);
8528                 psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8529                 spin_unlock_irq(&phba->hbalock);
8530         }
8531         return rc;
8532 }
8533
8534 /**
8535  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
8536  * @phba: Pointer to HBA context object.
8537  *
8538  * The function unblocks and resume posting of SLI4 asynchronous mailbox
8539  * commands from the driver internal pending mailbox queue. It makes sure
8540  * that there is no outstanding mailbox command before resuming posting
8541  * asynchronous mailbox commands. If, for any reason, there is outstanding
8542  * mailbox command, it will try to wait it out before resuming asynchronous
8543  * mailbox command posting.
8544  **/
8545 static void
8546 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
8547 {
8548         struct lpfc_sli *psli = &phba->sli;
8549
8550         spin_lock_irq(&phba->hbalock);
8551         if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8552                 /* Asynchronous mailbox posting is not blocked, do nothing */
8553                 spin_unlock_irq(&phba->hbalock);
8554                 return;
8555         }
8556
8557         /* Outstanding synchronous mailbox command is guaranteed to be done,
8558          * successful or timeout, after timing-out the outstanding mailbox
8559          * command shall always be removed, so just unblock posting async
8560          * mailbox command and resume
8561          */
8562         psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8563         spin_unlock_irq(&phba->hbalock);
8564
8565         /* wake up worker thread to post asynchronous mailbox command */
8566         lpfc_worker_wake_up(phba);
8567 }
8568
8569 /**
8570  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
8571  * @phba: Pointer to HBA context object.
8572  * @mboxq: Pointer to mailbox object.
8573  *
8574  * The function waits for the bootstrap mailbox register ready bit from
8575  * port for twice the regular mailbox command timeout value.
8576  *
8577  *      0 - no timeout on waiting for bootstrap mailbox register ready.
8578  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
8579  **/
8580 static int
8581 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8582 {
8583         uint32_t db_ready;
8584         unsigned long timeout;
8585         struct lpfc_register bmbx_reg;
8586
8587         timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
8588                                    * 1000) + jiffies;
8589
8590         do {
8591                 bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
8592                 db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
8593                 if (!db_ready)
8594                         mdelay(2);
8595
8596                 if (time_after(jiffies, timeout))
8597                         return MBXERR_ERROR;
8598         } while (!db_ready);
8599
8600         return 0;
8601 }
8602
8603 /**
8604  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
8605  * @phba: Pointer to HBA context object.
8606  * @mboxq: Pointer to mailbox object.
8607  *
8608  * The function posts a mailbox to the port.  The mailbox is expected
8609  * to be comletely filled in and ready for the port to operate on it.
8610  * This routine executes a synchronous completion operation on the
8611  * mailbox by polling for its completion.
8612  *
8613  * The caller must not be holding any locks when calling this routine.
8614  *
8615  * Returns:
8616  *      MBX_SUCCESS - mailbox posted successfully
8617  *      Any of the MBX error values.
8618  **/
8619 static int
8620 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
8621 {
8622         int rc = MBX_SUCCESS;
8623         unsigned long iflag;
8624         uint32_t mcqe_status;
8625         uint32_t mbx_cmnd;
8626         struct lpfc_sli *psli = &phba->sli;
8627         struct lpfc_mqe *mb = &mboxq->u.mqe;
8628         struct lpfc_bmbx_create *mbox_rgn;
8629         struct dma_address *dma_address;
8630
8631         /*
8632          * Only one mailbox can be active to the bootstrap mailbox region
8633          * at a time and there is no queueing provided.
8634          */
8635         spin_lock_irqsave(&phba->hbalock, iflag);
8636         if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8637                 spin_unlock_irqrestore(&phba->hbalock, iflag);
8638                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8639                                 "(%d):2532 Mailbox command x%x (x%x/x%x) "
8640                                 "cannot issue Data: x%x x%x\n",
8641                                 mboxq->vport ? mboxq->vport->vpi : 0,
8642                                 mboxq->u.mb.mbxCommand,
8643                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8644                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8645                                 psli->sli_flag, MBX_POLL);
8646                 return MBXERR_ERROR;
8647         }
8648         /* The server grabs the token and owns it until release */
8649         psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8650         phba->sli.mbox_active = mboxq;
8651         spin_unlock_irqrestore(&phba->hbalock, iflag);
8652
8653         /* wait for bootstrap mbox register for readyness */
8654         rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8655         if (rc)
8656                 goto exit;
8657         /*
8658          * Initialize the bootstrap memory region to avoid stale data areas
8659          * in the mailbox post.  Then copy the caller's mailbox contents to
8660          * the bmbx mailbox region.
8661          */
8662         mbx_cmnd = bf_get(lpfc_mqe_command, mb);
8663         memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
8664         lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
8665                                sizeof(struct lpfc_mqe));
8666
8667         /* Post the high mailbox dma address to the port and wait for ready. */
8668         dma_address = &phba->sli4_hba.bmbx.dma_address;
8669         writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
8670
8671         /* wait for bootstrap mbox register for hi-address write done */
8672         rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8673         if (rc)
8674                 goto exit;
8675
8676         /* Post the low mailbox dma address to the port. */
8677         writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
8678
8679         /* wait for bootstrap mbox register for low address write done */
8680         rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
8681         if (rc)
8682                 goto exit;
8683
8684         /*
8685          * Read the CQ to ensure the mailbox has completed.
8686          * If so, update the mailbox status so that the upper layers
8687          * can complete the request normally.
8688          */
8689         lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
8690                                sizeof(struct lpfc_mqe));
8691         mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
8692         lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
8693                                sizeof(struct lpfc_mcqe));
8694         mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
8695         /*
8696          * When the CQE status indicates a failure and the mailbox status
8697          * indicates success then copy the CQE status into the mailbox status
8698          * (and prefix it with x4000).
8699          */
8700         if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
8701                 if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
8702                         bf_set(lpfc_mqe_status, mb,
8703                                (LPFC_MBX_ERROR_RANGE | mcqe_status));
8704                 rc = MBXERR_ERROR;
8705         } else
8706                 lpfc_sli4_swap_str(phba, mboxq);
8707
8708         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8709                         "(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
8710                         "Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
8711                         " x%x x%x CQ: x%x x%x x%x x%x\n",
8712                         mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
8713                         lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8714                         lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8715                         bf_get(lpfc_mqe_status, mb),
8716                         mb->un.mb_words[0], mb->un.mb_words[1],
8717                         mb->un.mb_words[2], mb->un.mb_words[3],
8718                         mb->un.mb_words[4], mb->un.mb_words[5],
8719                         mb->un.mb_words[6], mb->un.mb_words[7],
8720                         mb->un.mb_words[8], mb->un.mb_words[9],
8721                         mb->un.mb_words[10], mb->un.mb_words[11],
8722                         mb->un.mb_words[12], mboxq->mcqe.word0,
8723                         mboxq->mcqe.mcqe_tag0,  mboxq->mcqe.mcqe_tag1,
8724                         mboxq->mcqe.trailer);
8725 exit:
8726         /* We are holding the token, no needed for lock when release */
8727         spin_lock_irqsave(&phba->hbalock, iflag);
8728         psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8729         phba->sli.mbox_active = NULL;
8730         spin_unlock_irqrestore(&phba->hbalock, iflag);
8731         return rc;
8732 }
8733
8734 /**
8735  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
8736  * @phba: Pointer to HBA context object.
8737  * @pmbox: Pointer to mailbox object.
8738  * @flag: Flag indicating how the mailbox need to be processed.
8739  *
8740  * This function is called by discovery code and HBA management code to submit
8741  * a mailbox command to firmware with SLI-4 interface spec.
8742  *
8743  * Return codes the caller owns the mailbox command after the return of the
8744  * function.
8745  **/
8746 static int
8747 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
8748                        uint32_t flag)
8749 {
8750         struct lpfc_sli *psli = &phba->sli;
8751         unsigned long iflags;
8752         int rc;
8753
8754         /* dump from issue mailbox command if setup */
8755         lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
8756
8757         rc = lpfc_mbox_dev_check(phba);
8758         if (unlikely(rc)) {
8759                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8760                                 "(%d):2544 Mailbox command x%x (x%x/x%x) "
8761                                 "cannot issue Data: x%x x%x\n",
8762                                 mboxq->vport ? mboxq->vport->vpi : 0,
8763                                 mboxq->u.mb.mbxCommand,
8764                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8765                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8766                                 psli->sli_flag, flag);
8767                 goto out_not_finished;
8768         }
8769
8770         /* Detect polling mode and jump to a handler */
8771         if (!phba->sli4_hba.intr_enable) {
8772                 if (flag == MBX_POLL)
8773                         rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
8774                 else
8775                         rc = -EIO;
8776                 if (rc != MBX_SUCCESS)
8777                         lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8778                                         "(%d):2541 Mailbox command x%x "
8779                                         "(x%x/x%x) failure: "
8780                                         "mqe_sta: x%x mcqe_sta: x%x/x%x "
8781                                         "Data: x%x x%x\n,",
8782                                         mboxq->vport ? mboxq->vport->vpi : 0,
8783                                         mboxq->u.mb.mbxCommand,
8784                                         lpfc_sli_config_mbox_subsys_get(phba,
8785                                                                         mboxq),
8786                                         lpfc_sli_config_mbox_opcode_get(phba,
8787                                                                         mboxq),
8788                                         bf_get(lpfc_mqe_status, &mboxq->u.mqe),
8789                                         bf_get(lpfc_mcqe_status, &mboxq->mcqe),
8790                                         bf_get(lpfc_mcqe_ext_status,
8791                                                &mboxq->mcqe),
8792                                         psli->sli_flag, flag);
8793                 return rc;
8794         } else if (flag == MBX_POLL) {
8795                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8796                                 "(%d):2542 Try to issue mailbox command "
8797                                 "x%x (x%x/x%x) synchronously ahead of async "
8798                                 "mailbox command queue: x%x x%x\n",
8799                                 mboxq->vport ? mboxq->vport->vpi : 0,
8800                                 mboxq->u.mb.mbxCommand,
8801                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8802                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8803                                 psli->sli_flag, flag);
8804                 /* Try to block the asynchronous mailbox posting */
8805                 rc = lpfc_sli4_async_mbox_block(phba);
8806                 if (!rc) {
8807                         /* Successfully blocked, now issue sync mbox cmd */
8808                         rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
8809                         if (rc != MBX_SUCCESS)
8810                                 lpfc_printf_log(phba, KERN_WARNING,
8811                                         LOG_MBOX | LOG_SLI,
8812                                         "(%d):2597 Sync Mailbox command "
8813                                         "x%x (x%x/x%x) failure: "
8814                                         "mqe_sta: x%x mcqe_sta: x%x/x%x "
8815                                         "Data: x%x x%x\n,",
8816                                         mboxq->vport ? mboxq->vport->vpi : 0,
8817                                         mboxq->u.mb.mbxCommand,
8818                                         lpfc_sli_config_mbox_subsys_get(phba,
8819                                                                         mboxq),
8820                                         lpfc_sli_config_mbox_opcode_get(phba,
8821                                                                         mboxq),
8822                                         bf_get(lpfc_mqe_status, &mboxq->u.mqe),
8823                                         bf_get(lpfc_mcqe_status, &mboxq->mcqe),
8824                                         bf_get(lpfc_mcqe_ext_status,
8825                                                &mboxq->mcqe),
8826                                         psli->sli_flag, flag);
8827                         /* Unblock the async mailbox posting afterward */
8828                         lpfc_sli4_async_mbox_unblock(phba);
8829                 }
8830                 return rc;
8831         }
8832
8833         /* Now, interrupt mode asynchronous mailbox command */
8834         rc = lpfc_mbox_cmd_check(phba, mboxq);
8835         if (rc) {
8836                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8837                                 "(%d):2543 Mailbox command x%x (x%x/x%x) "
8838                                 "cannot issue Data: x%x x%x\n",
8839                                 mboxq->vport ? mboxq->vport->vpi : 0,
8840                                 mboxq->u.mb.mbxCommand,
8841                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8842                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8843                                 psli->sli_flag, flag);
8844                 goto out_not_finished;
8845         }
8846
8847         /* Put the mailbox command to the driver internal FIFO */
8848         psli->slistat.mbox_busy++;
8849         spin_lock_irqsave(&phba->hbalock, iflags);
8850         lpfc_mbox_put(phba, mboxq);
8851         spin_unlock_irqrestore(&phba->hbalock, iflags);
8852         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8853                         "(%d):0354 Mbox cmd issue - Enqueue Data: "
8854                         "x%x (x%x/x%x) x%x x%x x%x\n",
8855                         mboxq->vport ? mboxq->vport->vpi : 0xffffff,
8856                         bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8857                         lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8858                         lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8859                         phba->pport->port_state,
8860                         psli->sli_flag, MBX_NOWAIT);
8861         /* Wake up worker thread to transport mailbox command from head */
8862         lpfc_worker_wake_up(phba);
8863
8864         return MBX_BUSY;
8865
8866 out_not_finished:
8867         return MBX_NOT_FINISHED;
8868 }
8869
8870 /**
8871  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
8872  * @phba: Pointer to HBA context object.
8873  *
8874  * This function is called by worker thread to send a mailbox command to
8875  * SLI4 HBA firmware.
8876  *
8877  **/
8878 int
8879 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
8880 {
8881         struct lpfc_sli *psli = &phba->sli;
8882         LPFC_MBOXQ_t *mboxq;
8883         int rc = MBX_SUCCESS;
8884         unsigned long iflags;
8885         struct lpfc_mqe *mqe;
8886         uint32_t mbx_cmnd;
8887
8888         /* Check interrupt mode before post async mailbox command */
8889         if (unlikely(!phba->sli4_hba.intr_enable))
8890                 return MBX_NOT_FINISHED;
8891
8892         /* Check for mailbox command service token */
8893         spin_lock_irqsave(&phba->hbalock, iflags);
8894         if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
8895                 spin_unlock_irqrestore(&phba->hbalock, iflags);
8896                 return MBX_NOT_FINISHED;
8897         }
8898         if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
8899                 spin_unlock_irqrestore(&phba->hbalock, iflags);
8900                 return MBX_NOT_FINISHED;
8901         }
8902         if (unlikely(phba->sli.mbox_active)) {
8903                 spin_unlock_irqrestore(&phba->hbalock, iflags);
8904                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8905                                 "0384 There is pending active mailbox cmd\n");
8906                 return MBX_NOT_FINISHED;
8907         }
8908         /* Take the mailbox command service token */
8909         psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
8910
8911         /* Get the next mailbox command from head of queue */
8912         mboxq = lpfc_mbox_get(phba);
8913
8914         /* If no more mailbox command waiting for post, we're done */
8915         if (!mboxq) {
8916                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8917                 spin_unlock_irqrestore(&phba->hbalock, iflags);
8918                 return MBX_SUCCESS;
8919         }
8920         phba->sli.mbox_active = mboxq;
8921         spin_unlock_irqrestore(&phba->hbalock, iflags);
8922
8923         /* Check device readiness for posting mailbox command */
8924         rc = lpfc_mbox_dev_check(phba);
8925         if (unlikely(rc))
8926                 /* Driver clean routine will clean up pending mailbox */
8927                 goto out_not_finished;
8928
8929         /* Prepare the mbox command to be posted */
8930         mqe = &mboxq->u.mqe;
8931         mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
8932
8933         /* Start timer for the mbox_tmo and log some mailbox post messages */
8934         mod_timer(&psli->mbox_tmo, (jiffies +
8935                   msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
8936
8937         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8938                         "(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
8939                         "x%x x%x\n",
8940                         mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
8941                         lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8942                         lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8943                         phba->pport->port_state, psli->sli_flag);
8944
8945         if (mbx_cmnd != MBX_HEARTBEAT) {
8946                 if (mboxq->vport) {
8947                         lpfc_debugfs_disc_trc(mboxq->vport,
8948                                 LPFC_DISC_TRC_MBOX_VPORT,
8949                                 "MBOX Send vport: cmd:x%x mb:x%x x%x",
8950                                 mbx_cmnd, mqe->un.mb_words[0],
8951                                 mqe->un.mb_words[1]);
8952                 } else {
8953                         lpfc_debugfs_disc_trc(phba->pport,
8954                                 LPFC_DISC_TRC_MBOX,
8955                                 "MBOX Send: cmd:x%x mb:x%x x%x",
8956                                 mbx_cmnd, mqe->un.mb_words[0],
8957                                 mqe->un.mb_words[1]);
8958                 }
8959         }
8960         psli->slistat.mbox_cmd++;
8961
8962         /* Post the mailbox command to the port */
8963         rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
8964         if (rc != MBX_SUCCESS) {
8965                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_SLI,
8966                                 "(%d):2533 Mailbox command x%x (x%x/x%x) "
8967                                 "cannot issue Data: x%x x%x\n",
8968                                 mboxq->vport ? mboxq->vport->vpi : 0,
8969                                 mboxq->u.mb.mbxCommand,
8970                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
8971                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
8972                                 psli->sli_flag, MBX_NOWAIT);
8973                 goto out_not_finished;
8974         }
8975
8976         return rc;
8977
8978 out_not_finished:
8979         spin_lock_irqsave(&phba->hbalock, iflags);
8980         if (phba->sli.mbox_active) {
8981                 mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
8982                 __lpfc_mbox_cmpl_put(phba, mboxq);
8983                 /* Release the token */
8984                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
8985                 phba->sli.mbox_active = NULL;
8986         }
8987         spin_unlock_irqrestore(&phba->hbalock, iflags);
8988
8989         return MBX_NOT_FINISHED;
8990 }
8991
8992 /**
8993  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
8994  * @phba: Pointer to HBA context object.
8995  * @pmbox: Pointer to mailbox object.
8996  * @flag: Flag indicating how the mailbox need to be processed.
8997  *
8998  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
8999  * the API jump table function pointer from the lpfc_hba struct.
9000  *
9001  * Return codes the caller owns the mailbox command after the return of the
9002  * function.
9003  **/
9004 int
9005 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
9006 {
9007         return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
9008 }
9009
9010 /**
9011  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
9012  * @phba: The hba struct for which this call is being executed.
9013  * @dev_grp: The HBA PCI-Device group number.
9014  *
9015  * This routine sets up the mbox interface API function jump table in @phba
9016  * struct.
9017  * Returns: 0 - success, -ENODEV - failure.
9018  **/
9019 int
9020 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
9021 {
9022
9023         switch (dev_grp) {
9024         case LPFC_PCI_DEV_LP:
9025                 phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
9026                 phba->lpfc_sli_handle_slow_ring_event =
9027                                 lpfc_sli_handle_slow_ring_event_s3;
9028                 phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
9029                 phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
9030                 phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
9031                 break;
9032         case LPFC_PCI_DEV_OC:
9033                 phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
9034                 phba->lpfc_sli_handle_slow_ring_event =
9035                                 lpfc_sli_handle_slow_ring_event_s4;
9036                 phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
9037                 phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
9038                 phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
9039                 break;
9040         default:
9041                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9042                                 "1420 Invalid HBA PCI-device group: 0x%x\n",
9043                                 dev_grp);
9044                 return -ENODEV;
9045                 break;
9046         }
9047         return 0;
9048 }
9049
9050 /**
9051  * __lpfc_sli_ringtx_put - Add an iocb to the txq
9052  * @phba: Pointer to HBA context object.
9053  * @pring: Pointer to driver SLI ring object.
9054  * @piocb: Pointer to address of newly added command iocb.
9055  *
9056  * This function is called with hbalock held for SLI3 ports or
9057  * the ring lock held for SLI4 ports to add a command
9058  * iocb to the txq when SLI layer cannot submit the command iocb
9059  * to the ring.
9060  **/
9061 void
9062 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9063                     struct lpfc_iocbq *piocb)
9064 {
9065         if (phba->sli_rev == LPFC_SLI_REV4)
9066                 lockdep_assert_held(&pring->ring_lock);
9067         else
9068                 lockdep_assert_held(&phba->hbalock);
9069         /* Insert the caller's iocb in the txq tail for later processing. */
9070         list_add_tail(&piocb->list, &pring->txq);
9071 }
9072
9073 /**
9074  * lpfc_sli_next_iocb - Get the next iocb in the txq
9075  * @phba: Pointer to HBA context object.
9076  * @pring: Pointer to driver SLI ring object.
9077  * @piocb: Pointer to address of newly added command iocb.
9078  *
9079  * This function is called with hbalock held before a new
9080  * iocb is submitted to the firmware. This function checks
9081  * txq to flush the iocbs in txq to Firmware before
9082  * submitting new iocbs to the Firmware.
9083  * If there are iocbs in the txq which need to be submitted
9084  * to firmware, lpfc_sli_next_iocb returns the first element
9085  * of the txq after dequeuing it from txq.
9086  * If there is no iocb in the txq then the function will return
9087  * *piocb and *piocb is set to NULL. Caller needs to check
9088  * *piocb to find if there are more commands in the txq.
9089  **/
9090 static struct lpfc_iocbq *
9091 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
9092                    struct lpfc_iocbq **piocb)
9093 {
9094         struct lpfc_iocbq * nextiocb;
9095
9096         lockdep_assert_held(&phba->hbalock);
9097
9098         nextiocb = lpfc_sli_ringtx_get(phba, pring);
9099         if (!nextiocb) {
9100                 nextiocb = *piocb;
9101                 *piocb = NULL;
9102         }
9103
9104         return nextiocb;
9105 }
9106
9107 /**
9108  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
9109  * @phba: Pointer to HBA context object.
9110  * @ring_number: SLI ring number to issue iocb on.
9111  * @piocb: Pointer to command iocb.
9112  * @flag: Flag indicating if this command can be put into txq.
9113  *
9114  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
9115  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
9116  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
9117  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
9118  * this function allows only iocbs for posting buffers. This function finds
9119  * next available slot in the command ring and posts the command to the
9120  * available slot and writes the port attention register to request HBA start
9121  * processing new iocb. If there is no slot available in the ring and
9122  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
9123  * the function returns IOCB_BUSY.
9124  *
9125  * This function is called with hbalock held. The function will return success
9126  * after it successfully submit the iocb to firmware or after adding to the
9127  * txq.
9128  **/
9129 static int
9130 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
9131                     struct lpfc_iocbq *piocb, uint32_t flag)
9132 {
9133         struct lpfc_iocbq *nextiocb;
9134         IOCB_t *iocb;
9135         struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
9136
9137         lockdep_assert_held(&phba->hbalock);
9138
9139         if (piocb->iocb_cmpl && (!piocb->vport) &&
9140            (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
9141            (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
9142                 lpfc_printf_log(phba, KERN_ERR,
9143                                 LOG_SLI | LOG_VPORT,
9144                                 "1807 IOCB x%x failed. No vport\n",
9145                                 piocb->iocb.ulpCommand);
9146                 dump_stack();
9147                 return IOCB_ERROR;
9148         }
9149
9150
9151         /* If the PCI channel is in offline state, do not post iocbs. */
9152         if (unlikely(pci_channel_offline(phba->pcidev)))
9153                 return IOCB_ERROR;
9154
9155         /* If HBA has a deferred error attention, fail the iocb. */
9156         if (unlikely(phba->hba_flag & DEFER_ERATT))
9157                 return IOCB_ERROR;
9158
9159         /*
9160          * We should never get an IOCB if we are in a < LINK_DOWN state
9161          */
9162         if (unlikely(phba->link_state < LPFC_LINK_DOWN))
9163                 return IOCB_ERROR;
9164
9165         /*
9166          * Check to see if we are blocking IOCB processing because of a
9167          * outstanding event.
9168          */
9169         if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
9170                 goto iocb_busy;
9171
9172         if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
9173                 /*
9174                  * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
9175                  * can be issued if the link is not up.
9176                  */
9177                 switch (piocb->iocb.ulpCommand) {
9178                 case CMD_GEN_REQUEST64_CR:
9179                 case CMD_GEN_REQUEST64_CX:
9180                         if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
9181                                 (piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
9182                                         FC_RCTL_DD_UNSOL_CMD) ||
9183                                 (piocb->iocb.un.genreq64.w5.hcsw.Type !=
9184                                         MENLO_TRANSPORT_TYPE))
9185
9186                                 goto iocb_busy;
9187                         break;
9188                 case CMD_QUE_RING_BUF_CN:
9189                 case CMD_QUE_RING_BUF64_CN:
9190                         /*
9191                          * For IOCBs, like QUE_RING_BUF, that have no rsp ring
9192                          * completion, iocb_cmpl MUST be 0.
9193                          */
9194                         if (piocb->iocb_cmpl)
9195                                 piocb->iocb_cmpl = NULL;
9196                         /*FALLTHROUGH*/
9197                 case CMD_CREATE_XRI_CR:
9198                 case CMD_CLOSE_XRI_CN:
9199                 case CMD_CLOSE_XRI_CX:
9200                         break;
9201                 default:
9202                         goto iocb_busy;
9203                 }
9204
9205         /*
9206          * For FCP commands, we must be in a state where we can process link
9207          * attention events.
9208          */
9209         } else if (unlikely(pring->ringno == LPFC_FCP_RING &&
9210                             !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
9211                 goto iocb_busy;
9212         }
9213
9214         while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
9215                (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
9216                 lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
9217
9218         if (iocb)
9219                 lpfc_sli_update_ring(phba, pring);
9220         else
9221                 lpfc_sli_update_full_ring(phba, pring);
9222
9223         if (!piocb)
9224                 return IOCB_SUCCESS;
9225
9226         goto out_busy;
9227
9228  iocb_busy:
9229         pring->stats.iocb_cmd_delay++;
9230
9231  out_busy:
9232
9233         if (!(flag & SLI_IOCB_RET_IOCB)) {
9234                 __lpfc_sli_ringtx_put(phba, pring, piocb);
9235                 return IOCB_SUCCESS;
9236         }
9237
9238         return IOCB_BUSY;
9239 }
9240
9241 /**
9242  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
9243  * @phba: Pointer to HBA context object.
9244  * @piocb: Pointer to command iocb.
9245  * @sglq: Pointer to the scatter gather queue object.
9246  *
9247  * This routine converts the bpl or bde that is in the IOCB
9248  * to a sgl list for the sli4 hardware. The physical address
9249  * of the bpl/bde is converted back to a virtual address.
9250  * If the IOCB contains a BPL then the list of BDE's is
9251  * converted to sli4_sge's. If the IOCB contains a single
9252  * BDE then it is converted to a single sli_sge.
9253  * The IOCB is still in cpu endianess so the contents of
9254  * the bpl can be used without byte swapping.
9255  *
9256  * Returns valid XRI = Success, NO_XRI = Failure.
9257 **/
9258 static uint16_t
9259 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
9260                 struct lpfc_sglq *sglq)
9261 {
9262         uint16_t xritag = NO_XRI;
9263         struct ulp_bde64 *bpl = NULL;
9264         struct ulp_bde64 bde;
9265         struct sli4_sge *sgl  = NULL;
9266         struct lpfc_dmabuf *dmabuf;
9267         IOCB_t *icmd;
9268         int numBdes = 0;
9269         int i = 0;
9270         uint32_t offset = 0; /* accumulated offset in the sg request list */
9271         int inbound = 0; /* number of sg reply entries inbound from firmware */
9272
9273         if (!piocbq || !sglq)
9274                 return xritag;
9275
9276         sgl  = (struct sli4_sge *)sglq->sgl;
9277         icmd = &piocbq->iocb;
9278         if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
9279                 return sglq->sli4_xritag;
9280         if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9281                 numBdes = icmd->un.genreq64.bdl.bdeSize /
9282                                 sizeof(struct ulp_bde64);
9283                 /* The addrHigh and addrLow fields within the IOCB
9284                  * have not been byteswapped yet so there is no
9285                  * need to swap them back.
9286                  */
9287                 if (piocbq->context3)
9288                         dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
9289                 else
9290                         return xritag;
9291
9292                 bpl  = (struct ulp_bde64 *)dmabuf->virt;
9293                 if (!bpl)
9294                         return xritag;
9295
9296                 for (i = 0; i < numBdes; i++) {
9297                         /* Should already be byte swapped. */
9298                         sgl->addr_hi = bpl->addrHigh;
9299                         sgl->addr_lo = bpl->addrLow;
9300
9301                         sgl->word2 = le32_to_cpu(sgl->word2);
9302                         if ((i+1) == numBdes)
9303                                 bf_set(lpfc_sli4_sge_last, sgl, 1);
9304                         else
9305                                 bf_set(lpfc_sli4_sge_last, sgl, 0);
9306                         /* swap the size field back to the cpu so we
9307                          * can assign it to the sgl.
9308                          */
9309                         bde.tus.w = le32_to_cpu(bpl->tus.w);
9310                         sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
9311                         /* The offsets in the sgl need to be accumulated
9312                          * separately for the request and reply lists.
9313                          * The request is always first, the reply follows.
9314                          */
9315                         if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
9316                                 /* add up the reply sg entries */
9317                                 if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
9318                                         inbound++;
9319                                 /* first inbound? reset the offset */
9320                                 if (inbound == 1)
9321                                         offset = 0;
9322                                 bf_set(lpfc_sli4_sge_offset, sgl, offset);
9323                                 bf_set(lpfc_sli4_sge_type, sgl,
9324                                         LPFC_SGE_TYPE_DATA);
9325                                 offset += bde.tus.f.bdeSize;
9326                         }
9327                         sgl->word2 = cpu_to_le32(sgl->word2);
9328                         bpl++;
9329                         sgl++;
9330                 }
9331         } else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
9332                         /* The addrHigh and addrLow fields of the BDE have not
9333                          * been byteswapped yet so they need to be swapped
9334                          * before putting them in the sgl.
9335                          */
9336                         sgl->addr_hi =
9337                                 cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
9338                         sgl->addr_lo =
9339                                 cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
9340                         sgl->word2 = le32_to_cpu(sgl->word2);
9341                         bf_set(lpfc_sli4_sge_last, sgl, 1);
9342                         sgl->word2 = cpu_to_le32(sgl->word2);
9343                         sgl->sge_len =
9344                                 cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
9345         }
9346         return sglq->sli4_xritag;
9347 }
9348
9349 /**
9350  * lpfc_sli_iocb2wqe - Convert the IOCB to a work queue entry.
9351  * @phba: Pointer to HBA context object.
9352  * @piocb: Pointer to command iocb.
9353  * @wqe: Pointer to the work queue entry.
9354  *
9355  * This routine converts the iocb command to its Work Queue Entry
9356  * equivalent. The wqe pointer should not have any fields set when
9357  * this routine is called because it will memcpy over them.
9358  * This routine does not set the CQ_ID or the WQEC bits in the
9359  * wqe.
9360  *
9361  * Returns: 0 = Success, IOCB_ERROR = Failure.
9362  **/
9363 static int
9364 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
9365                 union lpfc_wqe128 *wqe)
9366 {
9367         uint32_t xmit_len = 0, total_len = 0;
9368         uint8_t ct = 0;
9369         uint32_t fip;
9370         uint32_t abort_tag;
9371         uint8_t command_type = ELS_COMMAND_NON_FIP;
9372         uint8_t cmnd;
9373         uint16_t xritag;
9374         uint16_t abrt_iotag;
9375         struct lpfc_iocbq *abrtiocbq;
9376         struct ulp_bde64 *bpl = NULL;
9377         uint32_t els_id = LPFC_ELS_ID_DEFAULT;
9378         int numBdes, i;
9379         struct ulp_bde64 bde;
9380         struct lpfc_nodelist *ndlp;
9381         uint32_t *pcmd;
9382         uint32_t if_type;
9383
9384         fip = phba->hba_flag & HBA_FIP_SUPPORT;
9385         /* The fcp commands will set command type */
9386         if (iocbq->iocb_flag &  LPFC_IO_FCP)
9387                 command_type = FCP_COMMAND;
9388         else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
9389                 command_type = ELS_COMMAND_FIP;
9390         else
9391                 command_type = ELS_COMMAND_NON_FIP;
9392
9393         if (phba->fcp_embed_io)
9394                 memset(wqe, 0, sizeof(union lpfc_wqe128));
9395         /* Some of the fields are in the right position already */
9396         memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
9397         /* The ct field has moved so reset */
9398         wqe->generic.wqe_com.word7 = 0;
9399         wqe->generic.wqe_com.word10 = 0;
9400
9401         abort_tag = (uint32_t) iocbq->iotag;
9402         xritag = iocbq->sli4_xritag;
9403         /* words0-2 bpl convert bde */
9404         if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
9405                 numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
9406                                 sizeof(struct ulp_bde64);
9407                 bpl  = (struct ulp_bde64 *)
9408                         ((struct lpfc_dmabuf *)iocbq->context3)->virt;
9409                 if (!bpl)
9410                         return IOCB_ERROR;
9411
9412                 /* Should already be byte swapped. */
9413                 wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
9414                 wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
9415                 /* swap the size field back to the cpu so we
9416                  * can assign it to the sgl.
9417                  */
9418                 wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
9419                 xmit_len = wqe->generic.bde.tus.f.bdeSize;
9420                 total_len = 0;
9421                 for (i = 0; i < numBdes; i++) {
9422                         bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
9423                         total_len += bde.tus.f.bdeSize;
9424                 }
9425         } else
9426                 xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
9427
9428         iocbq->iocb.ulpIoTag = iocbq->iotag;
9429         cmnd = iocbq->iocb.ulpCommand;
9430
9431         switch (iocbq->iocb.ulpCommand) {
9432         case CMD_ELS_REQUEST64_CR:
9433                 if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
9434                         ndlp = iocbq->context_un.ndlp;
9435                 else
9436                         ndlp = (struct lpfc_nodelist *)iocbq->context1;
9437                 if (!iocbq->iocb.ulpLe) {
9438                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9439                                 "2007 Only Limited Edition cmd Format"
9440                                 " supported 0x%x\n",
9441                                 iocbq->iocb.ulpCommand);
9442                         return IOCB_ERROR;
9443                 }
9444
9445                 wqe->els_req.payload_len = xmit_len;
9446                 /* Els_reguest64 has a TMO */
9447                 bf_set(wqe_tmo, &wqe->els_req.wqe_com,
9448                         iocbq->iocb.ulpTimeout);
9449                 /* Need a VF for word 4 set the vf bit*/
9450                 bf_set(els_req64_vf, &wqe->els_req, 0);
9451                 /* And a VFID for word 12 */
9452                 bf_set(els_req64_vfid, &wqe->els_req, 0);
9453                 ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
9454                 bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9455                        iocbq->iocb.ulpContext);
9456                 bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
9457                 bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
9458                 /* CCP CCPE PV PRI in word10 were set in the memcpy */
9459                 if (command_type == ELS_COMMAND_FIP)
9460                         els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
9461                                         >> LPFC_FIP_ELS_ID_SHIFT);
9462                 pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
9463                                         iocbq->context2)->virt);
9464                 if_type = bf_get(lpfc_sli_intf_if_type,
9465                                         &phba->sli4_hba.sli_intf);
9466                 if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
9467                         if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
9468                                 *pcmd == ELS_CMD_SCR ||
9469                                 *pcmd == ELS_CMD_RDF ||
9470                                 *pcmd == ELS_CMD_RSCN_XMT ||
9471                                 *pcmd == ELS_CMD_FDISC ||
9472                                 *pcmd == ELS_CMD_LOGO ||
9473                                 *pcmd == ELS_CMD_PLOGI)) {
9474                                 bf_set(els_req64_sp, &wqe->els_req, 1);
9475                                 bf_set(els_req64_sid, &wqe->els_req,
9476                                         iocbq->vport->fc_myDID);
9477                                 if ((*pcmd == ELS_CMD_FLOGI) &&
9478                                         !(phba->fc_topology ==
9479                                                 LPFC_TOPOLOGY_LOOP))
9480                                         bf_set(els_req64_sid, &wqe->els_req, 0);
9481                                 bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
9482                                 bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9483                                         phba->vpi_ids[iocbq->vport->vpi]);
9484                         } else if (pcmd && iocbq->context1) {
9485                                 bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
9486                                 bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
9487                                         phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9488                         }
9489                 }
9490                 bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
9491                        phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9492                 bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
9493                 bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
9494                 bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
9495                 bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
9496                 bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
9497                 bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
9498                 wqe->els_req.max_response_payload_len = total_len - xmit_len;
9499                 break;
9500         case CMD_XMIT_SEQUENCE64_CX:
9501                 bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
9502                        iocbq->iocb.un.ulpWord[3]);
9503                 bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
9504                        iocbq->iocb.unsli3.rcvsli3.ox_id);
9505                 /* The entire sequence is transmitted for this IOCB */
9506                 xmit_len = total_len;
9507                 cmnd = CMD_XMIT_SEQUENCE64_CR;
9508                 if (phba->link_flag & LS_LOOPBACK_MODE)
9509                         bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
9510                 /* fall through */
9511         case CMD_XMIT_SEQUENCE64_CR:
9512                 /* word3 iocb=io_tag32 wqe=reserved */
9513                 wqe->xmit_sequence.rsvd3 = 0;
9514                 /* word4 relative_offset memcpy */
9515                 /* word5 r_ctl/df_ctl memcpy */
9516                 bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
9517                 bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
9518                 bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
9519                        LPFC_WQE_IOD_WRITE);
9520                 bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
9521                        LPFC_WQE_LENLOC_WORD12);
9522                 bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
9523                 wqe->xmit_sequence.xmit_len = xmit_len;
9524                 command_type = OTHER_COMMAND;
9525                 break;
9526         case CMD_XMIT_BCAST64_CN:
9527                 /* word3 iocb=iotag32 wqe=seq_payload_len */
9528                 wqe->xmit_bcast64.seq_payload_len = xmit_len;
9529                 /* word4 iocb=rsvd wqe=rsvd */
9530                 /* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
9531                 /* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
9532                 bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
9533                         ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9534                 bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
9535                 bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
9536                 bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
9537                        LPFC_WQE_LENLOC_WORD3);
9538                 bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
9539                 break;
9540         case CMD_FCP_IWRITE64_CR:
9541                 command_type = FCP_COMMAND_DATA_OUT;
9542                 /* word3 iocb=iotag wqe=payload_offset_len */
9543                 /* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9544                 bf_set(payload_offset_len, &wqe->fcp_iwrite,
9545                        xmit_len + sizeof(struct fcp_rsp));
9546                 bf_set(cmd_buff_len, &wqe->fcp_iwrite,
9547                        0);
9548                 /* word4 iocb=parameter wqe=total_xfer_length memcpy */
9549                 /* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9550                 bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
9551                        iocbq->iocb.ulpFCP2Rcvy);
9552                 bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
9553                 /* Always open the exchange */
9554                 bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
9555                 bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
9556                        LPFC_WQE_LENLOC_WORD4);
9557                 bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
9558                 bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
9559                 if (iocbq->iocb_flag & LPFC_IO_OAS) {
9560                         bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
9561                         bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
9562                         if (iocbq->priority) {
9563                                 bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9564                                        (iocbq->priority << 1));
9565                         } else {
9566                                 bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
9567                                        (phba->cfg_XLanePriority << 1));
9568                         }
9569                 }
9570                 /* Note, word 10 is already initialized to 0 */
9571
9572                 /* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9573                 if (phba->cfg_enable_pbde)
9574                         bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 1);
9575                 else
9576                         bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
9577
9578                 if (phba->fcp_embed_io) {
9579                         struct lpfc_io_buf *lpfc_cmd;
9580                         struct sli4_sge *sgl;
9581                         struct fcp_cmnd *fcp_cmnd;
9582                         uint32_t *ptr;
9583
9584                         /* 128 byte wqe support here */
9585
9586                         lpfc_cmd = iocbq->context1;
9587                         sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9588                         fcp_cmnd = lpfc_cmd->fcp_cmnd;
9589
9590                         /* Word 0-2 - FCP_CMND */
9591                         wqe->generic.bde.tus.f.bdeFlags =
9592                                 BUFF_TYPE_BDE_IMMED;
9593                         wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9594                         wqe->generic.bde.addrHigh = 0;
9595                         wqe->generic.bde.addrLow =  88;  /* Word 22 */
9596
9597                         bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
9598                         bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
9599
9600                         /* Word 22-29  FCP CMND Payload */
9601                         ptr = &wqe->words[22];
9602                         memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9603                 }
9604                 break;
9605         case CMD_FCP_IREAD64_CR:
9606                 /* word3 iocb=iotag wqe=payload_offset_len */
9607                 /* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9608                 bf_set(payload_offset_len, &wqe->fcp_iread,
9609                        xmit_len + sizeof(struct fcp_rsp));
9610                 bf_set(cmd_buff_len, &wqe->fcp_iread,
9611                        0);
9612                 /* word4 iocb=parameter wqe=total_xfer_length memcpy */
9613                 /* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
9614                 bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
9615                        iocbq->iocb.ulpFCP2Rcvy);
9616                 bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
9617                 /* Always open the exchange */
9618                 bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
9619                 bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
9620                        LPFC_WQE_LENLOC_WORD4);
9621                 bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
9622                 bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
9623                 if (iocbq->iocb_flag & LPFC_IO_OAS) {
9624                         bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
9625                         bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
9626                         if (iocbq->priority) {
9627                                 bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9628                                        (iocbq->priority << 1));
9629                         } else {
9630                                 bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
9631                                        (phba->cfg_XLanePriority << 1));
9632                         }
9633                 }
9634                 /* Note, word 10 is already initialized to 0 */
9635
9636                 /* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
9637                 if (phba->cfg_enable_pbde)
9638                         bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 1);
9639                 else
9640                         bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
9641
9642                 if (phba->fcp_embed_io) {
9643                         struct lpfc_io_buf *lpfc_cmd;
9644                         struct sli4_sge *sgl;
9645                         struct fcp_cmnd *fcp_cmnd;
9646                         uint32_t *ptr;
9647
9648                         /* 128 byte wqe support here */
9649
9650                         lpfc_cmd = iocbq->context1;
9651                         sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9652                         fcp_cmnd = lpfc_cmd->fcp_cmnd;
9653
9654                         /* Word 0-2 - FCP_CMND */
9655                         wqe->generic.bde.tus.f.bdeFlags =
9656                                 BUFF_TYPE_BDE_IMMED;
9657                         wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9658                         wqe->generic.bde.addrHigh = 0;
9659                         wqe->generic.bde.addrLow =  88;  /* Word 22 */
9660
9661                         bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
9662                         bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
9663
9664                         /* Word 22-29  FCP CMND Payload */
9665                         ptr = &wqe->words[22];
9666                         memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9667                 }
9668                 break;
9669         case CMD_FCP_ICMND64_CR:
9670                 /* word3 iocb=iotag wqe=payload_offset_len */
9671                 /* Add the FCP_CMD and FCP_RSP sizes to get the offset */
9672                 bf_set(payload_offset_len, &wqe->fcp_icmd,
9673                        xmit_len + sizeof(struct fcp_rsp));
9674                 bf_set(cmd_buff_len, &wqe->fcp_icmd,
9675                        0);
9676                 /* word3 iocb=IO_TAG wqe=reserved */
9677                 bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
9678                 /* Always open the exchange */
9679                 bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
9680                 bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
9681                 bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
9682                 bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
9683                        LPFC_WQE_LENLOC_NONE);
9684                 bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
9685                        iocbq->iocb.ulpFCP2Rcvy);
9686                 if (iocbq->iocb_flag & LPFC_IO_OAS) {
9687                         bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
9688                         bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
9689                         if (iocbq->priority) {
9690                                 bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
9691                                        (iocbq->priority << 1));
9692                         } else {
9693                                 bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
9694                                        (phba->cfg_XLanePriority << 1));
9695                         }
9696                 }
9697                 /* Note, word 10 is already initialized to 0 */
9698
9699                 if (phba->fcp_embed_io) {
9700                         struct lpfc_io_buf *lpfc_cmd;
9701                         struct sli4_sge *sgl;
9702                         struct fcp_cmnd *fcp_cmnd;
9703                         uint32_t *ptr;
9704
9705                         /* 128 byte wqe support here */
9706
9707                         lpfc_cmd = iocbq->context1;
9708                         sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
9709                         fcp_cmnd = lpfc_cmd->fcp_cmnd;
9710
9711                         /* Word 0-2 - FCP_CMND */
9712                         wqe->generic.bde.tus.f.bdeFlags =
9713                                 BUFF_TYPE_BDE_IMMED;
9714                         wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
9715                         wqe->generic.bde.addrHigh = 0;
9716                         wqe->generic.bde.addrLow =  88;  /* Word 22 */
9717
9718                         bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
9719                         bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
9720
9721                         /* Word 22-29  FCP CMND Payload */
9722                         ptr = &wqe->words[22];
9723                         memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
9724                 }
9725                 break;
9726         case CMD_GEN_REQUEST64_CR:
9727                 /* For this command calculate the xmit length of the
9728                  * request bde.
9729                  */
9730                 xmit_len = 0;
9731                 numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
9732                         sizeof(struct ulp_bde64);
9733                 for (i = 0; i < numBdes; i++) {
9734                         bde.tus.w = le32_to_cpu(bpl[i].tus.w);
9735                         if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
9736                                 break;
9737                         xmit_len += bde.tus.f.bdeSize;
9738                 }
9739                 /* word3 iocb=IO_TAG wqe=request_payload_len */
9740                 wqe->gen_req.request_payload_len = xmit_len;
9741                 /* word4 iocb=parameter wqe=relative_offset memcpy */
9742                 /* word5 [rctl, type, df_ctl, la] copied in memcpy */
9743                 /* word6 context tag copied in memcpy */
9744                 if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
9745                         ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
9746                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9747                                 "2015 Invalid CT %x command 0x%x\n",
9748                                 ct, iocbq->iocb.ulpCommand);
9749                         return IOCB_ERROR;
9750                 }
9751                 bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
9752                 bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
9753                 bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
9754                 bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
9755                 bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
9756                 bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
9757                 bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
9758                 bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
9759                 wqe->gen_req.max_response_payload_len = total_len - xmit_len;
9760                 command_type = OTHER_COMMAND;
9761                 break;
9762         case CMD_XMIT_ELS_RSP64_CX:
9763                 ndlp = (struct lpfc_nodelist *)iocbq->context1;
9764                 /* words0-2 BDE memcpy */
9765                 /* word3 iocb=iotag32 wqe=response_payload_len */
9766                 wqe->xmit_els_rsp.response_payload_len = xmit_len;
9767                 /* word4 */
9768                 wqe->xmit_els_rsp.word4 = 0;
9769                 /* word5 iocb=rsvd wge=did */
9770                 bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
9771                          iocbq->iocb.un.xseq64.xmit_els_remoteID);
9772
9773                 if_type = bf_get(lpfc_sli_intf_if_type,
9774                                         &phba->sli4_hba.sli_intf);
9775                 if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
9776                         if (iocbq->vport->fc_flag & FC_PT2PT) {
9777                                 bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
9778                                 bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
9779                                         iocbq->vport->fc_myDID);
9780                                 if (iocbq->vport->fc_myDID == Fabric_DID) {
9781                                         bf_set(wqe_els_did,
9782                                                 &wqe->xmit_els_rsp.wqe_dest, 0);
9783                                 }
9784                         }
9785                 }
9786                 bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
9787                        ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9788                 bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
9789                 bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
9790                        iocbq->iocb.unsli3.rcvsli3.ox_id);
9791                 if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
9792                         bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
9793                                phba->vpi_ids[iocbq->vport->vpi]);
9794                 bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
9795                 bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
9796                 bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
9797                 bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
9798                        LPFC_WQE_LENLOC_WORD3);
9799                 bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
9800                 bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
9801                        phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
9802                 pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
9803                                         iocbq->context2)->virt);
9804                 if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
9805                                 bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
9806                                 bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
9807                                         iocbq->vport->fc_myDID);
9808                                 bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
9809                                 bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
9810                                         phba->vpi_ids[phba->pport->vpi]);
9811                 }
9812                 command_type = OTHER_COMMAND;
9813                 break;
9814         case CMD_CLOSE_XRI_CN:
9815         case CMD_ABORT_XRI_CN:
9816         case CMD_ABORT_XRI_CX:
9817                 /* words 0-2 memcpy should be 0 rserved */
9818                 /* port will send abts */
9819                 abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
9820                 if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
9821                         abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
9822                         fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
9823                 } else
9824                         fip = 0;
9825
9826                 if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
9827                         /*
9828                          * The link is down, or the command was ELS_FIP
9829                          * so the fw does not need to send abts
9830                          * on the wire.
9831                          */
9832                         bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
9833                 else
9834                         bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
9835                 bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
9836                 /* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
9837                 wqe->abort_cmd.rsrvd5 = 0;
9838                 bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
9839                         ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
9840                 abort_tag = iocbq->iocb.un.acxri.abortIoTag;
9841                 /*
9842                  * The abort handler will send us CMD_ABORT_XRI_CN or
9843                  * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
9844                  */
9845                 bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
9846                 bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
9847                 bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
9848                        LPFC_WQE_LENLOC_NONE);
9849                 cmnd = CMD_ABORT_XRI_CX;
9850                 command_type = OTHER_COMMAND;
9851                 xritag = 0;
9852                 break;
9853         case CMD_XMIT_BLS_RSP64_CX:
9854                 ndlp = (struct lpfc_nodelist *)iocbq->context1;
9855                 /* As BLS ABTS RSP WQE is very different from other WQEs,
9856                  * we re-construct this WQE here based on information in
9857                  * iocbq from scratch.
9858                  */
9859                 memset(wqe, 0, sizeof(*wqe));
9860                 /* OX_ID is invariable to who sent ABTS to CT exchange */
9861                 bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
9862                        bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
9863                 if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
9864                     LPFC_ABTS_UNSOL_INT) {
9865                         /* ABTS sent by initiator to CT exchange, the
9866                          * RX_ID field will be filled with the newly
9867                          * allocated responder XRI.
9868                          */
9869                         bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
9870                                iocbq->sli4_xritag);
9871                 } else {
9872                         /* ABTS sent by responder to CT exchange, the
9873                          * RX_ID field will be filled with the responder
9874                          * RX_ID from ABTS.
9875                          */
9876                         bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
9877                                bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
9878                 }
9879                 bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
9880                 bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
9881
9882                 /* Use CT=VPI */
9883                 bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
9884                         ndlp->nlp_DID);
9885                 bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
9886                         iocbq->iocb.ulpContext);
9887                 bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
9888                 bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
9889                         phba->vpi_ids[phba->pport->vpi]);
9890                 bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
9891                 bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
9892                        LPFC_WQE_LENLOC_NONE);
9893                 /* Overwrite the pre-set comnd type with OTHER_COMMAND */
9894                 command_type = OTHER_COMMAND;
9895                 if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
9896                         bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
9897                                bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
9898                         bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
9899                                bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
9900                         bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
9901                                bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
9902                 }
9903
9904                 break;
9905         case CMD_SEND_FRAME:
9906                 bf_set(wqe_cmnd, &wqe->generic.wqe_com, CMD_SEND_FRAME);
9907                 bf_set(wqe_sof, &wqe->generic.wqe_com, 0x2E); /* SOF byte */
9908                 bf_set(wqe_eof, &wqe->generic.wqe_com, 0x41); /* EOF byte */
9909                 bf_set(wqe_lenloc, &wqe->generic.wqe_com, 1);
9910                 bf_set(wqe_xbl, &wqe->generic.wqe_com, 1);
9911                 bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
9912                 bf_set(wqe_xc, &wqe->generic.wqe_com, 1);
9913                 bf_set(wqe_cmd_type, &wqe->generic.wqe_com, 0xA);
9914                 bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
9915                 bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
9916                 bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
9917                 return 0;
9918         case CMD_XRI_ABORTED_CX:
9919         case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
9920         case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
9921         case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
9922         case CMD_FCP_TRSP64_CX: /* Target mode rcv */
9923         case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
9924         default:
9925                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
9926                                 "2014 Invalid command 0x%x\n",
9927                                 iocbq->iocb.ulpCommand);
9928                 return IOCB_ERROR;
9929                 break;
9930         }
9931
9932         if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
9933                 bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
9934         else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
9935                 bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
9936         else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
9937                 bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
9938         iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
9939                               LPFC_IO_DIF_INSERT);
9940         bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
9941         bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
9942         wqe->generic.wqe_com.abort_tag = abort_tag;
9943         bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
9944         bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
9945         bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
9946         bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
9947         return 0;
9948 }
9949
9950 /**
9951  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
9952  * @phba: Pointer to HBA context object.
9953  * @ring_number: SLI ring number to issue iocb on.
9954  * @piocb: Pointer to command iocb.
9955  * @flag: Flag indicating if this command can be put into txq.
9956  *
9957  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
9958  * an iocb command to an HBA with SLI-4 interface spec.
9959  *
9960  * This function is called with ringlock held. The function will return success
9961  * after it successfully submit the iocb to firmware or after adding to the
9962  * txq.
9963  **/
9964 static int
9965 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
9966                          struct lpfc_iocbq *piocb, uint32_t flag)
9967 {
9968         struct lpfc_sglq *sglq;
9969         union lpfc_wqe128 wqe;
9970         struct lpfc_queue *wq;
9971         struct lpfc_sli_ring *pring;
9972
9973         /* Get the WQ */
9974         if ((piocb->iocb_flag & LPFC_IO_FCP) ||
9975             (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
9976                 wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
9977         } else {
9978                 wq = phba->sli4_hba.els_wq;
9979         }
9980
9981         /* Get corresponding ring */
9982         pring = wq->pring;
9983
9984         /*
9985          * The WQE can be either 64 or 128 bytes,
9986          */
9987
9988         lockdep_assert_held(&pring->ring_lock);
9989
9990         if (piocb->sli4_xritag == NO_XRI) {
9991                 if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
9992                     piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
9993                         sglq = NULL;
9994                 else {
9995                         if (!list_empty(&pring->txq)) {
9996                                 if (!(flag & SLI_IOCB_RET_IOCB)) {
9997                                         __lpfc_sli_ringtx_put(phba,
9998                                                 pring, piocb);
9999                                         return IOCB_SUCCESS;
10000                                 } else {
10001                                         return IOCB_BUSY;
10002                                 }
10003                         } else {
10004                                 sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10005                                 if (!sglq) {
10006                                         if (!(flag & SLI_IOCB_RET_IOCB)) {
10007                                                 __lpfc_sli_ringtx_put(phba,
10008                                                                 pring,
10009                                                                 piocb);
10010                                                 return IOCB_SUCCESS;
10011                                         } else
10012                                                 return IOCB_BUSY;
10013                                 }
10014                         }
10015                 }
10016         } else if (piocb->iocb_flag &  LPFC_IO_FCP)
10017                 /* These IO's already have an XRI and a mapped sgl. */
10018                 sglq = NULL;
10019         else {
10020                 /*
10021                  * This is a continuation of a commandi,(CX) so this
10022                  * sglq is on the active list
10023                  */
10024                 sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10025                 if (!sglq)
10026                         return IOCB_ERROR;
10027         }
10028
10029         if (sglq) {
10030                 piocb->sli4_lxritag = sglq->sli4_lxritag;
10031                 piocb->sli4_xritag = sglq->sli4_xritag;
10032                 if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
10033                         return IOCB_ERROR;
10034         }
10035
10036         if (lpfc_sli4_iocb2wqe(phba, piocb, &wqe))
10037                 return IOCB_ERROR;
10038
10039         if (lpfc_sli4_wq_put(wq, &wqe))
10040                 return IOCB_ERROR;
10041         lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10042
10043         return 0;
10044 }
10045
10046 /**
10047  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10048  *
10049  * This routine wraps the actual lockless version for issusing IOCB function
10050  * pointer from the lpfc_hba struct.
10051  *
10052  * Return codes:
10053  * IOCB_ERROR - Error
10054  * IOCB_SUCCESS - Success
10055  * IOCB_BUSY - Busy
10056  **/
10057 int
10058 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10059                 struct lpfc_iocbq *piocb, uint32_t flag)
10060 {
10061         return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10062 }
10063
10064 /**
10065  * lpfc_sli_api_table_setup - Set up sli api function jump table
10066  * @phba: The hba struct for which this call is being executed.
10067  * @dev_grp: The HBA PCI-Device group number.
10068  *
10069  * This routine sets up the SLI interface API function jump table in @phba
10070  * struct.
10071  * Returns: 0 - success, -ENODEV - failure.
10072  **/
10073 int
10074 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10075 {
10076
10077         switch (dev_grp) {
10078         case LPFC_PCI_DEV_LP:
10079                 phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
10080                 phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
10081                 break;
10082         case LPFC_PCI_DEV_OC:
10083                 phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
10084                 phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
10085                 break;
10086         default:
10087                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10088                                 "1419 Invalid HBA PCI-device group: 0x%x\n",
10089                                 dev_grp);
10090                 return -ENODEV;
10091                 break;
10092         }
10093         phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
10094         return 0;
10095 }
10096
10097 /**
10098  * lpfc_sli4_calc_ring - Calculates which ring to use
10099  * @phba: Pointer to HBA context object.
10100  * @piocb: Pointer to command iocb.
10101  *
10102  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
10103  * hba_wqidx, thus we need to calculate the corresponding ring.
10104  * Since ABORTS must go on the same WQ of the command they are
10105  * aborting, we use command's hba_wqidx.
10106  */
10107 struct lpfc_sli_ring *
10108 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
10109 {
10110         struct lpfc_io_buf *lpfc_cmd;
10111
10112         if (piocb->iocb_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
10113                 if (unlikely(!phba->sli4_hba.hdwq))
10114                         return NULL;
10115                 /*
10116                  * for abort iocb hba_wqidx should already
10117                  * be setup based on what work queue we used.
10118                  */
10119                 if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
10120                         lpfc_cmd = (struct lpfc_io_buf *)piocb->context1;
10121                         piocb->hba_wqidx = lpfc_cmd->hdwq_no;
10122                 }
10123                 return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
10124         } else {
10125                 if (unlikely(!phba->sli4_hba.els_wq))
10126                         return NULL;
10127                 piocb->hba_wqidx = 0;
10128                 return phba->sli4_hba.els_wq->pring;
10129         }
10130 }
10131
10132 /**
10133  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
10134  * @phba: Pointer to HBA context object.
10135  * @pring: Pointer to driver SLI ring object.
10136  * @piocb: Pointer to command iocb.
10137  * @flag: Flag indicating if this command can be put into txq.
10138  *
10139  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
10140  * function. This function gets the hbalock and calls
10141  * __lpfc_sli_issue_iocb function and will return the error returned
10142  * by __lpfc_sli_issue_iocb function. This wrapper is used by
10143  * functions which do not hold hbalock.
10144  **/
10145 int
10146 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10147                     struct lpfc_iocbq *piocb, uint32_t flag)
10148 {
10149         struct lpfc_sli_ring *pring;
10150         struct lpfc_queue *eq;
10151         unsigned long iflags;
10152         int rc;
10153
10154         if (phba->sli_rev == LPFC_SLI_REV4) {
10155                 eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
10156
10157                 pring = lpfc_sli4_calc_ring(phba, piocb);
10158                 if (unlikely(pring == NULL))
10159                         return IOCB_ERROR;
10160
10161                 spin_lock_irqsave(&pring->ring_lock, iflags);
10162                 rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10163                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
10164
10165                 lpfc_sli4_poll_eq(eq, LPFC_POLL_FASTPATH);
10166         } else {
10167                 /* For now, SLI2/3 will still use hbalock */
10168                 spin_lock_irqsave(&phba->hbalock, iflags);
10169                 rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10170                 spin_unlock_irqrestore(&phba->hbalock, iflags);
10171         }
10172         return rc;
10173 }
10174
10175 /**
10176  * lpfc_extra_ring_setup - Extra ring setup function
10177  * @phba: Pointer to HBA context object.
10178  *
10179  * This function is called while driver attaches with the
10180  * HBA to setup the extra ring. The extra ring is used
10181  * only when driver needs to support target mode functionality
10182  * or IP over FC functionalities.
10183  *
10184  * This function is called with no lock held. SLI3 only.
10185  **/
10186 static int
10187 lpfc_extra_ring_setup( struct lpfc_hba *phba)
10188 {
10189         struct lpfc_sli *psli;
10190         struct lpfc_sli_ring *pring;
10191
10192         psli = &phba->sli;
10193
10194         /* Adjust cmd/rsp ring iocb entries more evenly */
10195
10196         /* Take some away from the FCP ring */
10197         pring = &psli->sli3_ring[LPFC_FCP_RING];
10198         pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10199         pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10200         pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10201         pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10202
10203         /* and give them to the extra ring */
10204         pring = &psli->sli3_ring[LPFC_EXTRA_RING];
10205
10206         pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10207         pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10208         pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10209         pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10210
10211         /* Setup default profile for this ring */
10212         pring->iotag_max = 4096;
10213         pring->num_mask = 1;
10214         pring->prt[0].profile = 0;      /* Mask 0 */
10215         pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
10216         pring->prt[0].type = phba->cfg_multi_ring_type;
10217         pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
10218         return 0;
10219 }
10220
10221 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
10222  * @phba: Pointer to HBA context object.
10223  * @iocbq: Pointer to iocb object.
10224  *
10225  * The async_event handler calls this routine when it receives
10226  * an ASYNC_STATUS_CN event from the port.  The port generates
10227  * this event when an Abort Sequence request to an rport fails
10228  * twice in succession.  The abort could be originated by the
10229  * driver or by the port.  The ABTS could have been for an ELS
10230  * or FCP IO.  The port only generates this event when an ABTS
10231  * fails to complete after one retry.
10232  */
10233 static void
10234 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
10235                           struct lpfc_iocbq *iocbq)
10236 {
10237         struct lpfc_nodelist *ndlp = NULL;
10238         uint16_t rpi = 0, vpi = 0;
10239         struct lpfc_vport *vport = NULL;
10240
10241         /* The rpi in the ulpContext is vport-sensitive. */
10242         vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
10243         rpi = iocbq->iocb.ulpContext;
10244
10245         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10246                         "3092 Port generated ABTS async event "
10247                         "on vpi %d rpi %d status 0x%x\n",
10248                         vpi, rpi, iocbq->iocb.ulpStatus);
10249
10250         vport = lpfc_find_vport_by_vpid(phba, vpi);
10251         if (!vport)
10252                 goto err_exit;
10253         ndlp = lpfc_findnode_rpi(vport, rpi);
10254         if (!ndlp || !NLP_CHK_NODE_ACT(ndlp))
10255                 goto err_exit;
10256
10257         if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
10258                 lpfc_sli_abts_recover_port(vport, ndlp);
10259         return;
10260
10261  err_exit:
10262         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10263                         "3095 Event Context not found, no "
10264                         "action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
10265                         iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
10266                         vpi, rpi);
10267 }
10268
10269 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
10270  * @phba: pointer to HBA context object.
10271  * @ndlp: nodelist pointer for the impacted rport.
10272  * @axri: pointer to the wcqe containing the failed exchange.
10273  *
10274  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
10275  * port.  The port generates this event when an abort exchange request to an
10276  * rport fails twice in succession with no reply.  The abort could be originated
10277  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
10278  */
10279 void
10280 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
10281                            struct lpfc_nodelist *ndlp,
10282                            struct sli4_wcqe_xri_aborted *axri)
10283 {
10284         struct lpfc_vport *vport;
10285         uint32_t ext_status = 0;
10286
10287         if (!ndlp || !NLP_CHK_NODE_ACT(ndlp)) {
10288                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
10289                                 "3115 Node Context not found, driver "
10290                                 "ignoring abts err event\n");
10291                 return;
10292         }
10293
10294         vport = ndlp->vport;
10295         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
10296                         "3116 Port generated FCP XRI ABORT event on "
10297                         "vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
10298                         ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
10299                         bf_get(lpfc_wcqe_xa_xri, axri),
10300                         bf_get(lpfc_wcqe_xa_status, axri),
10301                         axri->parameter);
10302
10303         /*
10304          * Catch the ABTS protocol failure case.  Older OCe FW releases returned
10305          * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
10306          * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
10307          */
10308         ext_status = axri->parameter & IOERR_PARAM_MASK;
10309         if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
10310             ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
10311                 lpfc_sli_abts_recover_port(vport, ndlp);
10312 }
10313
10314 /**
10315  * lpfc_sli_async_event_handler - ASYNC iocb handler function
10316  * @phba: Pointer to HBA context object.
10317  * @pring: Pointer to driver SLI ring object.
10318  * @iocbq: Pointer to iocb object.
10319  *
10320  * This function is called by the slow ring event handler
10321  * function when there is an ASYNC event iocb in the ring.
10322  * This function is called with no lock held.
10323  * Currently this function handles only temperature related
10324  * ASYNC events. The function decodes the temperature sensor
10325  * event message and posts events for the management applications.
10326  **/
10327 static void
10328 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
10329         struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
10330 {
10331         IOCB_t *icmd;
10332         uint16_t evt_code;
10333         struct temp_event temp_event_data;
10334         struct Scsi_Host *shost;
10335         uint32_t *iocb_w;
10336
10337         icmd = &iocbq->iocb;
10338         evt_code = icmd->un.asyncstat.evt_code;
10339
10340         switch (evt_code) {
10341         case ASYNC_TEMP_WARN:
10342         case ASYNC_TEMP_SAFE:
10343                 temp_event_data.data = (uint32_t) icmd->ulpContext;
10344                 temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
10345                 if (evt_code == ASYNC_TEMP_WARN) {
10346                         temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
10347                         lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
10348                                 "0347 Adapter is very hot, please take "
10349                                 "corrective action. temperature : %d Celsius\n",
10350                                 (uint32_t) icmd->ulpContext);
10351                 } else {
10352                         temp_event_data.event_code = LPFC_NORMAL_TEMP;
10353                         lpfc_printf_log(phba, KERN_ERR, LOG_TEMP,
10354                                 "0340 Adapter temperature is OK now. "
10355                                 "temperature : %d Celsius\n",
10356                                 (uint32_t) icmd->ulpContext);
10357                 }
10358
10359                 /* Send temperature change event to applications */
10360                 shost = lpfc_shost_from_vport(phba->pport);
10361                 fc_host_post_vendor_event(shost, fc_get_event_number(),
10362                         sizeof(temp_event_data), (char *) &temp_event_data,
10363                         LPFC_NL_VENDOR_ID);
10364                 break;
10365         case ASYNC_STATUS_CN:
10366                 lpfc_sli_abts_err_handler(phba, iocbq);
10367                 break;
10368         default:
10369                 iocb_w = (uint32_t *) icmd;
10370                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
10371                         "0346 Ring %d handler: unexpected ASYNC_STATUS"
10372                         " evt_code 0x%x\n"
10373                         "W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
10374                         "W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
10375                         "W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
10376                         "W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
10377                         pring->ringno, icmd->un.asyncstat.evt_code,
10378                         iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
10379                         iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
10380                         iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
10381                         iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
10382
10383                 break;
10384         }
10385 }
10386
10387
10388 /**
10389  * lpfc_sli4_setup - SLI ring setup function
10390  * @phba: Pointer to HBA context object.
10391  *
10392  * lpfc_sli_setup sets up rings of the SLI interface with
10393  * number of iocbs per ring and iotags. This function is
10394  * called while driver attach to the HBA and before the
10395  * interrupts are enabled. So there is no need for locking.
10396  *
10397  * This function always returns 0.
10398  **/
10399 int
10400 lpfc_sli4_setup(struct lpfc_hba *phba)
10401 {
10402         struct lpfc_sli_ring *pring;
10403
10404         pring = phba->sli4_hba.els_wq->pring;
10405         pring->num_mask = LPFC_MAX_RING_MASK;
10406         pring->prt[0].profile = 0;      /* Mask 0 */
10407         pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10408         pring->prt[0].type = FC_TYPE_ELS;
10409         pring->prt[0].lpfc_sli_rcv_unsol_event =
10410             lpfc_els_unsol_event;
10411         pring->prt[1].profile = 0;      /* Mask 1 */
10412         pring->prt[1].rctl = FC_RCTL_ELS_REP;
10413         pring->prt[1].type = FC_TYPE_ELS;
10414         pring->prt[1].lpfc_sli_rcv_unsol_event =
10415             lpfc_els_unsol_event;
10416         pring->prt[2].profile = 0;      /* Mask 2 */
10417         /* NameServer Inquiry */
10418         pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10419         /* NameServer */
10420         pring->prt[2].type = FC_TYPE_CT;
10421         pring->prt[2].lpfc_sli_rcv_unsol_event =
10422             lpfc_ct_unsol_event;
10423         pring->prt[3].profile = 0;      /* Mask 3 */
10424         /* NameServer response */
10425         pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10426         /* NameServer */
10427         pring->prt[3].type = FC_TYPE_CT;
10428         pring->prt[3].lpfc_sli_rcv_unsol_event =
10429             lpfc_ct_unsol_event;
10430         return 0;
10431 }
10432
10433 /**
10434  * lpfc_sli_setup - SLI ring setup function
10435  * @phba: Pointer to HBA context object.
10436  *
10437  * lpfc_sli_setup sets up rings of the SLI interface with
10438  * number of iocbs per ring and iotags. This function is
10439  * called while driver attach to the HBA and before the
10440  * interrupts are enabled. So there is no need for locking.
10441  *
10442  * This function always returns 0. SLI3 only.
10443  **/
10444 int
10445 lpfc_sli_setup(struct lpfc_hba *phba)
10446 {
10447         int i, totiocbsize = 0;
10448         struct lpfc_sli *psli = &phba->sli;
10449         struct lpfc_sli_ring *pring;
10450
10451         psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
10452         psli->sli_flag = 0;
10453
10454         psli->iocbq_lookup = NULL;
10455         psli->iocbq_lookup_len = 0;
10456         psli->last_iotag = 0;
10457
10458         for (i = 0; i < psli->num_rings; i++) {
10459                 pring = &psli->sli3_ring[i];
10460                 switch (i) {
10461                 case LPFC_FCP_RING:     /* ring 0 - FCP */
10462                         /* numCiocb and numRiocb are used in config_port */
10463                         pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
10464                         pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
10465                         pring->sli.sli3.numCiocb +=
10466                                 SLI2_IOCB_CMD_R1XTRA_ENTRIES;
10467                         pring->sli.sli3.numRiocb +=
10468                                 SLI2_IOCB_RSP_R1XTRA_ENTRIES;
10469                         pring->sli.sli3.numCiocb +=
10470                                 SLI2_IOCB_CMD_R3XTRA_ENTRIES;
10471                         pring->sli.sli3.numRiocb +=
10472                                 SLI2_IOCB_RSP_R3XTRA_ENTRIES;
10473                         pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10474                                                         SLI3_IOCB_CMD_SIZE :
10475                                                         SLI2_IOCB_CMD_SIZE;
10476                         pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10477                                                         SLI3_IOCB_RSP_SIZE :
10478                                                         SLI2_IOCB_RSP_SIZE;
10479                         pring->iotag_ctr = 0;
10480                         pring->iotag_max =
10481                             (phba->cfg_hba_queue_depth * 2);
10482                         pring->fast_iotag = pring->iotag_max;
10483                         pring->num_mask = 0;
10484                         break;
10485                 case LPFC_EXTRA_RING:   /* ring 1 - EXTRA */
10486                         /* numCiocb and numRiocb are used in config_port */
10487                         pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
10488                         pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
10489                         pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10490                                                         SLI3_IOCB_CMD_SIZE :
10491                                                         SLI2_IOCB_CMD_SIZE;
10492                         pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10493                                                         SLI3_IOCB_RSP_SIZE :
10494                                                         SLI2_IOCB_RSP_SIZE;
10495                         pring->iotag_max = phba->cfg_hba_queue_depth;
10496                         pring->num_mask = 0;
10497                         break;
10498                 case LPFC_ELS_RING:     /* ring 2 - ELS / CT */
10499                         /* numCiocb and numRiocb are used in config_port */
10500                         pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
10501                         pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
10502                         pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
10503                                                         SLI3_IOCB_CMD_SIZE :
10504                                                         SLI2_IOCB_CMD_SIZE;
10505                         pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
10506                                                         SLI3_IOCB_RSP_SIZE :
10507                                                         SLI2_IOCB_RSP_SIZE;
10508                         pring->fast_iotag = 0;
10509                         pring->iotag_ctr = 0;
10510                         pring->iotag_max = 4096;
10511                         pring->lpfc_sli_rcv_async_status =
10512                                 lpfc_sli_async_event_handler;
10513                         pring->num_mask = LPFC_MAX_RING_MASK;
10514                         pring->prt[0].profile = 0;      /* Mask 0 */
10515                         pring->prt[0].rctl = FC_RCTL_ELS_REQ;
10516                         pring->prt[0].type = FC_TYPE_ELS;
10517                         pring->prt[0].lpfc_sli_rcv_unsol_event =
10518                             lpfc_els_unsol_event;
10519                         pring->prt[1].profile = 0;      /* Mask 1 */
10520                         pring->prt[1].rctl = FC_RCTL_ELS_REP;
10521                         pring->prt[1].type = FC_TYPE_ELS;
10522                         pring->prt[1].lpfc_sli_rcv_unsol_event =
10523                             lpfc_els_unsol_event;
10524                         pring->prt[2].profile = 0;      /* Mask 2 */
10525                         /* NameServer Inquiry */
10526                         pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
10527                         /* NameServer */
10528                         pring->prt[2].type = FC_TYPE_CT;
10529                         pring->prt[2].lpfc_sli_rcv_unsol_event =
10530                             lpfc_ct_unsol_event;
10531                         pring->prt[3].profile = 0;      /* Mask 3 */
10532                         /* NameServer response */
10533                         pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
10534                         /* NameServer */
10535                         pring->prt[3].type = FC_TYPE_CT;
10536                         pring->prt[3].lpfc_sli_rcv_unsol_event =
10537                             lpfc_ct_unsol_event;
10538                         break;
10539                 }
10540                 totiocbsize += (pring->sli.sli3.numCiocb *
10541                         pring->sli.sli3.sizeCiocb) +
10542                         (pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
10543         }
10544         if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
10545                 /* Too many cmd / rsp ring entries in SLI2 SLIM */
10546                 printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
10547                        "SLI2 SLIM Data: x%x x%lx\n",
10548                        phba->brd_no, totiocbsize,
10549                        (unsigned long) MAX_SLIM_IOCB_SIZE);
10550         }
10551         if (phba->cfg_multi_ring_support == 2)
10552                 lpfc_extra_ring_setup(phba);
10553
10554         return 0;
10555 }
10556
10557 /**
10558  * lpfc_sli4_queue_init - Queue initialization function
10559  * @phba: Pointer to HBA context object.
10560  *
10561  * lpfc_sli4_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_sli4_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 < phba->cfg_hdw_queue; i++) {
10581                 pring = phba->sli4_hba.hdwq[i].io_wq->pring;
10582                 pring->flag = 0;
10583                 pring->ringno = LPFC_FCP_RING;
10584                 pring->txcmplq_cnt = 0;
10585                 INIT_LIST_HEAD(&pring->txq);
10586                 INIT_LIST_HEAD(&pring->txcmplq);
10587                 INIT_LIST_HEAD(&pring->iocb_continueq);
10588                 spin_lock_init(&pring->ring_lock);
10589         }
10590         pring = phba->sli4_hba.els_wq->pring;
10591         pring->flag = 0;
10592         pring->ringno = LPFC_ELS_RING;
10593         pring->txcmplq_cnt = 0;
10594         INIT_LIST_HEAD(&pring->txq);
10595         INIT_LIST_HEAD(&pring->txcmplq);
10596         INIT_LIST_HEAD(&pring->iocb_continueq);
10597         spin_lock_init(&pring->ring_lock);
10598
10599         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
10600                 pring = phba->sli4_hba.nvmels_wq->pring;
10601                 pring->flag = 0;
10602                 pring->ringno = LPFC_ELS_RING;
10603                 pring->txcmplq_cnt = 0;
10604                 INIT_LIST_HEAD(&pring->txq);
10605                 INIT_LIST_HEAD(&pring->txcmplq);
10606                 INIT_LIST_HEAD(&pring->iocb_continueq);
10607                 spin_lock_init(&pring->ring_lock);
10608         }
10609
10610         spin_unlock_irq(&phba->hbalock);
10611 }
10612
10613 /**
10614  * lpfc_sli_queue_init - Queue initialization function
10615  * @phba: Pointer to HBA context object.
10616  *
10617  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
10618  * ring. This function also initializes ring indices of each ring.
10619  * This function is called during the initialization of the SLI
10620  * interface of an HBA.
10621  * This function is called with no lock held and always returns
10622  * 1.
10623  **/
10624 void
10625 lpfc_sli_queue_init(struct lpfc_hba *phba)
10626 {
10627         struct lpfc_sli *psli;
10628         struct lpfc_sli_ring *pring;
10629         int i;
10630
10631         psli = &phba->sli;
10632         spin_lock_irq(&phba->hbalock);
10633         INIT_LIST_HEAD(&psli->mboxq);
10634         INIT_LIST_HEAD(&psli->mboxq_cmpl);
10635         /* Initialize list headers for txq and txcmplq as double linked lists */
10636         for (i = 0; i < psli->num_rings; i++) {
10637                 pring = &psli->sli3_ring[i];
10638                 pring->ringno = i;
10639                 pring->sli.sli3.next_cmdidx  = 0;
10640                 pring->sli.sli3.local_getidx = 0;
10641                 pring->sli.sli3.cmdidx = 0;
10642                 INIT_LIST_HEAD(&pring->iocb_continueq);
10643                 INIT_LIST_HEAD(&pring->iocb_continue_saveq);
10644                 INIT_LIST_HEAD(&pring->postbufq);
10645                 pring->flag = 0;
10646                 INIT_LIST_HEAD(&pring->txq);
10647                 INIT_LIST_HEAD(&pring->txcmplq);
10648                 spin_lock_init(&pring->ring_lock);
10649         }
10650         spin_unlock_irq(&phba->hbalock);
10651 }
10652
10653 /**
10654  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
10655  * @phba: Pointer to HBA context object.
10656  *
10657  * This routine flushes the mailbox command subsystem. It will unconditionally
10658  * flush all the mailbox commands in the three possible stages in the mailbox
10659  * command sub-system: pending mailbox command queue; the outstanding mailbox
10660  * command; and completed mailbox command queue. It is caller's responsibility
10661  * to make sure that the driver is in the proper state to flush the mailbox
10662  * command sub-system. Namely, the posting of mailbox commands into the
10663  * pending mailbox command queue from the various clients must be stopped;
10664  * either the HBA is in a state that it will never works on the outstanding
10665  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
10666  * mailbox command has been completed.
10667  **/
10668 static void
10669 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
10670 {
10671         LIST_HEAD(completions);
10672         struct lpfc_sli *psli = &phba->sli;
10673         LPFC_MBOXQ_t *pmb;
10674         unsigned long iflag;
10675
10676         /* Disable softirqs, including timers from obtaining phba->hbalock */
10677         local_bh_disable();
10678
10679         /* Flush all the mailbox commands in the mbox system */
10680         spin_lock_irqsave(&phba->hbalock, iflag);
10681
10682         /* The pending mailbox command queue */
10683         list_splice_init(&phba->sli.mboxq, &completions);
10684         /* The outstanding active mailbox command */
10685         if (psli->mbox_active) {
10686                 list_add_tail(&psli->mbox_active->list, &completions);
10687                 psli->mbox_active = NULL;
10688                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10689         }
10690         /* The completed mailbox command queue */
10691         list_splice_init(&phba->sli.mboxq_cmpl, &completions);
10692         spin_unlock_irqrestore(&phba->hbalock, iflag);
10693
10694         /* Enable softirqs again, done with phba->hbalock */
10695         local_bh_enable();
10696
10697         /* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
10698         while (!list_empty(&completions)) {
10699                 list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
10700                 pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
10701                 if (pmb->mbox_cmpl)
10702                         pmb->mbox_cmpl(phba, pmb);
10703         }
10704 }
10705
10706 /**
10707  * lpfc_sli_host_down - Vport cleanup function
10708  * @vport: Pointer to virtual port object.
10709  *
10710  * lpfc_sli_host_down is called to clean up the resources
10711  * associated with a vport before destroying virtual
10712  * port data structures.
10713  * This function does following operations:
10714  * - Free discovery resources associated with this virtual
10715  *   port.
10716  * - Free iocbs associated with this virtual port in
10717  *   the txq.
10718  * - Send abort for all iocb commands associated with this
10719  *   vport in txcmplq.
10720  *
10721  * This function is called with no lock held and always returns 1.
10722  **/
10723 int
10724 lpfc_sli_host_down(struct lpfc_vport *vport)
10725 {
10726         LIST_HEAD(completions);
10727         struct lpfc_hba *phba = vport->phba;
10728         struct lpfc_sli *psli = &phba->sli;
10729         struct lpfc_queue *qp = NULL;
10730         struct lpfc_sli_ring *pring;
10731         struct lpfc_iocbq *iocb, *next_iocb;
10732         int i;
10733         unsigned long flags = 0;
10734         uint16_t prev_pring_flag;
10735
10736         lpfc_cleanup_discovery_resources(vport);
10737
10738         spin_lock_irqsave(&phba->hbalock, flags);
10739
10740         /*
10741          * Error everything on the txq since these iocbs
10742          * have not been given to the FW yet.
10743          * Also issue ABTS for everything on the txcmplq
10744          */
10745         if (phba->sli_rev != LPFC_SLI_REV4) {
10746                 for (i = 0; i < psli->num_rings; i++) {
10747                         pring = &psli->sli3_ring[i];
10748                         prev_pring_flag = pring->flag;
10749                         /* Only slow rings */
10750                         if (pring->ringno == LPFC_ELS_RING) {
10751                                 pring->flag |= LPFC_DEFERRED_RING_EVENT;
10752                                 /* Set the lpfc data pending flag */
10753                                 set_bit(LPFC_DATA_READY, &phba->data_flags);
10754                         }
10755                         list_for_each_entry_safe(iocb, next_iocb,
10756                                                  &pring->txq, list) {
10757                                 if (iocb->vport != vport)
10758                                         continue;
10759                                 list_move_tail(&iocb->list, &completions);
10760                         }
10761                         list_for_each_entry_safe(iocb, next_iocb,
10762                                                  &pring->txcmplq, list) {
10763                                 if (iocb->vport != vport)
10764                                         continue;
10765                                 lpfc_sli_issue_abort_iotag(phba, pring, iocb);
10766                         }
10767                         pring->flag = prev_pring_flag;
10768                 }
10769         } else {
10770                 list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
10771                         pring = qp->pring;
10772                         if (!pring)
10773                                 continue;
10774                         if (pring == phba->sli4_hba.els_wq->pring) {
10775                                 pring->flag |= LPFC_DEFERRED_RING_EVENT;
10776                                 /* Set the lpfc data pending flag */
10777                                 set_bit(LPFC_DATA_READY, &phba->data_flags);
10778                         }
10779                         prev_pring_flag = pring->flag;
10780                         spin_lock(&pring->ring_lock);
10781                         list_for_each_entry_safe(iocb, next_iocb,
10782                                                  &pring->txq, list) {
10783                                 if (iocb->vport != vport)
10784                                         continue;
10785                                 list_move_tail(&iocb->list, &completions);
10786                         }
10787                         spin_unlock(&pring->ring_lock);
10788                         list_for_each_entry_safe(iocb, next_iocb,
10789                                                  &pring->txcmplq, list) {
10790                                 if (iocb->vport != vport)
10791                                         continue;
10792                                 lpfc_sli_issue_abort_iotag(phba, pring, iocb);
10793                         }
10794                         pring->flag = prev_pring_flag;
10795                 }
10796         }
10797         spin_unlock_irqrestore(&phba->hbalock, flags);
10798
10799         /* Cancel all the IOCBs from the completions list */
10800         lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
10801                               IOERR_SLI_DOWN);
10802         return 1;
10803 }
10804
10805 /**
10806  * lpfc_sli_hba_down - Resource cleanup function for the HBA
10807  * @phba: Pointer to HBA context object.
10808  *
10809  * This function cleans up all iocb, buffers, mailbox commands
10810  * while shutting down the HBA. This function is called with no
10811  * lock held and always returns 1.
10812  * This function does the following to cleanup driver resources:
10813  * - Free discovery resources for each virtual port
10814  * - Cleanup any pending fabric iocbs
10815  * - Iterate through the iocb txq and free each entry
10816  *   in the list.
10817  * - Free up any buffer posted to the HBA
10818  * - Free mailbox commands in the mailbox queue.
10819  **/
10820 int
10821 lpfc_sli_hba_down(struct lpfc_hba *phba)
10822 {
10823         LIST_HEAD(completions);
10824         struct lpfc_sli *psli = &phba->sli;
10825         struct lpfc_queue *qp = NULL;
10826         struct lpfc_sli_ring *pring;
10827         struct lpfc_dmabuf *buf_ptr;
10828         unsigned long flags = 0;
10829         int i;
10830
10831         /* Shutdown the mailbox command sub-system */
10832         lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
10833
10834         lpfc_hba_down_prep(phba);
10835
10836         /* Disable softirqs, including timers from obtaining phba->hbalock */
10837         local_bh_disable();
10838
10839         lpfc_fabric_abort_hba(phba);
10840
10841         spin_lock_irqsave(&phba->hbalock, flags);
10842
10843         /*
10844          * Error everything on the txq since these iocbs
10845          * have not been given to the FW yet.
10846          */
10847         if (phba->sli_rev != LPFC_SLI_REV4) {
10848                 for (i = 0; i < psli->num_rings; i++) {
10849                         pring = &psli->sli3_ring[i];
10850                         /* Only slow rings */
10851                         if (pring->ringno == LPFC_ELS_RING) {
10852                                 pring->flag |= LPFC_DEFERRED_RING_EVENT;
10853                                 /* Set the lpfc data pending flag */
10854                                 set_bit(LPFC_DATA_READY, &phba->data_flags);
10855                         }
10856                         list_splice_init(&pring->txq, &completions);
10857                 }
10858         } else {
10859                 list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
10860                         pring = qp->pring;
10861                         if (!pring)
10862                                 continue;
10863                         spin_lock(&pring->ring_lock);
10864                         list_splice_init(&pring->txq, &completions);
10865                         spin_unlock(&pring->ring_lock);
10866                         if (pring == phba->sli4_hba.els_wq->pring) {
10867                                 pring->flag |= LPFC_DEFERRED_RING_EVENT;
10868                                 /* Set the lpfc data pending flag */
10869                                 set_bit(LPFC_DATA_READY, &phba->data_flags);
10870                         }
10871                 }
10872         }
10873         spin_unlock_irqrestore(&phba->hbalock, flags);
10874
10875         /* Cancel all the IOCBs from the completions list */
10876         lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
10877                               IOERR_SLI_DOWN);
10878
10879         spin_lock_irqsave(&phba->hbalock, flags);
10880         list_splice_init(&phba->elsbuf, &completions);
10881         phba->elsbuf_cnt = 0;
10882         phba->elsbuf_prev_cnt = 0;
10883         spin_unlock_irqrestore(&phba->hbalock, flags);
10884
10885         while (!list_empty(&completions)) {
10886                 list_remove_head(&completions, buf_ptr,
10887                         struct lpfc_dmabuf, list);
10888                 lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
10889                 kfree(buf_ptr);
10890         }
10891
10892         /* Enable softirqs again, done with phba->hbalock */
10893         local_bh_enable();
10894
10895         /* Return any active mbox cmds */
10896         del_timer_sync(&psli->mbox_tmo);
10897
10898         spin_lock_irqsave(&phba->pport->work_port_lock, flags);
10899         phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
10900         spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
10901
10902         return 1;
10903 }
10904
10905 /**
10906  * lpfc_sli_pcimem_bcopy - SLI memory copy function
10907  * @srcp: Source memory pointer.
10908  * @destp: Destination memory pointer.
10909  * @cnt: Number of words required to be copied.
10910  *
10911  * This function is used for copying data between driver memory
10912  * and the SLI memory. This function also changes the endianness
10913  * of each word if native endianness is different from SLI
10914  * endianness. This function can be called with or without
10915  * lock.
10916  **/
10917 void
10918 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
10919 {
10920         uint32_t *src = srcp;
10921         uint32_t *dest = destp;
10922         uint32_t ldata;
10923         int i;
10924
10925         for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
10926                 ldata = *src;
10927                 ldata = le32_to_cpu(ldata);
10928                 *dest = ldata;
10929                 src++;
10930                 dest++;
10931         }
10932 }
10933
10934
10935 /**
10936  * lpfc_sli_bemem_bcopy - SLI memory copy function
10937  * @srcp: Source memory pointer.
10938  * @destp: Destination memory pointer.
10939  * @cnt: Number of words required to be copied.
10940  *
10941  * This function is used for copying data between a data structure
10942  * with big endian representation to local endianness.
10943  * This function can be called with or without lock.
10944  **/
10945 void
10946 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
10947 {
10948         uint32_t *src = srcp;
10949         uint32_t *dest = destp;
10950         uint32_t ldata;
10951         int i;
10952
10953         for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
10954                 ldata = *src;
10955                 ldata = be32_to_cpu(ldata);
10956                 *dest = ldata;
10957                 src++;
10958                 dest++;
10959         }
10960 }
10961
10962 /**
10963  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
10964  * @phba: Pointer to HBA context object.
10965  * @pring: Pointer to driver SLI ring object.
10966  * @mp: Pointer to driver buffer object.
10967  *
10968  * This function is called with no lock held.
10969  * It always return zero after adding the buffer to the postbufq
10970  * buffer list.
10971  **/
10972 int
10973 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10974                          struct lpfc_dmabuf *mp)
10975 {
10976         /* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
10977            later */
10978         spin_lock_irq(&phba->hbalock);
10979         list_add_tail(&mp->list, &pring->postbufq);
10980         pring->postbufq_cnt++;
10981         spin_unlock_irq(&phba->hbalock);
10982         return 0;
10983 }
10984
10985 /**
10986  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
10987  * @phba: Pointer to HBA context object.
10988  *
10989  * When HBQ is enabled, buffers are searched based on tags. This function
10990  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
10991  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
10992  * does not conflict with tags of buffer posted for unsolicited events.
10993  * The function returns the allocated tag. The function is called with
10994  * no locks held.
10995  **/
10996 uint32_t
10997 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
10998 {
10999         spin_lock_irq(&phba->hbalock);
11000         phba->buffer_tag_count++;
11001         /*
11002          * Always set the QUE_BUFTAG_BIT to distiguish between
11003          * a tag assigned by HBQ.
11004          */
11005         phba->buffer_tag_count |= QUE_BUFTAG_BIT;
11006         spin_unlock_irq(&phba->hbalock);
11007         return phba->buffer_tag_count;
11008 }
11009
11010 /**
11011  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
11012  * @phba: Pointer to HBA context object.
11013  * @pring: Pointer to driver SLI ring object.
11014  * @tag: Buffer tag.
11015  *
11016  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
11017  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
11018  * iocb is posted to the response ring with the tag of the buffer.
11019  * This function searches the pring->postbufq list using the tag
11020  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
11021  * iocb. If the buffer is found then lpfc_dmabuf object of the
11022  * buffer is returned to the caller else NULL is returned.
11023  * This function is called with no lock held.
11024  **/
11025 struct lpfc_dmabuf *
11026 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11027                         uint32_t tag)
11028 {
11029         struct lpfc_dmabuf *mp, *next_mp;
11030         struct list_head *slp = &pring->postbufq;
11031
11032         /* Search postbufq, from the beginning, looking for a match on tag */
11033         spin_lock_irq(&phba->hbalock);
11034         list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11035                 if (mp->buffer_tag == tag) {
11036                         list_del_init(&mp->list);
11037                         pring->postbufq_cnt--;
11038                         spin_unlock_irq(&phba->hbalock);
11039                         return mp;
11040                 }
11041         }
11042
11043         spin_unlock_irq(&phba->hbalock);
11044         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11045                         "0402 Cannot find virtual addr for buffer tag on "
11046                         "ring %d Data x%lx x%px x%px x%x\n",
11047                         pring->ringno, (unsigned long) tag,
11048                         slp->next, slp->prev, pring->postbufq_cnt);
11049
11050         return NULL;
11051 }
11052
11053 /**
11054  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
11055  * @phba: Pointer to HBA context object.
11056  * @pring: Pointer to driver SLI ring object.
11057  * @phys: DMA address of the buffer.
11058  *
11059  * This function searches the buffer list using the dma_address
11060  * of unsolicited event to find the driver's lpfc_dmabuf object
11061  * corresponding to the dma_address. The function returns the
11062  * lpfc_dmabuf object if a buffer is found else it returns NULL.
11063  * This function is called by the ct and els unsolicited event
11064  * handlers to get the buffer associated with the unsolicited
11065  * event.
11066  *
11067  * This function is called with no lock held.
11068  **/
11069 struct lpfc_dmabuf *
11070 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11071                          dma_addr_t phys)
11072 {
11073         struct lpfc_dmabuf *mp, *next_mp;
11074         struct list_head *slp = &pring->postbufq;
11075
11076         /* Search postbufq, from the beginning, looking for a match on phys */
11077         spin_lock_irq(&phba->hbalock);
11078         list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
11079                 if (mp->phys == phys) {
11080                         list_del_init(&mp->list);
11081                         pring->postbufq_cnt--;
11082                         spin_unlock_irq(&phba->hbalock);
11083                         return mp;
11084                 }
11085         }
11086
11087         spin_unlock_irq(&phba->hbalock);
11088         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11089                         "0410 Cannot find virtual addr for mapped buf on "
11090                         "ring %d Data x%llx x%px x%px x%x\n",
11091                         pring->ringno, (unsigned long long)phys,
11092                         slp->next, slp->prev, pring->postbufq_cnt);
11093         return NULL;
11094 }
11095
11096 /**
11097  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
11098  * @phba: Pointer to HBA context object.
11099  * @cmdiocb: Pointer to driver command iocb object.
11100  * @rspiocb: Pointer to driver response iocb object.
11101  *
11102  * This function is the completion handler for the abort iocbs for
11103  * ELS commands. This function is called from the ELS ring event
11104  * handler with no lock held. This function frees memory resources
11105  * associated with the abort iocb.
11106  **/
11107 static void
11108 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11109                         struct lpfc_iocbq *rspiocb)
11110 {
11111         IOCB_t *irsp = &rspiocb->iocb;
11112         uint16_t abort_iotag, abort_context;
11113         struct lpfc_iocbq *abort_iocb = NULL;
11114
11115         if (irsp->ulpStatus) {
11116
11117                 /*
11118                  * Assume that the port already completed and returned, or
11119                  * will return the iocb. Just Log the message.
11120                  */
11121                 abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
11122                 abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
11123
11124                 spin_lock_irq(&phba->hbalock);
11125                 if (phba->sli_rev < LPFC_SLI_REV4) {
11126                         if (irsp->ulpCommand == CMD_ABORT_XRI_CX &&
11127                             irsp->ulpStatus == IOSTAT_LOCAL_REJECT &&
11128                             irsp->un.ulpWord[4] == IOERR_ABORT_REQUESTED) {
11129                                 spin_unlock_irq(&phba->hbalock);
11130                                 goto release_iocb;
11131                         }
11132                         if (abort_iotag != 0 &&
11133                                 abort_iotag <= phba->sli.last_iotag)
11134                                 abort_iocb =
11135                                         phba->sli.iocbq_lookup[abort_iotag];
11136                 } else
11137                         /* For sli4 the abort_tag is the XRI,
11138                          * so the abort routine puts the iotag  of the iocb
11139                          * being aborted in the context field of the abort
11140                          * IOCB.
11141                          */
11142                         abort_iocb = phba->sli.iocbq_lookup[abort_context];
11143
11144                 lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
11145                                 "0327 Cannot abort els iocb x%px "
11146                                 "with tag %x context %x, abort status %x, "
11147                                 "abort code %x\n",
11148                                 abort_iocb, abort_iotag, abort_context,
11149                                 irsp->ulpStatus, irsp->un.ulpWord[4]);
11150
11151                 spin_unlock_irq(&phba->hbalock);
11152         }
11153 release_iocb:
11154         lpfc_sli_release_iocbq(phba, cmdiocb);
11155         return;
11156 }
11157
11158 /**
11159  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
11160  * @phba: Pointer to HBA context object.
11161  * @cmdiocb: Pointer to driver command iocb object.
11162  * @rspiocb: Pointer to driver response iocb object.
11163  *
11164  * The function is called from SLI ring event handler with no
11165  * lock held. This function is the completion handler for ELS commands
11166  * which are aborted. The function frees memory resources used for
11167  * the aborted ELS commands.
11168  **/
11169 static void
11170 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11171                      struct lpfc_iocbq *rspiocb)
11172 {
11173         IOCB_t *irsp = &rspiocb->iocb;
11174
11175         /* ELS cmd tag <ulpIoTag> completes */
11176         lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
11177                         "0139 Ignoring ELS cmd tag x%x completion Data: "
11178                         "x%x x%x x%x\n",
11179                         irsp->ulpIoTag, irsp->ulpStatus,
11180                         irsp->un.ulpWord[4], irsp->ulpTimeout);
11181         if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR)
11182                 lpfc_ct_free_iocb(phba, cmdiocb);
11183         else
11184                 lpfc_els_free_iocb(phba, cmdiocb);
11185         return;
11186 }
11187
11188 /**
11189  * lpfc_sli_abort_iotag_issue - Issue abort for a command iocb
11190  * @phba: Pointer to HBA context object.
11191  * @pring: Pointer to driver SLI ring object.
11192  * @cmdiocb: Pointer to driver command iocb object.
11193  *
11194  * This function issues an abort iocb for the provided command iocb down to
11195  * the port. Other than the case the outstanding command iocb is an abort
11196  * request, this function issues abort out unconditionally. This function is
11197  * called with hbalock held. The function returns 0 when it fails due to
11198  * memory allocation failure or when the command iocb is an abort request.
11199  **/
11200 static int
11201 lpfc_sli_abort_iotag_issue(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11202                            struct lpfc_iocbq *cmdiocb)
11203 {
11204         struct lpfc_vport *vport = cmdiocb->vport;
11205         struct lpfc_iocbq *abtsiocbp;
11206         IOCB_t *icmd = NULL;
11207         IOCB_t *iabt = NULL;
11208         int retval;
11209         unsigned long iflags;
11210         struct lpfc_nodelist *ndlp;
11211
11212         lockdep_assert_held(&phba->hbalock);
11213
11214         /*
11215          * There are certain command types we don't want to abort.  And we
11216          * don't want to abort commands that are already in the process of
11217          * being aborted.
11218          */
11219         icmd = &cmdiocb->iocb;
11220         if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11221             icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
11222             (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
11223                 return 0;
11224
11225         /* issue ABTS for this IOCB based on iotag */
11226         abtsiocbp = __lpfc_sli_get_iocbq(phba);
11227         if (abtsiocbp == NULL)
11228                 return 0;
11229
11230         /* This signals the response to set the correct status
11231          * before calling the completion handler
11232          */
11233         cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
11234
11235         iabt = &abtsiocbp->iocb;
11236         iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
11237         iabt->un.acxri.abortContextTag = icmd->ulpContext;
11238         if (phba->sli_rev == LPFC_SLI_REV4) {
11239                 iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
11240                 iabt->un.acxri.abortContextTag = cmdiocb->iotag;
11241         } else {
11242                 iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
11243                 if (pring->ringno == LPFC_ELS_RING) {
11244                         ndlp = (struct lpfc_nodelist *)(cmdiocb->context1);
11245                         iabt->un.acxri.abortContextTag = ndlp->nlp_rpi;
11246                 }
11247         }
11248         iabt->ulpLe = 1;
11249         iabt->ulpClass = icmd->ulpClass;
11250
11251         /* ABTS WQE must go to the same WQ as the WQE to be aborted */
11252         abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
11253         if (cmdiocb->iocb_flag & LPFC_IO_FCP)
11254                 abtsiocbp->iocb_flag |= LPFC_USE_FCPWQIDX;
11255         if (cmdiocb->iocb_flag & LPFC_IO_FOF)
11256                 abtsiocbp->iocb_flag |= LPFC_IO_FOF;
11257
11258         if (phba->link_state >= LPFC_LINK_UP)
11259                 iabt->ulpCommand = CMD_ABORT_XRI_CN;
11260         else
11261                 iabt->ulpCommand = CMD_CLOSE_XRI_CN;
11262
11263         abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
11264         abtsiocbp->vport = vport;
11265
11266         lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
11267                          "0339 Abort xri x%x, original iotag x%x, "
11268                          "abort cmd iotag x%x\n",
11269                          iabt->un.acxri.abortIoTag,
11270                          iabt->un.acxri.abortContextTag,
11271                          abtsiocbp->iotag);
11272
11273         if (phba->sli_rev == LPFC_SLI_REV4) {
11274                 pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
11275                 if (unlikely(pring == NULL))
11276                         return 0;
11277                 /* Note: both hbalock and ring_lock need to be set here */
11278                 spin_lock_irqsave(&pring->ring_lock, iflags);
11279                 retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11280                         abtsiocbp, 0);
11281                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
11282         } else {
11283                 retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
11284                         abtsiocbp, 0);
11285         }
11286
11287         if (retval)
11288                 __lpfc_sli_release_iocbq(phba, abtsiocbp);
11289
11290         /*
11291          * Caller to this routine should check for IOCB_ERROR
11292          * and handle it properly.  This routine no longer removes
11293          * iocb off txcmplq and call compl in case of IOCB_ERROR.
11294          */
11295         return retval;
11296 }
11297
11298 /**
11299  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
11300  * @phba: Pointer to HBA context object.
11301  * @pring: Pointer to driver SLI ring object.
11302  * @cmdiocb: Pointer to driver command iocb object.
11303  *
11304  * This function issues an abort iocb for the provided command iocb. In case
11305  * of unloading, the abort iocb will not be issued to commands on the ELS
11306  * ring. Instead, the callback function shall be changed to those commands
11307  * so that nothing happens when them finishes. This function is called with
11308  * hbalock held. The function returns 0 when the command iocb is an abort
11309  * request.
11310  **/
11311 int
11312 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
11313                            struct lpfc_iocbq *cmdiocb)
11314 {
11315         struct lpfc_vport *vport = cmdiocb->vport;
11316         int retval = IOCB_ERROR;
11317         IOCB_t *icmd = NULL;
11318
11319         lockdep_assert_held(&phba->hbalock);
11320
11321         /*
11322          * There are certain command types we don't want to abort.  And we
11323          * don't want to abort commands that are already in the process of
11324          * being aborted.
11325          */
11326         icmd = &cmdiocb->iocb;
11327         if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
11328             icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
11329             (cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED) != 0)
11330                 return 0;
11331
11332         if (!pring) {
11333                 if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11334                         cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11335                 else
11336                         cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11337                 goto abort_iotag_exit;
11338         }
11339
11340         /*
11341          * If we're unloading, don't abort iocb on the ELS ring, but change
11342          * the callback so that nothing happens when it finishes.
11343          */
11344         if ((vport->load_flag & FC_UNLOADING) &&
11345             (pring->ringno == LPFC_ELS_RING)) {
11346                 if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
11347                         cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
11348                 else
11349                         cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
11350                 goto abort_iotag_exit;
11351         }
11352
11353         /* Now, we try to issue the abort to the cmdiocb out */
11354         retval = lpfc_sli_abort_iotag_issue(phba, pring, cmdiocb);
11355
11356 abort_iotag_exit:
11357         /*
11358          * Caller to this routine should check for IOCB_ERROR
11359          * and handle it properly.  This routine no longer removes
11360          * iocb off txcmplq and call compl in case of IOCB_ERROR.
11361          */
11362         return retval;
11363 }
11364
11365 /**
11366  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
11367  * @phba: pointer to lpfc HBA data structure.
11368  *
11369  * This routine will abort all pending and outstanding iocbs to an HBA.
11370  **/
11371 void
11372 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
11373 {
11374         struct lpfc_sli *psli = &phba->sli;
11375         struct lpfc_sli_ring *pring;
11376         struct lpfc_queue *qp = NULL;
11377         int i;
11378
11379         if (phba->sli_rev != LPFC_SLI_REV4) {
11380                 for (i = 0; i < psli->num_rings; i++) {
11381                         pring = &psli->sli3_ring[i];
11382                         lpfc_sli_abort_iocb_ring(phba, pring);
11383                 }
11384                 return;
11385         }
11386         list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11387                 pring = qp->pring;
11388                 if (!pring)
11389                         continue;
11390                 lpfc_sli_abort_iocb_ring(phba, pring);
11391         }
11392 }
11393
11394 /**
11395  * lpfc_sli_validate_fcp_iocb - find commands associated with a vport or LUN
11396  * @iocbq: Pointer to driver iocb object.
11397  * @vport: Pointer to driver virtual port object.
11398  * @tgt_id: SCSI ID of the target.
11399  * @lun_id: LUN ID of the scsi device.
11400  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
11401  *
11402  * This function acts as an iocb filter for functions which abort or count
11403  * all FCP iocbs pending on a lun/SCSI target/SCSI host. It will return
11404  * 0 if the filtering criteria is met for the given iocb and will return
11405  * 1 if the filtering criteria is not met.
11406  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
11407  * given iocb is for the SCSI device specified by vport, tgt_id and
11408  * lun_id parameter.
11409  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
11410  * given iocb is for the SCSI target specified by vport and tgt_id
11411  * parameters.
11412  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
11413  * given iocb is for the SCSI host associated with the given vport.
11414  * This function is called with no locks held.
11415  **/
11416 static int
11417 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
11418                            uint16_t tgt_id, uint64_t lun_id,
11419                            lpfc_ctx_cmd ctx_cmd)
11420 {
11421         struct lpfc_io_buf *lpfc_cmd;
11422         int rc = 1;
11423
11424         if (iocbq->vport != vport)
11425                 return rc;
11426
11427         if (!(iocbq->iocb_flag &  LPFC_IO_FCP) ||
11428             !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ))
11429                 return rc;
11430
11431         lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
11432
11433         if (lpfc_cmd->pCmd == NULL)
11434                 return rc;
11435
11436         switch (ctx_cmd) {
11437         case LPFC_CTX_LUN:
11438                 if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11439                     (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
11440                     (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
11441                         rc = 0;
11442                 break;
11443         case LPFC_CTX_TGT:
11444                 if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
11445                     (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
11446                         rc = 0;
11447                 break;
11448         case LPFC_CTX_HOST:
11449                 rc = 0;
11450                 break;
11451         default:
11452                 printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
11453                         __func__, ctx_cmd);
11454                 break;
11455         }
11456
11457         return rc;
11458 }
11459
11460 /**
11461  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
11462  * @vport: Pointer to virtual port.
11463  * @tgt_id: SCSI ID of the target.
11464  * @lun_id: LUN ID of the scsi device.
11465  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11466  *
11467  * This function returns number of FCP commands pending for the vport.
11468  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
11469  * commands pending on the vport associated with SCSI device specified
11470  * by tgt_id and lun_id parameters.
11471  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
11472  * commands pending on the vport associated with SCSI target specified
11473  * by tgt_id parameter.
11474  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
11475  * commands pending on the vport.
11476  * This function returns the number of iocbs which satisfy the filter.
11477  * This function is called without any lock held.
11478  **/
11479 int
11480 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
11481                   lpfc_ctx_cmd ctx_cmd)
11482 {
11483         struct lpfc_hba *phba = vport->phba;
11484         struct lpfc_iocbq *iocbq;
11485         int sum, i;
11486
11487         spin_lock_irq(&phba->hbalock);
11488         for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
11489                 iocbq = phba->sli.iocbq_lookup[i];
11490
11491                 if (lpfc_sli_validate_fcp_iocb (iocbq, vport, tgt_id, lun_id,
11492                                                 ctx_cmd) == 0)
11493                         sum++;
11494         }
11495         spin_unlock_irq(&phba->hbalock);
11496
11497         return sum;
11498 }
11499
11500 /**
11501  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
11502  * @phba: Pointer to HBA context object
11503  * @cmdiocb: Pointer to command iocb object.
11504  * @rspiocb: Pointer to response iocb object.
11505  *
11506  * This function is called when an aborted FCP iocb completes. This
11507  * function is called by the ring event handler with no lock held.
11508  * This function frees the iocb.
11509  **/
11510 void
11511 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
11512                         struct lpfc_iocbq *rspiocb)
11513 {
11514         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11515                         "3096 ABORT_XRI_CN completing on rpi x%x "
11516                         "original iotag x%x, abort cmd iotag x%x "
11517                         "status 0x%x, reason 0x%x\n",
11518                         cmdiocb->iocb.un.acxri.abortContextTag,
11519                         cmdiocb->iocb.un.acxri.abortIoTag,
11520                         cmdiocb->iotag, rspiocb->iocb.ulpStatus,
11521                         rspiocb->iocb.un.ulpWord[4]);
11522         lpfc_sli_release_iocbq(phba, cmdiocb);
11523         return;
11524 }
11525
11526 /**
11527  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
11528  * @vport: Pointer to virtual port.
11529  * @pring: Pointer to driver SLI ring object.
11530  * @tgt_id: SCSI ID of the target.
11531  * @lun_id: LUN ID of the scsi device.
11532  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11533  *
11534  * This function sends an abort command for every SCSI command
11535  * associated with the given virtual port pending on the ring
11536  * filtered by lpfc_sli_validate_fcp_iocb function.
11537  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
11538  * FCP iocbs associated with lun specified by tgt_id and lun_id
11539  * parameters
11540  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
11541  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
11542  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
11543  * FCP iocbs associated with virtual port.
11544  * This function returns number of iocbs it failed to abort.
11545  * This function is called with no locks held.
11546  **/
11547 int
11548 lpfc_sli_abort_iocb(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
11549                     uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd abort_cmd)
11550 {
11551         struct lpfc_hba *phba = vport->phba;
11552         struct lpfc_iocbq *iocbq;
11553         struct lpfc_iocbq *abtsiocb;
11554         struct lpfc_sli_ring *pring_s4;
11555         IOCB_t *cmd = NULL;
11556         int errcnt = 0, ret_val = 0;
11557         int i;
11558
11559         /* all I/Os are in process of being flushed */
11560         if (phba->hba_flag & HBA_IOQ_FLUSH)
11561                 return errcnt;
11562
11563         for (i = 1; i <= phba->sli.last_iotag; i++) {
11564                 iocbq = phba->sli.iocbq_lookup[i];
11565
11566                 if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
11567                                                abort_cmd) != 0)
11568                         continue;
11569
11570                 /*
11571                  * If the iocbq is already being aborted, don't take a second
11572                  * action, but do count it.
11573                  */
11574                 if (iocbq->iocb_flag & LPFC_DRIVER_ABORTED)
11575                         continue;
11576
11577                 /* issue ABTS for this IOCB based on iotag */
11578                 abtsiocb = lpfc_sli_get_iocbq(phba);
11579                 if (abtsiocb == NULL) {
11580                         errcnt++;
11581                         continue;
11582                 }
11583
11584                 /* indicate the IO is being aborted by the driver. */
11585                 iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
11586
11587                 cmd = &iocbq->iocb;
11588                 abtsiocb->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
11589                 abtsiocb->iocb.un.acxri.abortContextTag = cmd->ulpContext;
11590                 if (phba->sli_rev == LPFC_SLI_REV4)
11591                         abtsiocb->iocb.un.acxri.abortIoTag = iocbq->sli4_xritag;
11592                 else
11593                         abtsiocb->iocb.un.acxri.abortIoTag = cmd->ulpIoTag;
11594                 abtsiocb->iocb.ulpLe = 1;
11595                 abtsiocb->iocb.ulpClass = cmd->ulpClass;
11596                 abtsiocb->vport = vport;
11597
11598                 /* ABTS WQE must go to the same WQ as the WQE to be aborted */
11599                 abtsiocb->hba_wqidx = iocbq->hba_wqidx;
11600                 if (iocbq->iocb_flag & LPFC_IO_FCP)
11601                         abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
11602                 if (iocbq->iocb_flag & LPFC_IO_FOF)
11603                         abtsiocb->iocb_flag |= LPFC_IO_FOF;
11604
11605                 if (lpfc_is_link_up(phba))
11606                         abtsiocb->iocb.ulpCommand = CMD_ABORT_XRI_CN;
11607                 else
11608                         abtsiocb->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
11609
11610                 /* Setup callback routine and issue the command. */
11611                 abtsiocb->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
11612                 if (phba->sli_rev == LPFC_SLI_REV4) {
11613                         pring_s4 = lpfc_sli4_calc_ring(phba, iocbq);
11614                         if (!pring_s4)
11615                                 continue;
11616                         ret_val = lpfc_sli_issue_iocb(phba, pring_s4->ringno,
11617                                                       abtsiocb, 0);
11618                 } else
11619                         ret_val = lpfc_sli_issue_iocb(phba, pring->ringno,
11620                                                       abtsiocb, 0);
11621                 if (ret_val == IOCB_ERROR) {
11622                         lpfc_sli_release_iocbq(phba, abtsiocb);
11623                         errcnt++;
11624                         continue;
11625                 }
11626         }
11627
11628         return errcnt;
11629 }
11630
11631 /**
11632  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
11633  * @vport: Pointer to virtual port.
11634  * @pring: Pointer to driver SLI ring object.
11635  * @tgt_id: SCSI ID of the target.
11636  * @lun_id: LUN ID of the scsi device.
11637  * @taskmgmt_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
11638  *
11639  * This function sends an abort command for every SCSI command
11640  * associated with the given virtual port pending on the ring
11641  * filtered by lpfc_sli_validate_fcp_iocb function.
11642  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
11643  * FCP iocbs associated with lun specified by tgt_id and lun_id
11644  * parameters
11645  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
11646  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
11647  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
11648  * FCP iocbs associated with virtual port.
11649  * This function returns number of iocbs it aborted .
11650  * This function is called with no locks held right after a taskmgmt
11651  * command is sent.
11652  **/
11653 int
11654 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
11655                         uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
11656 {
11657         struct lpfc_hba *phba = vport->phba;
11658         struct lpfc_io_buf *lpfc_cmd;
11659         struct lpfc_iocbq *abtsiocbq;
11660         struct lpfc_nodelist *ndlp;
11661         struct lpfc_iocbq *iocbq;
11662         IOCB_t *icmd;
11663         int sum, i, ret_val;
11664         unsigned long iflags;
11665         struct lpfc_sli_ring *pring_s4 = NULL;
11666
11667         spin_lock_irqsave(&phba->hbalock, iflags);
11668
11669         /* all I/Os are in process of being flushed */
11670         if (phba->hba_flag & HBA_IOQ_FLUSH) {
11671                 spin_unlock_irqrestore(&phba->hbalock, iflags);
11672                 return 0;
11673         }
11674         sum = 0;
11675
11676         for (i = 1; i <= phba->sli.last_iotag; i++) {
11677                 iocbq = phba->sli.iocbq_lookup[i];
11678
11679                 if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
11680                                                cmd) != 0)
11681                         continue;
11682
11683                 /* Guard against IO completion being called at same time */
11684                 lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
11685                 spin_lock(&lpfc_cmd->buf_lock);
11686
11687                 if (!lpfc_cmd->pCmd) {
11688                         spin_unlock(&lpfc_cmd->buf_lock);
11689                         continue;
11690                 }
11691
11692                 if (phba->sli_rev == LPFC_SLI_REV4) {
11693                         pring_s4 =
11694                             phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
11695                         if (!pring_s4) {
11696                                 spin_unlock(&lpfc_cmd->buf_lock);
11697                                 continue;
11698                         }
11699                         /* Note: both hbalock and ring_lock must be set here */
11700                         spin_lock(&pring_s4->ring_lock);
11701                 }
11702
11703                 /*
11704                  * If the iocbq is already being aborted, don't take a second
11705                  * action, but do count it.
11706                  */
11707                 if ((iocbq->iocb_flag & LPFC_DRIVER_ABORTED) ||
11708                     !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ)) {
11709                         if (phba->sli_rev == LPFC_SLI_REV4)
11710                                 spin_unlock(&pring_s4->ring_lock);
11711                         spin_unlock(&lpfc_cmd->buf_lock);
11712                         continue;
11713                 }
11714
11715                 /* issue ABTS for this IOCB based on iotag */
11716                 abtsiocbq = __lpfc_sli_get_iocbq(phba);
11717                 if (!abtsiocbq) {
11718                         if (phba->sli_rev == LPFC_SLI_REV4)
11719                                 spin_unlock(&pring_s4->ring_lock);
11720                         spin_unlock(&lpfc_cmd->buf_lock);
11721                         continue;
11722                 }
11723
11724                 icmd = &iocbq->iocb;
11725                 abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
11726                 abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
11727                 if (phba->sli_rev == LPFC_SLI_REV4)
11728                         abtsiocbq->iocb.un.acxri.abortIoTag =
11729                                                          iocbq->sli4_xritag;
11730                 else
11731                         abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
11732                 abtsiocbq->iocb.ulpLe = 1;
11733                 abtsiocbq->iocb.ulpClass = icmd->ulpClass;
11734                 abtsiocbq->vport = vport;
11735
11736                 /* ABTS WQE must go to the same WQ as the WQE to be aborted */
11737                 abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
11738                 if (iocbq->iocb_flag & LPFC_IO_FCP)
11739                         abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
11740                 if (iocbq->iocb_flag & LPFC_IO_FOF)
11741                         abtsiocbq->iocb_flag |= LPFC_IO_FOF;
11742
11743                 ndlp = lpfc_cmd->rdata->pnode;
11744
11745                 if (lpfc_is_link_up(phba) &&
11746                     (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
11747                         abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
11748                 else
11749                         abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
11750
11751                 /* Setup callback routine and issue the command. */
11752                 abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
11753
11754                 /*
11755                  * Indicate the IO is being aborted by the driver and set
11756                  * the caller's flag into the aborted IO.
11757                  */
11758                 iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
11759
11760                 if (phba->sli_rev == LPFC_SLI_REV4) {
11761                         ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
11762                                                         abtsiocbq, 0);
11763                         spin_unlock(&pring_s4->ring_lock);
11764                 } else {
11765                         ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
11766                                                         abtsiocbq, 0);
11767                 }
11768
11769                 spin_unlock(&lpfc_cmd->buf_lock);
11770
11771                 if (ret_val == IOCB_ERROR)
11772                         __lpfc_sli_release_iocbq(phba, abtsiocbq);
11773                 else
11774                         sum++;
11775         }
11776         spin_unlock_irqrestore(&phba->hbalock, iflags);
11777         return sum;
11778 }
11779
11780 /**
11781  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
11782  * @phba: Pointer to HBA context object.
11783  * @cmdiocbq: Pointer to command iocb.
11784  * @rspiocbq: Pointer to response iocb.
11785  *
11786  * This function is the completion handler for iocbs issued using
11787  * lpfc_sli_issue_iocb_wait function. This function is called by the
11788  * ring event handler function without any lock held. This function
11789  * can be called from both worker thread context and interrupt
11790  * context. This function also can be called from other thread which
11791  * cleans up the SLI layer objects.
11792  * This function copy the contents of the response iocb to the
11793  * response iocb memory object provided by the caller of
11794  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
11795  * sleeps for the iocb completion.
11796  **/
11797 static void
11798 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
11799                         struct lpfc_iocbq *cmdiocbq,
11800                         struct lpfc_iocbq *rspiocbq)
11801 {
11802         wait_queue_head_t *pdone_q;
11803         unsigned long iflags;
11804         struct lpfc_io_buf *lpfc_cmd;
11805
11806         spin_lock_irqsave(&phba->hbalock, iflags);
11807         if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
11808
11809                 /*
11810                  * A time out has occurred for the iocb.  If a time out
11811                  * completion handler has been supplied, call it.  Otherwise,
11812                  * just free the iocbq.
11813                  */
11814
11815                 spin_unlock_irqrestore(&phba->hbalock, iflags);
11816                 cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
11817                 cmdiocbq->wait_iocb_cmpl = NULL;
11818                 if (cmdiocbq->iocb_cmpl)
11819                         (cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
11820                 else
11821                         lpfc_sli_release_iocbq(phba, cmdiocbq);
11822                 return;
11823         }
11824
11825         cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
11826         if (cmdiocbq->context2 && rspiocbq)
11827                 memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
11828                        &rspiocbq->iocb, sizeof(IOCB_t));
11829
11830         /* Set the exchange busy flag for task management commands */
11831         if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
11832                 !(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
11833                 lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
11834                         cur_iocbq);
11835                 if (rspiocbq && (rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY))
11836                         lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
11837                 else
11838                         lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
11839         }
11840
11841         pdone_q = cmdiocbq->context_un.wait_queue;
11842         if (pdone_q)
11843                 wake_up(pdone_q);
11844         spin_unlock_irqrestore(&phba->hbalock, iflags);
11845         return;
11846 }
11847
11848 /**
11849  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
11850  * @phba: Pointer to HBA context object..
11851  * @piocbq: Pointer to command iocb.
11852  * @flag: Flag to test.
11853  *
11854  * This routine grabs the hbalock and then test the iocb_flag to
11855  * see if the passed in flag is set.
11856  * Returns:
11857  * 1 if flag is set.
11858  * 0 if flag is not set.
11859  **/
11860 static int
11861 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
11862                  struct lpfc_iocbq *piocbq, uint32_t flag)
11863 {
11864         unsigned long iflags;
11865         int ret;
11866
11867         spin_lock_irqsave(&phba->hbalock, iflags);
11868         ret = piocbq->iocb_flag & flag;
11869         spin_unlock_irqrestore(&phba->hbalock, iflags);
11870         return ret;
11871
11872 }
11873
11874 /**
11875  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
11876  * @phba: Pointer to HBA context object..
11877  * @pring: Pointer to sli ring.
11878  * @piocb: Pointer to command iocb.
11879  * @prspiocbq: Pointer to response iocb.
11880  * @timeout: Timeout in number of seconds.
11881  *
11882  * This function issues the iocb to firmware and waits for the
11883  * iocb to complete. The iocb_cmpl field of the shall be used
11884  * to handle iocbs which time out. If the field is NULL, the
11885  * function shall free the iocbq structure.  If more clean up is
11886  * needed, the caller is expected to provide a completion function
11887  * that will provide the needed clean up.  If the iocb command is
11888  * not completed within timeout seconds, the function will either
11889  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
11890  * completion function set in the iocb_cmpl field and then return
11891  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
11892  * resources if this function returns IOCB_TIMEDOUT.
11893  * The function waits for the iocb completion using an
11894  * non-interruptible wait.
11895  * This function will sleep while waiting for iocb completion.
11896  * So, this function should not be called from any context which
11897  * does not allow sleeping. Due to the same reason, this function
11898  * cannot be called with interrupt disabled.
11899  * This function assumes that the iocb completions occur while
11900  * this function sleep. So, this function cannot be called from
11901  * the thread which process iocb completion for this ring.
11902  * This function clears the iocb_flag of the iocb object before
11903  * issuing the iocb and the iocb completion handler sets this
11904  * flag and wakes this thread when the iocb completes.
11905  * The contents of the response iocb will be copied to prspiocbq
11906  * by the completion handler when the command completes.
11907  * This function returns IOCB_SUCCESS when success.
11908  * This function is called with no lock held.
11909  **/
11910 int
11911 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
11912                          uint32_t ring_number,
11913                          struct lpfc_iocbq *piocb,
11914                          struct lpfc_iocbq *prspiocbq,
11915                          uint32_t timeout)
11916 {
11917         DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
11918         long timeleft, timeout_req = 0;
11919         int retval = IOCB_SUCCESS;
11920         uint32_t creg_val;
11921         struct lpfc_iocbq *iocb;
11922         int txq_cnt = 0;
11923         int txcmplq_cnt = 0;
11924         struct lpfc_sli_ring *pring;
11925         unsigned long iflags;
11926         bool iocb_completed = true;
11927
11928         if (phba->sli_rev >= LPFC_SLI_REV4)
11929                 pring = lpfc_sli4_calc_ring(phba, piocb);
11930         else
11931                 pring = &phba->sli.sli3_ring[ring_number];
11932         /*
11933          * If the caller has provided a response iocbq buffer, then context2
11934          * is NULL or its an error.
11935          */
11936         if (prspiocbq) {
11937                 if (piocb->context2)
11938                         return IOCB_ERROR;
11939                 piocb->context2 = prspiocbq;
11940         }
11941
11942         piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
11943         piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
11944         piocb->context_un.wait_queue = &done_q;
11945         piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
11946
11947         if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
11948                 if (lpfc_readl(phba->HCregaddr, &creg_val))
11949                         return IOCB_ERROR;
11950                 creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
11951                 writel(creg_val, phba->HCregaddr);
11952                 readl(phba->HCregaddr); /* flush */
11953         }
11954
11955         retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
11956                                      SLI_IOCB_RET_IOCB);
11957         if (retval == IOCB_SUCCESS) {
11958                 timeout_req = msecs_to_jiffies(timeout * 1000);
11959                 timeleft = wait_event_timeout(done_q,
11960                                 lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
11961                                 timeout_req);
11962                 spin_lock_irqsave(&phba->hbalock, iflags);
11963                 if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
11964
11965                         /*
11966                          * IOCB timed out.  Inform the wake iocb wait
11967                          * completion function and set local status
11968                          */
11969
11970                         iocb_completed = false;
11971                         piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
11972                 }
11973                 spin_unlock_irqrestore(&phba->hbalock, iflags);
11974                 if (iocb_completed) {
11975                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11976                                         "0331 IOCB wake signaled\n");
11977                         /* Note: we are not indicating if the IOCB has a success
11978                          * status or not - that's for the caller to check.
11979                          * IOCB_SUCCESS means just that the command was sent and
11980                          * completed. Not that it completed successfully.
11981                          * */
11982                 } else if (timeleft == 0) {
11983                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11984                                         "0338 IOCB wait timeout error - no "
11985                                         "wake response Data x%x\n", timeout);
11986                         retval = IOCB_TIMEDOUT;
11987                 } else {
11988                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
11989                                         "0330 IOCB wake NOT set, "
11990                                         "Data x%x x%lx\n",
11991                                         timeout, (timeleft / jiffies));
11992                         retval = IOCB_TIMEDOUT;
11993                 }
11994         } else if (retval == IOCB_BUSY) {
11995                 if (phba->cfg_log_verbose & LOG_SLI) {
11996                         list_for_each_entry(iocb, &pring->txq, list) {
11997                                 txq_cnt++;
11998                         }
11999                         list_for_each_entry(iocb, &pring->txcmplq, list) {
12000                                 txcmplq_cnt++;
12001                         }
12002                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12003                                 "2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
12004                                 phba->iocb_cnt, txq_cnt, txcmplq_cnt);
12005                 }
12006                 return retval;
12007         } else {
12008                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12009                                 "0332 IOCB wait issue failed, Data x%x\n",
12010                                 retval);
12011                 retval = IOCB_ERROR;
12012         }
12013
12014         if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
12015                 if (lpfc_readl(phba->HCregaddr, &creg_val))
12016                         return IOCB_ERROR;
12017                 creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
12018                 writel(creg_val, phba->HCregaddr);
12019                 readl(phba->HCregaddr); /* flush */
12020         }
12021
12022         if (prspiocbq)
12023                 piocb->context2 = NULL;
12024
12025         piocb->context_un.wait_queue = NULL;
12026         piocb->iocb_cmpl = NULL;
12027         return retval;
12028 }
12029
12030 /**
12031  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
12032  * @phba: Pointer to HBA context object.
12033  * @pmboxq: Pointer to driver mailbox object.
12034  * @timeout: Timeout in number of seconds.
12035  *
12036  * This function issues the mailbox to firmware and waits for the
12037  * mailbox command to complete. If the mailbox command is not
12038  * completed within timeout seconds, it returns MBX_TIMEOUT.
12039  * The function waits for the mailbox completion using an
12040  * interruptible wait. If the thread is woken up due to a
12041  * signal, MBX_TIMEOUT error is returned to the caller. Caller
12042  * should not free the mailbox resources, if this function returns
12043  * MBX_TIMEOUT.
12044  * This function will sleep while waiting for mailbox completion.
12045  * So, this function should not be called from any context which
12046  * does not allow sleeping. Due to the same reason, this function
12047  * cannot be called with interrupt disabled.
12048  * This function assumes that the mailbox completion occurs while
12049  * this function sleep. So, this function cannot be called from
12050  * the worker thread which processes mailbox completion.
12051  * This function is called in the context of HBA management
12052  * applications.
12053  * This function returns MBX_SUCCESS when successful.
12054  * This function is called with no lock held.
12055  **/
12056 int
12057 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
12058                          uint32_t timeout)
12059 {
12060         struct completion mbox_done;
12061         int retval;
12062         unsigned long flag;
12063
12064         pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
12065         /* setup wake call as IOCB callback */
12066         pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
12067
12068         /* setup context3 field to pass wait_queue pointer to wake function  */
12069         init_completion(&mbox_done);
12070         pmboxq->context3 = &mbox_done;
12071         /* now issue the command */
12072         retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
12073         if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
12074                 wait_for_completion_timeout(&mbox_done,
12075                                             msecs_to_jiffies(timeout * 1000));
12076
12077                 spin_lock_irqsave(&phba->hbalock, flag);
12078                 pmboxq->context3 = NULL;
12079                 /*
12080                  * if LPFC_MBX_WAKE flag is set the mailbox is completed
12081                  * else do not free the resources.
12082                  */
12083                 if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
12084                         retval = MBX_SUCCESS;
12085                 } else {
12086                         retval = MBX_TIMEOUT;
12087                         pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
12088                 }
12089                 spin_unlock_irqrestore(&phba->hbalock, flag);
12090         }
12091         return retval;
12092 }
12093
12094 /**
12095  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
12096  * @phba: Pointer to HBA context.
12097  *
12098  * This function is called to shutdown the driver's mailbox sub-system.
12099  * It first marks the mailbox sub-system is in a block state to prevent
12100  * the asynchronous mailbox command from issued off the pending mailbox
12101  * command queue. If the mailbox command sub-system shutdown is due to
12102  * HBA error conditions such as EEH or ERATT, this routine shall invoke
12103  * the mailbox sub-system flush routine to forcefully bring down the
12104  * mailbox sub-system. Otherwise, if it is due to normal condition (such
12105  * as with offline or HBA function reset), this routine will wait for the
12106  * outstanding mailbox command to complete before invoking the mailbox
12107  * sub-system flush routine to gracefully bring down mailbox sub-system.
12108  **/
12109 void
12110 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
12111 {
12112         struct lpfc_sli *psli = &phba->sli;
12113         unsigned long timeout;
12114
12115         if (mbx_action == LPFC_MBX_NO_WAIT) {
12116                 /* delay 100ms for port state */
12117                 msleep(100);
12118                 lpfc_sli_mbox_sys_flush(phba);
12119                 return;
12120         }
12121         timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
12122
12123         /* Disable softirqs, including timers from obtaining phba->hbalock */
12124         local_bh_disable();
12125
12126         spin_lock_irq(&phba->hbalock);
12127         psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
12128
12129         if (psli->sli_flag & LPFC_SLI_ACTIVE) {
12130                 /* Determine how long we might wait for the active mailbox
12131                  * command to be gracefully completed by firmware.
12132                  */
12133                 if (phba->sli.mbox_active)
12134                         timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
12135                                                 phba->sli.mbox_active) *
12136                                                 1000) + jiffies;
12137                 spin_unlock_irq(&phba->hbalock);
12138
12139                 /* Enable softirqs again, done with phba->hbalock */
12140                 local_bh_enable();
12141
12142                 while (phba->sli.mbox_active) {
12143                         /* Check active mailbox complete status every 2ms */
12144                         msleep(2);
12145                         if (time_after(jiffies, timeout))
12146                                 /* Timeout, let the mailbox flush routine to
12147                                  * forcefully release active mailbox command
12148                                  */
12149                                 break;
12150                 }
12151         } else {
12152                 spin_unlock_irq(&phba->hbalock);
12153
12154                 /* Enable softirqs again, done with phba->hbalock */
12155                 local_bh_enable();
12156         }
12157
12158         lpfc_sli_mbox_sys_flush(phba);
12159 }
12160
12161 /**
12162  * lpfc_sli_eratt_read - read sli-3 error attention events
12163  * @phba: Pointer to HBA context.
12164  *
12165  * This function is called to read the SLI3 device error attention registers
12166  * for possible error attention events. The caller must hold the hostlock
12167  * with spin_lock_irq().
12168  *
12169  * This function returns 1 when there is Error Attention in the Host Attention
12170  * Register and returns 0 otherwise.
12171  **/
12172 static int
12173 lpfc_sli_eratt_read(struct lpfc_hba *phba)
12174 {
12175         uint32_t ha_copy;
12176
12177         /* Read chip Host Attention (HA) register */
12178         if (lpfc_readl(phba->HAregaddr, &ha_copy))
12179                 goto unplug_err;
12180
12181         if (ha_copy & HA_ERATT) {
12182                 /* Read host status register to retrieve error event */
12183                 if (lpfc_sli_read_hs(phba))
12184                         goto unplug_err;
12185
12186                 /* Check if there is a deferred error condition is active */
12187                 if ((HS_FFER1 & phba->work_hs) &&
12188                     ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12189                       HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
12190                         phba->hba_flag |= DEFER_ERATT;
12191                         /* Clear all interrupt enable conditions */
12192                         writel(0, phba->HCregaddr);
12193                         readl(phba->HCregaddr);
12194                 }
12195
12196                 /* Set the driver HA work bitmap */
12197                 phba->work_ha |= HA_ERATT;
12198                 /* Indicate polling handles this ERATT */
12199                 phba->hba_flag |= HBA_ERATT_HANDLED;
12200                 return 1;
12201         }
12202         return 0;
12203
12204 unplug_err:
12205         /* Set the driver HS work bitmap */
12206         phba->work_hs |= UNPLUG_ERR;
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
12214 /**
12215  * lpfc_sli4_eratt_read - read sli-4 error attention events
12216  * @phba: Pointer to HBA context.
12217  *
12218  * This function is called to read the SLI4 device error attention registers
12219  * for possible error attention events. The caller must hold the hostlock
12220  * with spin_lock_irq().
12221  *
12222  * This function returns 1 when there is Error Attention in the Host Attention
12223  * Register and returns 0 otherwise.
12224  **/
12225 static int
12226 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
12227 {
12228         uint32_t uerr_sta_hi, uerr_sta_lo;
12229         uint32_t if_type, portsmphr;
12230         struct lpfc_register portstat_reg;
12231
12232         /*
12233          * For now, use the SLI4 device internal unrecoverable error
12234          * registers for error attention. This can be changed later.
12235          */
12236         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
12237         switch (if_type) {
12238         case LPFC_SLI_INTF_IF_TYPE_0:
12239                 if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
12240                         &uerr_sta_lo) ||
12241                         lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
12242                         &uerr_sta_hi)) {
12243                         phba->work_hs |= UNPLUG_ERR;
12244                         phba->work_ha |= HA_ERATT;
12245                         phba->hba_flag |= HBA_ERATT_HANDLED;
12246                         return 1;
12247                 }
12248                 if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
12249                     (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
12250                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12251                                         "1423 HBA Unrecoverable error: "
12252                                         "uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
12253                                         "ue_mask_lo_reg=0x%x, "
12254                                         "ue_mask_hi_reg=0x%x\n",
12255                                         uerr_sta_lo, uerr_sta_hi,
12256                                         phba->sli4_hba.ue_mask_lo,
12257                                         phba->sli4_hba.ue_mask_hi);
12258                         phba->work_status[0] = uerr_sta_lo;
12259                         phba->work_status[1] = uerr_sta_hi;
12260                         phba->work_ha |= HA_ERATT;
12261                         phba->hba_flag |= HBA_ERATT_HANDLED;
12262                         return 1;
12263                 }
12264                 break;
12265         case LPFC_SLI_INTF_IF_TYPE_2:
12266         case LPFC_SLI_INTF_IF_TYPE_6:
12267                 if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
12268                         &portstat_reg.word0) ||
12269                         lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
12270                         &portsmphr)){
12271                         phba->work_hs |= UNPLUG_ERR;
12272                         phba->work_ha |= HA_ERATT;
12273                         phba->hba_flag |= HBA_ERATT_HANDLED;
12274                         return 1;
12275                 }
12276                 if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
12277                         phba->work_status[0] =
12278                                 readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
12279                         phba->work_status[1] =
12280                                 readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
12281                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12282                                         "2885 Port Status Event: "
12283                                         "port status reg 0x%x, "
12284                                         "port smphr reg 0x%x, "
12285                                         "error 1=0x%x, error 2=0x%x\n",
12286                                         portstat_reg.word0,
12287                                         portsmphr,
12288                                         phba->work_status[0],
12289                                         phba->work_status[1]);
12290                         phba->work_ha |= HA_ERATT;
12291                         phba->hba_flag |= HBA_ERATT_HANDLED;
12292                         return 1;
12293                 }
12294                 break;
12295         case LPFC_SLI_INTF_IF_TYPE_1:
12296         default:
12297                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12298                                 "2886 HBA Error Attention on unsupported "
12299                                 "if type %d.", if_type);
12300                 return 1;
12301         }
12302
12303         return 0;
12304 }
12305
12306 /**
12307  * lpfc_sli_check_eratt - check error attention events
12308  * @phba: Pointer to HBA context.
12309  *
12310  * This function is called from timer soft interrupt context to check HBA's
12311  * error attention register bit for error attention events.
12312  *
12313  * This function returns 1 when there is Error Attention in the Host Attention
12314  * Register and returns 0 otherwise.
12315  **/
12316 int
12317 lpfc_sli_check_eratt(struct lpfc_hba *phba)
12318 {
12319         uint32_t ha_copy;
12320
12321         /* If somebody is waiting to handle an eratt, don't process it
12322          * here. The brdkill function will do this.
12323          */
12324         if (phba->link_flag & LS_IGNORE_ERATT)
12325                 return 0;
12326
12327         /* Check if interrupt handler handles this ERATT */
12328         spin_lock_irq(&phba->hbalock);
12329         if (phba->hba_flag & HBA_ERATT_HANDLED) {
12330                 /* Interrupt handler has handled ERATT */
12331                 spin_unlock_irq(&phba->hbalock);
12332                 return 0;
12333         }
12334
12335         /*
12336          * If there is deferred error attention, do not check for error
12337          * attention
12338          */
12339         if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12340                 spin_unlock_irq(&phba->hbalock);
12341                 return 0;
12342         }
12343
12344         /* If PCI channel is offline, don't process it */
12345         if (unlikely(pci_channel_offline(phba->pcidev))) {
12346                 spin_unlock_irq(&phba->hbalock);
12347                 return 0;
12348         }
12349
12350         switch (phba->sli_rev) {
12351         case LPFC_SLI_REV2:
12352         case LPFC_SLI_REV3:
12353                 /* Read chip Host Attention (HA) register */
12354                 ha_copy = lpfc_sli_eratt_read(phba);
12355                 break;
12356         case LPFC_SLI_REV4:
12357                 /* Read device Uncoverable Error (UERR) registers */
12358                 ha_copy = lpfc_sli4_eratt_read(phba);
12359                 break;
12360         default:
12361                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
12362                                 "0299 Invalid SLI revision (%d)\n",
12363                                 phba->sli_rev);
12364                 ha_copy = 0;
12365                 break;
12366         }
12367         spin_unlock_irq(&phba->hbalock);
12368
12369         return ha_copy;
12370 }
12371
12372 /**
12373  * lpfc_intr_state_check - Check device state for interrupt handling
12374  * @phba: Pointer to HBA context.
12375  *
12376  * This inline routine checks whether a device or its PCI slot is in a state
12377  * that the interrupt should be handled.
12378  *
12379  * This function returns 0 if the device or the PCI slot is in a state that
12380  * interrupt should be handled, otherwise -EIO.
12381  */
12382 static inline int
12383 lpfc_intr_state_check(struct lpfc_hba *phba)
12384 {
12385         /* If the pci channel is offline, ignore all the interrupts */
12386         if (unlikely(pci_channel_offline(phba->pcidev)))
12387                 return -EIO;
12388
12389         /* Update device level interrupt statistics */
12390         phba->sli.slistat.sli_intr++;
12391
12392         /* Ignore all interrupts during initialization. */
12393         if (unlikely(phba->link_state < LPFC_LINK_DOWN))
12394                 return -EIO;
12395
12396         return 0;
12397 }
12398
12399 /**
12400  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
12401  * @irq: Interrupt number.
12402  * @dev_id: The device context pointer.
12403  *
12404  * This function is directly called from the PCI layer as an interrupt
12405  * service routine when device with SLI-3 interface spec is enabled with
12406  * MSI-X multi-message interrupt mode and there are slow-path events in
12407  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
12408  * interrupt mode, this function is called as part of the device-level
12409  * interrupt handler. When the PCI slot is in error recovery or the HBA
12410  * is undergoing initialization, the interrupt handler will not process
12411  * the interrupt. The link attention and ELS ring attention events are
12412  * handled by the worker thread. The interrupt handler signals the worker
12413  * thread and returns for these events. This function is called without
12414  * any lock held. It gets the hbalock to access and update SLI data
12415  * structures.
12416  *
12417  * This function returns IRQ_HANDLED when interrupt is handled else it
12418  * returns IRQ_NONE.
12419  **/
12420 irqreturn_t
12421 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
12422 {
12423         struct lpfc_hba  *phba;
12424         uint32_t ha_copy, hc_copy;
12425         uint32_t work_ha_copy;
12426         unsigned long status;
12427         unsigned long iflag;
12428         uint32_t control;
12429
12430         MAILBOX_t *mbox, *pmbox;
12431         struct lpfc_vport *vport;
12432         struct lpfc_nodelist *ndlp;
12433         struct lpfc_dmabuf *mp;
12434         LPFC_MBOXQ_t *pmb;
12435         int rc;
12436
12437         /*
12438          * Get the driver's phba structure from the dev_id and
12439          * assume the HBA is not interrupting.
12440          */
12441         phba = (struct lpfc_hba *)dev_id;
12442
12443         if (unlikely(!phba))
12444                 return IRQ_NONE;
12445
12446         /*
12447          * Stuff needs to be attented to when this function is invoked as an
12448          * individual interrupt handler in MSI-X multi-message interrupt mode
12449          */
12450         if (phba->intr_type == MSIX) {
12451                 /* Check device state for handling interrupt */
12452                 if (lpfc_intr_state_check(phba))
12453                         return IRQ_NONE;
12454                 /* Need to read HA REG for slow-path events */
12455                 spin_lock_irqsave(&phba->hbalock, iflag);
12456                 if (lpfc_readl(phba->HAregaddr, &ha_copy))
12457                         goto unplug_error;
12458                 /* If somebody is waiting to handle an eratt don't process it
12459                  * here. The brdkill function will do this.
12460                  */
12461                 if (phba->link_flag & LS_IGNORE_ERATT)
12462                         ha_copy &= ~HA_ERATT;
12463                 /* Check the need for handling ERATT in interrupt handler */
12464                 if (ha_copy & HA_ERATT) {
12465                         if (phba->hba_flag & HBA_ERATT_HANDLED)
12466                                 /* ERATT polling has handled ERATT */
12467                                 ha_copy &= ~HA_ERATT;
12468                         else
12469                                 /* Indicate interrupt handler handles ERATT */
12470                                 phba->hba_flag |= HBA_ERATT_HANDLED;
12471                 }
12472
12473                 /*
12474                  * If there is deferred error attention, do not check for any
12475                  * interrupt.
12476                  */
12477                 if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12478                         spin_unlock_irqrestore(&phba->hbalock, iflag);
12479                         return IRQ_NONE;
12480                 }
12481
12482                 /* Clear up only attention source related to slow-path */
12483                 if (lpfc_readl(phba->HCregaddr, &hc_copy))
12484                         goto unplug_error;
12485
12486                 writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
12487                         HC_LAINT_ENA | HC_ERINT_ENA),
12488                         phba->HCregaddr);
12489                 writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
12490                         phba->HAregaddr);
12491                 writel(hc_copy, phba->HCregaddr);
12492                 readl(phba->HAregaddr); /* flush */
12493                 spin_unlock_irqrestore(&phba->hbalock, iflag);
12494         } else
12495                 ha_copy = phba->ha_copy;
12496
12497         work_ha_copy = ha_copy & phba->work_ha_mask;
12498
12499         if (work_ha_copy) {
12500                 if (work_ha_copy & HA_LATT) {
12501                         if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
12502                                 /*
12503                                  * Turn off Link Attention interrupts
12504                                  * until CLEAR_LA done
12505                                  */
12506                                 spin_lock_irqsave(&phba->hbalock, iflag);
12507                                 phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
12508                                 if (lpfc_readl(phba->HCregaddr, &control))
12509                                         goto unplug_error;
12510                                 control &= ~HC_LAINT_ENA;
12511                                 writel(control, phba->HCregaddr);
12512                                 readl(phba->HCregaddr); /* flush */
12513                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
12514                         }
12515                         else
12516                                 work_ha_copy &= ~HA_LATT;
12517                 }
12518
12519                 if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
12520                         /*
12521                          * Turn off Slow Rings interrupts, LPFC_ELS_RING is
12522                          * the only slow ring.
12523                          */
12524                         status = (work_ha_copy &
12525                                 (HA_RXMASK  << (4*LPFC_ELS_RING)));
12526                         status >>= (4*LPFC_ELS_RING);
12527                         if (status & HA_RXMASK) {
12528                                 spin_lock_irqsave(&phba->hbalock, iflag);
12529                                 if (lpfc_readl(phba->HCregaddr, &control))
12530                                         goto unplug_error;
12531
12532                                 lpfc_debugfs_slow_ring_trc(phba,
12533                                 "ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
12534                                 control, status,
12535                                 (uint32_t)phba->sli.slistat.sli_intr);
12536
12537                                 if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
12538                                         lpfc_debugfs_slow_ring_trc(phba,
12539                                                 "ISR Disable ring:"
12540                                                 "pwork:x%x hawork:x%x wait:x%x",
12541                                                 phba->work_ha, work_ha_copy,
12542                                                 (uint32_t)((unsigned long)
12543                                                 &phba->work_waitq));
12544
12545                                         control &=
12546                                             ~(HC_R0INT_ENA << LPFC_ELS_RING);
12547                                         writel(control, phba->HCregaddr);
12548                                         readl(phba->HCregaddr); /* flush */
12549                                 }
12550                                 else {
12551                                         lpfc_debugfs_slow_ring_trc(phba,
12552                                                 "ISR slow ring:   pwork:"
12553                                                 "x%x hawork:x%x wait:x%x",
12554                                                 phba->work_ha, work_ha_copy,
12555                                                 (uint32_t)((unsigned long)
12556                                                 &phba->work_waitq));
12557                                 }
12558                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
12559                         }
12560                 }
12561                 spin_lock_irqsave(&phba->hbalock, iflag);
12562                 if (work_ha_copy & HA_ERATT) {
12563                         if (lpfc_sli_read_hs(phba))
12564                                 goto unplug_error;
12565                         /*
12566                          * Check if there is a deferred error condition
12567                          * is active
12568                          */
12569                         if ((HS_FFER1 & phba->work_hs) &&
12570                                 ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
12571                                   HS_FFER6 | HS_FFER7 | HS_FFER8) &
12572                                   phba->work_hs)) {
12573                                 phba->hba_flag |= DEFER_ERATT;
12574                                 /* Clear all interrupt enable conditions */
12575                                 writel(0, phba->HCregaddr);
12576                                 readl(phba->HCregaddr);
12577                         }
12578                 }
12579
12580                 if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
12581                         pmb = phba->sli.mbox_active;
12582                         pmbox = &pmb->u.mb;
12583                         mbox = phba->mbox;
12584                         vport = pmb->vport;
12585
12586                         /* First check out the status word */
12587                         lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
12588                         if (pmbox->mbxOwner != OWN_HOST) {
12589                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
12590                                 /*
12591                                  * Stray Mailbox Interrupt, mbxCommand <cmd>
12592                                  * mbxStatus <status>
12593                                  */
12594                                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
12595                                                 LOG_SLI,
12596                                                 "(%d):0304 Stray Mailbox "
12597                                                 "Interrupt mbxCommand x%x "
12598                                                 "mbxStatus x%x\n",
12599                                                 (vport ? vport->vpi : 0),
12600                                                 pmbox->mbxCommand,
12601                                                 pmbox->mbxStatus);
12602                                 /* clear mailbox attention bit */
12603                                 work_ha_copy &= ~HA_MBATT;
12604                         } else {
12605                                 phba->sli.mbox_active = NULL;
12606                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
12607                                 phba->last_completion_time = jiffies;
12608                                 del_timer(&phba->sli.mbox_tmo);
12609                                 if (pmb->mbox_cmpl) {
12610                                         lpfc_sli_pcimem_bcopy(mbox, pmbox,
12611                                                         MAILBOX_CMD_SIZE);
12612                                         if (pmb->out_ext_byte_len &&
12613                                                 pmb->ctx_buf)
12614                                                 lpfc_sli_pcimem_bcopy(
12615                                                 phba->mbox_ext,
12616                                                 pmb->ctx_buf,
12617                                                 pmb->out_ext_byte_len);
12618                                 }
12619                                 if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
12620                                         pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
12621
12622                                         lpfc_debugfs_disc_trc(vport,
12623                                                 LPFC_DISC_TRC_MBOX_VPORT,
12624                                                 "MBOX dflt rpi: : "
12625                                                 "status:x%x rpi:x%x",
12626                                                 (uint32_t)pmbox->mbxStatus,
12627                                                 pmbox->un.varWords[0], 0);
12628
12629                                         if (!pmbox->mbxStatus) {
12630                                                 mp = (struct lpfc_dmabuf *)
12631                                                         (pmb->ctx_buf);
12632                                                 ndlp = (struct lpfc_nodelist *)
12633                                                         pmb->ctx_ndlp;
12634
12635                                                 /* Reg_LOGIN of dflt RPI was
12636                                                  * successful. new lets get
12637                                                  * rid of the RPI using the
12638                                                  * same mbox buffer.
12639                                                  */
12640                                                 lpfc_unreg_login(phba,
12641                                                         vport->vpi,
12642                                                         pmbox->un.varWords[0],
12643                                                         pmb);
12644                                                 pmb->mbox_cmpl =
12645                                                         lpfc_mbx_cmpl_dflt_rpi;
12646                                                 pmb->ctx_buf = mp;
12647                                                 pmb->ctx_ndlp = ndlp;
12648                                                 pmb->vport = vport;
12649                                                 rc = lpfc_sli_issue_mbox(phba,
12650                                                                 pmb,
12651                                                                 MBX_NOWAIT);
12652                                                 if (rc != MBX_BUSY)
12653                                                         lpfc_printf_log(phba,
12654                                                         KERN_ERR,
12655                                                         LOG_MBOX | LOG_SLI,
12656                                                         "0350 rc should have"
12657                                                         "been MBX_BUSY\n");
12658                                                 if (rc != MBX_NOT_FINISHED)
12659                                                         goto send_current_mbox;
12660                                         }
12661                                 }
12662                                 spin_lock_irqsave(
12663                                                 &phba->pport->work_port_lock,
12664                                                 iflag);
12665                                 phba->pport->work_port_events &=
12666                                         ~WORKER_MBOX_TMO;
12667                                 spin_unlock_irqrestore(
12668                                                 &phba->pport->work_port_lock,
12669                                                 iflag);
12670                                 lpfc_mbox_cmpl_put(phba, pmb);
12671                         }
12672                 } else
12673                         spin_unlock_irqrestore(&phba->hbalock, iflag);
12674
12675                 if ((work_ha_copy & HA_MBATT) &&
12676                     (phba->sli.mbox_active == NULL)) {
12677 send_current_mbox:
12678                         /* Process next mailbox command if there is one */
12679                         do {
12680                                 rc = lpfc_sli_issue_mbox(phba, NULL,
12681                                                          MBX_NOWAIT);
12682                         } while (rc == MBX_NOT_FINISHED);
12683                         if (rc != MBX_SUCCESS)
12684                                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
12685                                                 LOG_SLI, "0349 rc should be "
12686                                                 "MBX_SUCCESS\n");
12687                 }
12688
12689                 spin_lock_irqsave(&phba->hbalock, iflag);
12690                 phba->work_ha |= work_ha_copy;
12691                 spin_unlock_irqrestore(&phba->hbalock, iflag);
12692                 lpfc_worker_wake_up(phba);
12693         }
12694         return IRQ_HANDLED;
12695 unplug_error:
12696         spin_unlock_irqrestore(&phba->hbalock, iflag);
12697         return IRQ_HANDLED;
12698
12699 } /* lpfc_sli_sp_intr_handler */
12700
12701 /**
12702  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
12703  * @irq: Interrupt number.
12704  * @dev_id: The device context pointer.
12705  *
12706  * This function is directly called from the PCI layer as an interrupt
12707  * service routine when device with SLI-3 interface spec is enabled with
12708  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
12709  * ring event in the HBA. However, when the device is enabled with either
12710  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
12711  * device-level interrupt handler. When the PCI slot is in error recovery
12712  * or the HBA is undergoing initialization, the interrupt handler will not
12713  * process the interrupt. The SCSI FCP fast-path ring event are handled in
12714  * the intrrupt context. This function is called without any lock held.
12715  * It gets the hbalock to access and update SLI data structures.
12716  *
12717  * This function returns IRQ_HANDLED when interrupt is handled else it
12718  * returns IRQ_NONE.
12719  **/
12720 irqreturn_t
12721 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
12722 {
12723         struct lpfc_hba  *phba;
12724         uint32_t ha_copy;
12725         unsigned long status;
12726         unsigned long iflag;
12727         struct lpfc_sli_ring *pring;
12728
12729         /* Get the driver's phba structure from the dev_id and
12730          * assume the HBA is not interrupting.
12731          */
12732         phba = (struct lpfc_hba *) dev_id;
12733
12734         if (unlikely(!phba))
12735                 return IRQ_NONE;
12736
12737         /*
12738          * Stuff needs to be attented to when this function is invoked as an
12739          * individual interrupt handler in MSI-X multi-message interrupt mode
12740          */
12741         if (phba->intr_type == MSIX) {
12742                 /* Check device state for handling interrupt */
12743                 if (lpfc_intr_state_check(phba))
12744                         return IRQ_NONE;
12745                 /* Need to read HA REG for FCP ring and other ring events */
12746                 if (lpfc_readl(phba->HAregaddr, &ha_copy))
12747                         return IRQ_HANDLED;
12748                 /* Clear up only attention source related to fast-path */
12749                 spin_lock_irqsave(&phba->hbalock, iflag);
12750                 /*
12751                  * If there is deferred error attention, do not check for
12752                  * any interrupt.
12753                  */
12754                 if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12755                         spin_unlock_irqrestore(&phba->hbalock, iflag);
12756                         return IRQ_NONE;
12757                 }
12758                 writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
12759                         phba->HAregaddr);
12760                 readl(phba->HAregaddr); /* flush */
12761                 spin_unlock_irqrestore(&phba->hbalock, iflag);
12762         } else
12763                 ha_copy = phba->ha_copy;
12764
12765         /*
12766          * Process all events on FCP ring. Take the optimized path for FCP IO.
12767          */
12768         ha_copy &= ~(phba->work_ha_mask);
12769
12770         status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
12771         status >>= (4*LPFC_FCP_RING);
12772         pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12773         if (status & HA_RXMASK)
12774                 lpfc_sli_handle_fast_ring_event(phba, pring, status);
12775
12776         if (phba->cfg_multi_ring_support == 2) {
12777                 /*
12778                  * Process all events on extra ring. Take the optimized path
12779                  * for extra ring IO.
12780                  */
12781                 status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
12782                 status >>= (4*LPFC_EXTRA_RING);
12783                 if (status & HA_RXMASK) {
12784                         lpfc_sli_handle_fast_ring_event(phba,
12785                                         &phba->sli.sli3_ring[LPFC_EXTRA_RING],
12786                                         status);
12787                 }
12788         }
12789         return IRQ_HANDLED;
12790 }  /* lpfc_sli_fp_intr_handler */
12791
12792 /**
12793  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
12794  * @irq: Interrupt number.
12795  * @dev_id: The device context pointer.
12796  *
12797  * This function is the HBA device-level interrupt handler to device with
12798  * SLI-3 interface spec, called from the PCI layer when either MSI or
12799  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
12800  * requires driver attention. This function invokes the slow-path interrupt
12801  * attention handling function and fast-path interrupt attention handling
12802  * function in turn to process the relevant HBA attention events. This
12803  * function is called without any lock held. It gets the hbalock to access
12804  * and update SLI data structures.
12805  *
12806  * This function returns IRQ_HANDLED when interrupt is handled, else it
12807  * returns IRQ_NONE.
12808  **/
12809 irqreturn_t
12810 lpfc_sli_intr_handler(int irq, void *dev_id)
12811 {
12812         struct lpfc_hba  *phba;
12813         irqreturn_t sp_irq_rc, fp_irq_rc;
12814         unsigned long status1, status2;
12815         uint32_t hc_copy;
12816
12817         /*
12818          * Get the driver's phba structure from the dev_id and
12819          * assume the HBA is not interrupting.
12820          */
12821         phba = (struct lpfc_hba *) dev_id;
12822
12823         if (unlikely(!phba))
12824                 return IRQ_NONE;
12825
12826         /* Check device state for handling interrupt */
12827         if (lpfc_intr_state_check(phba))
12828                 return IRQ_NONE;
12829
12830         spin_lock(&phba->hbalock);
12831         if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
12832                 spin_unlock(&phba->hbalock);
12833                 return IRQ_HANDLED;
12834         }
12835
12836         if (unlikely(!phba->ha_copy)) {
12837                 spin_unlock(&phba->hbalock);
12838                 return IRQ_NONE;
12839         } else if (phba->ha_copy & HA_ERATT) {
12840                 if (phba->hba_flag & HBA_ERATT_HANDLED)
12841                         /* ERATT polling has handled ERATT */
12842                         phba->ha_copy &= ~HA_ERATT;
12843                 else
12844                         /* Indicate interrupt handler handles ERATT */
12845                         phba->hba_flag |= HBA_ERATT_HANDLED;
12846         }
12847
12848         /*
12849          * If there is deferred error attention, do not check for any interrupt.
12850          */
12851         if (unlikely(phba->hba_flag & DEFER_ERATT)) {
12852                 spin_unlock(&phba->hbalock);
12853                 return IRQ_NONE;
12854         }
12855
12856         /* Clear attention sources except link and error attentions */
12857         if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
12858                 spin_unlock(&phba->hbalock);
12859                 return IRQ_HANDLED;
12860         }
12861         writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
12862                 | HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
12863                 phba->HCregaddr);
12864         writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
12865         writel(hc_copy, phba->HCregaddr);
12866         readl(phba->HAregaddr); /* flush */
12867         spin_unlock(&phba->hbalock);
12868
12869         /*
12870          * Invokes slow-path host attention interrupt handling as appropriate.
12871          */
12872
12873         /* status of events with mailbox and link attention */
12874         status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
12875
12876         /* status of events with ELS ring */
12877         status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
12878         status2 >>= (4*LPFC_ELS_RING);
12879
12880         if (status1 || (status2 & HA_RXMASK))
12881                 sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
12882         else
12883                 sp_irq_rc = IRQ_NONE;
12884
12885         /*
12886          * Invoke fast-path host attention interrupt handling as appropriate.
12887          */
12888
12889         /* status of events with FCP ring */
12890         status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
12891         status1 >>= (4*LPFC_FCP_RING);
12892
12893         /* status of events with extra ring */
12894         if (phba->cfg_multi_ring_support == 2) {
12895                 status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
12896                 status2 >>= (4*LPFC_EXTRA_RING);
12897         } else
12898                 status2 = 0;
12899
12900         if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
12901                 fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
12902         else
12903                 fp_irq_rc = IRQ_NONE;
12904
12905         /* Return device-level interrupt handling status */
12906         return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
12907 }  /* lpfc_sli_intr_handler */
12908
12909 /**
12910  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
12911  * @phba: pointer to lpfc hba data structure.
12912  *
12913  * This routine is invoked by the worker thread to process all the pending
12914  * SLI4 els abort xri events.
12915  **/
12916 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
12917 {
12918         struct lpfc_cq_event *cq_event;
12919
12920         /* First, declare the els xri abort event has been handled */
12921         spin_lock_irq(&phba->hbalock);
12922         phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
12923         spin_unlock_irq(&phba->hbalock);
12924         /* Now, handle all the els xri abort events */
12925         while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
12926                 /* Get the first event from the head of the event queue */
12927                 spin_lock_irq(&phba->hbalock);
12928                 list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
12929                                  cq_event, struct lpfc_cq_event, list);
12930                 spin_unlock_irq(&phba->hbalock);
12931                 /* Notify aborted XRI for ELS work queue */
12932                 lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
12933                 /* Free the event processed back to the free pool */
12934                 lpfc_sli4_cq_event_release(phba, cq_event);
12935         }
12936 }
12937
12938 /**
12939  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
12940  * @phba: pointer to lpfc hba data structure
12941  * @pIocbIn: pointer to the rspiocbq
12942  * @pIocbOut: pointer to the cmdiocbq
12943  * @wcqe: pointer to the complete wcqe
12944  *
12945  * This routine transfers the fields of a command iocbq to a response iocbq
12946  * by copying all the IOCB fields from command iocbq and transferring the
12947  * completion status information from the complete wcqe.
12948  **/
12949 static void
12950 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
12951                               struct lpfc_iocbq *pIocbIn,
12952                               struct lpfc_iocbq *pIocbOut,
12953                               struct lpfc_wcqe_complete *wcqe)
12954 {
12955         int numBdes, i;
12956         unsigned long iflags;
12957         uint32_t status, max_response;
12958         struct lpfc_dmabuf *dmabuf;
12959         struct ulp_bde64 *bpl, bde;
12960         size_t offset = offsetof(struct lpfc_iocbq, iocb);
12961
12962         memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
12963                sizeof(struct lpfc_iocbq) - offset);
12964         /* Map WCQE parameters into irspiocb parameters */
12965         status = bf_get(lpfc_wcqe_c_status, wcqe);
12966         pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
12967         if (pIocbOut->iocb_flag & LPFC_IO_FCP)
12968                 if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
12969                         pIocbIn->iocb.un.fcpi.fcpi_parm =
12970                                         pIocbOut->iocb.un.fcpi.fcpi_parm -
12971                                         wcqe->total_data_placed;
12972                 else
12973                         pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
12974         else {
12975                 pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
12976                 switch (pIocbOut->iocb.ulpCommand) {
12977                 case CMD_ELS_REQUEST64_CR:
12978                         dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
12979                         bpl  = (struct ulp_bde64 *)dmabuf->virt;
12980                         bde.tus.w = le32_to_cpu(bpl[1].tus.w);
12981                         max_response = bde.tus.f.bdeSize;
12982                         break;
12983                 case CMD_GEN_REQUEST64_CR:
12984                         max_response = 0;
12985                         if (!pIocbOut->context3)
12986                                 break;
12987                         numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
12988                                         sizeof(struct ulp_bde64);
12989                         dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
12990                         bpl = (struct ulp_bde64 *)dmabuf->virt;
12991                         for (i = 0; i < numBdes; i++) {
12992                                 bde.tus.w = le32_to_cpu(bpl[i].tus.w);
12993                                 if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
12994                                         max_response += bde.tus.f.bdeSize;
12995                         }
12996                         break;
12997                 default:
12998                         max_response = wcqe->total_data_placed;
12999                         break;
13000                 }
13001                 if (max_response < wcqe->total_data_placed)
13002                         pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
13003                 else
13004                         pIocbIn->iocb.un.genreq64.bdl.bdeSize =
13005                                 wcqe->total_data_placed;
13006         }
13007
13008         /* Convert BG errors for completion status */
13009         if (status == CQE_STATUS_DI_ERROR) {
13010                 pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
13011
13012                 if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
13013                         pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
13014                 else
13015                         pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
13016
13017                 pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
13018                 if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
13019                         pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13020                                 BGS_GUARD_ERR_MASK;
13021                 if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
13022                         pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13023                                 BGS_APPTAG_ERR_MASK;
13024                 if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
13025                         pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13026                                 BGS_REFTAG_ERR_MASK;
13027
13028                 /* Check to see if there was any good data before the error */
13029                 if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
13030                         pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13031                                 BGS_HI_WATER_MARK_PRESENT_MASK;
13032                         pIocbIn->iocb.unsli3.sli3_bg.bghm =
13033                                 wcqe->total_data_placed;
13034                 }
13035
13036                 /*
13037                 * Set ALL the error bits to indicate we don't know what
13038                 * type of error it is.
13039                 */
13040                 if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
13041                         pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
13042                                 (BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
13043                                 BGS_GUARD_ERR_MASK);
13044         }
13045
13046         /* Pick up HBA exchange busy condition */
13047         if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
13048                 spin_lock_irqsave(&phba->hbalock, iflags);
13049                 pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
13050                 spin_unlock_irqrestore(&phba->hbalock, iflags);
13051         }
13052 }
13053
13054 /**
13055  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
13056  * @phba: Pointer to HBA context object.
13057  * @wcqe: Pointer to work-queue completion queue entry.
13058  *
13059  * This routine handles an ELS work-queue completion event and construct
13060  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
13061  * discovery engine to handle.
13062  *
13063  * Return: Pointer to the receive IOCBQ, NULL otherwise.
13064  **/
13065 static struct lpfc_iocbq *
13066 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
13067                                struct lpfc_iocbq *irspiocbq)
13068 {
13069         struct lpfc_sli_ring *pring;
13070         struct lpfc_iocbq *cmdiocbq;
13071         struct lpfc_wcqe_complete *wcqe;
13072         unsigned long iflags;
13073
13074         pring = lpfc_phba_elsring(phba);
13075         if (unlikely(!pring))
13076                 return NULL;
13077
13078         wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
13079         pring->stats.iocb_event++;
13080         /* Look up the ELS command IOCB and create pseudo response IOCB */
13081         cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
13082                                 bf_get(lpfc_wcqe_c_request_tag, wcqe));
13083         if (unlikely(!cmdiocbq)) {
13084                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13085                                 "0386 ELS complete with no corresponding "
13086                                 "cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
13087                                 wcqe->word0, wcqe->total_data_placed,
13088                                 wcqe->parameter, wcqe->word3);
13089                 lpfc_sli_release_iocbq(phba, irspiocbq);
13090                 return NULL;
13091         }
13092
13093         spin_lock_irqsave(&pring->ring_lock, iflags);
13094         /* Put the iocb back on the txcmplq */
13095         lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
13096         spin_unlock_irqrestore(&pring->ring_lock, iflags);
13097
13098         /* Fake the irspiocbq and copy necessary response information */
13099         lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
13100
13101         return irspiocbq;
13102 }
13103
13104 inline struct lpfc_cq_event *
13105 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
13106 {
13107         struct lpfc_cq_event *cq_event;
13108
13109         /* Allocate a new internal CQ_EVENT entry */
13110         cq_event = lpfc_sli4_cq_event_alloc(phba);
13111         if (!cq_event) {
13112                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13113                                 "0602 Failed to alloc CQ_EVENT entry\n");
13114                 return NULL;
13115         }
13116
13117         /* Move the CQE into the event */
13118         memcpy(&cq_event->cqe, entry, size);
13119         return cq_event;
13120 }
13121
13122 /**
13123  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
13124  * @phba: Pointer to HBA context object.
13125  * @cqe: Pointer to mailbox completion queue entry.
13126  *
13127  * This routine process a mailbox completion queue entry with asynchronous
13128  * event.
13129  *
13130  * Return: true if work posted to worker thread, otherwise false.
13131  **/
13132 static bool
13133 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13134 {
13135         struct lpfc_cq_event *cq_event;
13136         unsigned long iflags;
13137
13138         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13139                         "0392 Async Event: word0:x%x, word1:x%x, "
13140                         "word2:x%x, word3:x%x\n", mcqe->word0,
13141                         mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
13142
13143         cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
13144         if (!cq_event)
13145                 return false;
13146         spin_lock_irqsave(&phba->hbalock, iflags);
13147         list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
13148         /* Set the async event flag */
13149         phba->hba_flag |= ASYNC_EVENT;
13150         spin_unlock_irqrestore(&phba->hbalock, iflags);
13151
13152         return true;
13153 }
13154
13155 /**
13156  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
13157  * @phba: Pointer to HBA context object.
13158  * @cqe: Pointer to mailbox completion queue entry.
13159  *
13160  * This routine process a mailbox completion queue entry with mailbox
13161  * completion event.
13162  *
13163  * Return: true if work posted to worker thread, otherwise false.
13164  **/
13165 static bool
13166 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
13167 {
13168         uint32_t mcqe_status;
13169         MAILBOX_t *mbox, *pmbox;
13170         struct lpfc_mqe *mqe;
13171         struct lpfc_vport *vport;
13172         struct lpfc_nodelist *ndlp;
13173         struct lpfc_dmabuf *mp;
13174         unsigned long iflags;
13175         LPFC_MBOXQ_t *pmb;
13176         bool workposted = false;
13177         int rc;
13178
13179         /* If not a mailbox complete MCQE, out by checking mailbox consume */
13180         if (!bf_get(lpfc_trailer_completed, mcqe))
13181                 goto out_no_mqe_complete;
13182
13183         /* Get the reference to the active mbox command */
13184         spin_lock_irqsave(&phba->hbalock, iflags);
13185         pmb = phba->sli.mbox_active;
13186         if (unlikely(!pmb)) {
13187                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX,
13188                                 "1832 No pending MBOX command to handle\n");
13189                 spin_unlock_irqrestore(&phba->hbalock, iflags);
13190                 goto out_no_mqe_complete;
13191         }
13192         spin_unlock_irqrestore(&phba->hbalock, iflags);
13193         mqe = &pmb->u.mqe;
13194         pmbox = (MAILBOX_t *)&pmb->u.mqe;
13195         mbox = phba->mbox;
13196         vport = pmb->vport;
13197
13198         /* Reset heartbeat timer */
13199         phba->last_completion_time = jiffies;
13200         del_timer(&phba->sli.mbox_tmo);
13201
13202         /* Move mbox data to caller's mailbox region, do endian swapping */
13203         if (pmb->mbox_cmpl && mbox)
13204                 lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
13205
13206         /*
13207          * For mcqe errors, conditionally move a modified error code to
13208          * the mbox so that the error will not be missed.
13209          */
13210         mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
13211         if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
13212                 if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
13213                         bf_set(lpfc_mqe_status, mqe,
13214                                (LPFC_MBX_ERROR_RANGE | mcqe_status));
13215         }
13216         if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13217                 pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13218                 lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
13219                                       "MBOX dflt rpi: status:x%x rpi:x%x",
13220                                       mcqe_status,
13221                                       pmbox->un.varWords[0], 0);
13222                 if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
13223                         mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
13224                         ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
13225                         /* Reg_LOGIN of dflt RPI was successful. Now lets get
13226                          * RID of the PPI using the same mbox buffer.
13227                          */
13228                         lpfc_unreg_login(phba, vport->vpi,
13229                                          pmbox->un.varWords[0], pmb);
13230                         pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
13231                         pmb->ctx_buf = mp;
13232                         pmb->ctx_ndlp = ndlp;
13233                         pmb->vport = vport;
13234                         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
13235                         if (rc != MBX_BUSY)
13236                                 lpfc_printf_log(phba, KERN_ERR, LOG_MBOX |
13237                                                 LOG_SLI, "0385 rc should "
13238                                                 "have been MBX_BUSY\n");
13239                         if (rc != MBX_NOT_FINISHED)
13240                                 goto send_current_mbox;
13241                 }
13242         }
13243         spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
13244         phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
13245         spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
13246
13247         /* There is mailbox completion work to do */
13248         spin_lock_irqsave(&phba->hbalock, iflags);
13249         __lpfc_mbox_cmpl_put(phba, pmb);
13250         phba->work_ha |= HA_MBATT;
13251         spin_unlock_irqrestore(&phba->hbalock, iflags);
13252         workposted = true;
13253
13254 send_current_mbox:
13255         spin_lock_irqsave(&phba->hbalock, iflags);
13256         /* Release the mailbox command posting token */
13257         phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
13258         /* Setting active mailbox pointer need to be in sync to flag clear */
13259         phba->sli.mbox_active = NULL;
13260         if (bf_get(lpfc_trailer_consumed, mcqe))
13261                 lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13262         spin_unlock_irqrestore(&phba->hbalock, iflags);
13263         /* Wake up worker thread to post the next pending mailbox command */
13264         lpfc_worker_wake_up(phba);
13265         return workposted;
13266
13267 out_no_mqe_complete:
13268         spin_lock_irqsave(&phba->hbalock, iflags);
13269         if (bf_get(lpfc_trailer_consumed, mcqe))
13270                 lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
13271         spin_unlock_irqrestore(&phba->hbalock, iflags);
13272         return false;
13273 }
13274
13275 /**
13276  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
13277  * @phba: Pointer to HBA context object.
13278  * @cqe: Pointer to mailbox completion queue entry.
13279  *
13280  * This routine process a mailbox completion queue entry, it invokes the
13281  * proper mailbox complete handling or asynchronous event handling routine
13282  * according to the MCQE's async bit.
13283  *
13284  * Return: true if work posted to worker thread, otherwise false.
13285  **/
13286 static bool
13287 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13288                          struct lpfc_cqe *cqe)
13289 {
13290         struct lpfc_mcqe mcqe;
13291         bool workposted;
13292
13293         cq->CQ_mbox++;
13294
13295         /* Copy the mailbox MCQE and convert endian order as needed */
13296         lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
13297
13298         /* Invoke the proper event handling routine */
13299         if (!bf_get(lpfc_trailer_async, &mcqe))
13300                 workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
13301         else
13302                 workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
13303         return workposted;
13304 }
13305
13306 /**
13307  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
13308  * @phba: Pointer to HBA context object.
13309  * @cq: Pointer to associated CQ
13310  * @wcqe: Pointer to work-queue completion queue entry.
13311  *
13312  * This routine handles an ELS work-queue completion event.
13313  *
13314  * Return: true if work posted to worker thread, otherwise false.
13315  **/
13316 static bool
13317 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13318                              struct lpfc_wcqe_complete *wcqe)
13319 {
13320         struct lpfc_iocbq *irspiocbq;
13321         unsigned long iflags;
13322         struct lpfc_sli_ring *pring = cq->pring;
13323         int txq_cnt = 0;
13324         int txcmplq_cnt = 0;
13325
13326         /* Check for response status */
13327         if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
13328                 /* Log the error status */
13329                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13330                                 "0357 ELS CQE error: status=x%x: "
13331                                 "CQE: %08x %08x %08x %08x\n",
13332                                 bf_get(lpfc_wcqe_c_status, wcqe),
13333                                 wcqe->word0, wcqe->total_data_placed,
13334                                 wcqe->parameter, wcqe->word3);
13335         }
13336
13337         /* Get an irspiocbq for later ELS response processing use */
13338         irspiocbq = lpfc_sli_get_iocbq(phba);
13339         if (!irspiocbq) {
13340                 if (!list_empty(&pring->txq))
13341                         txq_cnt++;
13342                 if (!list_empty(&pring->txcmplq))
13343                         txcmplq_cnt++;
13344                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13345                         "0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
13346                         "els_txcmplq_cnt=%d\n",
13347                         txq_cnt, phba->iocb_cnt,
13348                         txcmplq_cnt);
13349                 return false;
13350         }
13351
13352         /* Save off the slow-path queue event for work thread to process */
13353         memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
13354         spin_lock_irqsave(&phba->hbalock, iflags);
13355         list_add_tail(&irspiocbq->cq_event.list,
13356                       &phba->sli4_hba.sp_queue_event);
13357         phba->hba_flag |= HBA_SP_QUEUE_EVT;
13358         spin_unlock_irqrestore(&phba->hbalock, iflags);
13359
13360         return true;
13361 }
13362
13363 /**
13364  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
13365  * @phba: Pointer to HBA context object.
13366  * @wcqe: Pointer to work-queue completion queue entry.
13367  *
13368  * This routine handles slow-path WQ entry consumed event by invoking the
13369  * proper WQ release routine to the slow-path WQ.
13370  **/
13371 static void
13372 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
13373                              struct lpfc_wcqe_release *wcqe)
13374 {
13375         /* sanity check on queue memory */
13376         if (unlikely(!phba->sli4_hba.els_wq))
13377                 return;
13378         /* Check for the slow-path ELS work queue */
13379         if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
13380                 lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
13381                                      bf_get(lpfc_wcqe_r_wqe_index, wcqe));
13382         else
13383                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13384                                 "2579 Slow-path wqe consume event carries "
13385                                 "miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
13386                                 bf_get(lpfc_wcqe_r_wqe_index, wcqe),
13387                                 phba->sli4_hba.els_wq->queue_id);
13388 }
13389
13390 /**
13391  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
13392  * @phba: Pointer to HBA context object.
13393  * @cq: Pointer to a WQ completion queue.
13394  * @wcqe: Pointer to work-queue completion queue entry.
13395  *
13396  * This routine handles an XRI abort event.
13397  *
13398  * Return: true if work posted to worker thread, otherwise false.
13399  **/
13400 static bool
13401 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
13402                                    struct lpfc_queue *cq,
13403                                    struct sli4_wcqe_xri_aborted *wcqe)
13404 {
13405         bool workposted = false;
13406         struct lpfc_cq_event *cq_event;
13407         unsigned long iflags;
13408
13409         switch (cq->subtype) {
13410         case LPFC_IO:
13411                 lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
13412                 if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
13413                         /* Notify aborted XRI for NVME work queue */
13414                         if (phba->nvmet_support)
13415                                 lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
13416                 }
13417                 workposted = false;
13418                 break;
13419         case LPFC_NVME_LS: /* NVME LS uses ELS resources */
13420         case LPFC_ELS:
13421                 cq_event = lpfc_cq_event_setup(
13422                         phba, wcqe, sizeof(struct sli4_wcqe_xri_aborted));
13423                 if (!cq_event)
13424                         return false;
13425                 cq_event->hdwq = cq->hdwq;
13426                 spin_lock_irqsave(&phba->hbalock, iflags);
13427                 list_add_tail(&cq_event->list,
13428                               &phba->sli4_hba.sp_els_xri_aborted_work_queue);
13429                 /* Set the els xri abort event flag */
13430                 phba->hba_flag |= ELS_XRI_ABORT_EVENT;
13431                 spin_unlock_irqrestore(&phba->hbalock, iflags);
13432                 workposted = true;
13433                 break;
13434         default:
13435                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13436                                 "0603 Invalid CQ subtype %d: "
13437                                 "%08x %08x %08x %08x\n",
13438                                 cq->subtype, wcqe->word0, wcqe->parameter,
13439                                 wcqe->word2, wcqe->word3);
13440                 workposted = false;
13441                 break;
13442         }
13443         return workposted;
13444 }
13445
13446 #define FC_RCTL_MDS_DIAGS       0xF4
13447
13448 /**
13449  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
13450  * @phba: Pointer to HBA context object.
13451  * @rcqe: Pointer to receive-queue completion queue entry.
13452  *
13453  * This routine process a receive-queue completion queue entry.
13454  *
13455  * Return: true if work posted to worker thread, otherwise false.
13456  **/
13457 static bool
13458 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
13459 {
13460         bool workposted = false;
13461         struct fc_frame_header *fc_hdr;
13462         struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
13463         struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
13464         struct lpfc_nvmet_tgtport *tgtp;
13465         struct hbq_dmabuf *dma_buf;
13466         uint32_t status, rq_id;
13467         unsigned long iflags;
13468
13469         /* sanity check on queue memory */
13470         if (unlikely(!hrq) || unlikely(!drq))
13471                 return workposted;
13472
13473         if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
13474                 rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
13475         else
13476                 rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
13477         if (rq_id != hrq->queue_id)
13478                 goto out;
13479
13480         status = bf_get(lpfc_rcqe_status, rcqe);
13481         switch (status) {
13482         case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
13483                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13484                                 "2537 Receive Frame Truncated!!\n");
13485                 /* fall through */
13486         case FC_STATUS_RQ_SUCCESS:
13487                 spin_lock_irqsave(&phba->hbalock, iflags);
13488                 lpfc_sli4_rq_release(hrq, drq);
13489                 dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
13490                 if (!dma_buf) {
13491                         hrq->RQ_no_buf_found++;
13492                         spin_unlock_irqrestore(&phba->hbalock, iflags);
13493                         goto out;
13494                 }
13495                 hrq->RQ_rcv_buf++;
13496                 hrq->RQ_buf_posted--;
13497                 memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
13498
13499                 fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
13500
13501                 if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
13502                     fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
13503                         spin_unlock_irqrestore(&phba->hbalock, iflags);
13504                         /* Handle MDS Loopback frames */
13505                         lpfc_sli4_handle_mds_loopback(phba->pport, dma_buf);
13506                         break;
13507                 }
13508
13509                 /* save off the frame for the work thread to process */
13510                 list_add_tail(&dma_buf->cq_event.list,
13511                               &phba->sli4_hba.sp_queue_event);
13512                 /* Frame received */
13513                 phba->hba_flag |= HBA_SP_QUEUE_EVT;
13514                 spin_unlock_irqrestore(&phba->hbalock, iflags);
13515                 workposted = true;
13516                 break;
13517         case FC_STATUS_INSUFF_BUF_FRM_DISC:
13518                 if (phba->nvmet_support) {
13519                         tgtp = phba->targetport->private;
13520                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_NVME,
13521                                         "6402 RQE Error x%x, posted %d err_cnt "
13522                                         "%d: %x %x %x\n",
13523                                         status, hrq->RQ_buf_posted,
13524                                         hrq->RQ_no_posted_buf,
13525                                         atomic_read(&tgtp->rcv_fcp_cmd_in),
13526                                         atomic_read(&tgtp->rcv_fcp_cmd_out),
13527                                         atomic_read(&tgtp->xmt_fcp_release));
13528                 }
13529                 /* fallthrough */
13530
13531         case FC_STATUS_INSUFF_BUF_NEED_BUF:
13532                 hrq->RQ_no_posted_buf++;
13533                 /* Post more buffers if possible */
13534                 spin_lock_irqsave(&phba->hbalock, iflags);
13535                 phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
13536                 spin_unlock_irqrestore(&phba->hbalock, iflags);
13537                 workposted = true;
13538                 break;
13539         }
13540 out:
13541         return workposted;
13542 }
13543
13544 /**
13545  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
13546  * @phba: Pointer to HBA context object.
13547  * @cq: Pointer to the completion queue.
13548  * @cqe: Pointer to a completion queue entry.
13549  *
13550  * This routine process a slow-path work-queue or receive queue completion queue
13551  * entry.
13552  *
13553  * Return: true if work posted to worker thread, otherwise false.
13554  **/
13555 static bool
13556 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13557                          struct lpfc_cqe *cqe)
13558 {
13559         struct lpfc_cqe cqevt;
13560         bool workposted = false;
13561
13562         /* Copy the work queue CQE and convert endian order if needed */
13563         lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
13564
13565         /* Check and process for different type of WCQE and dispatch */
13566         switch (bf_get(lpfc_cqe_code, &cqevt)) {
13567         case CQE_CODE_COMPL_WQE:
13568                 /* Process the WQ/RQ complete event */
13569                 phba->last_completion_time = jiffies;
13570                 workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
13571                                 (struct lpfc_wcqe_complete *)&cqevt);
13572                 break;
13573         case CQE_CODE_RELEASE_WQE:
13574                 /* Process the WQ release event */
13575                 lpfc_sli4_sp_handle_rel_wcqe(phba,
13576                                 (struct lpfc_wcqe_release *)&cqevt);
13577                 break;
13578         case CQE_CODE_XRI_ABORTED:
13579                 /* Process the WQ XRI abort event */
13580                 phba->last_completion_time = jiffies;
13581                 workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
13582                                 (struct sli4_wcqe_xri_aborted *)&cqevt);
13583                 break;
13584         case CQE_CODE_RECEIVE:
13585         case CQE_CODE_RECEIVE_V1:
13586                 /* Process the RQ event */
13587                 phba->last_completion_time = jiffies;
13588                 workposted = lpfc_sli4_sp_handle_rcqe(phba,
13589                                 (struct lpfc_rcqe *)&cqevt);
13590                 break;
13591         default:
13592                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13593                                 "0388 Not a valid WCQE code: x%x\n",
13594                                 bf_get(lpfc_cqe_code, &cqevt));
13595                 break;
13596         }
13597         return workposted;
13598 }
13599
13600 /**
13601  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
13602  * @phba: Pointer to HBA context object.
13603  * @eqe: Pointer to fast-path event queue entry.
13604  *
13605  * This routine process a event queue entry from the slow-path event queue.
13606  * It will check the MajorCode and MinorCode to determine this is for a
13607  * completion event on a completion queue, if not, an error shall be logged
13608  * and just return. Otherwise, it will get to the corresponding completion
13609  * queue and process all the entries on that completion queue, rearm the
13610  * completion queue, and then return.
13611  *
13612  **/
13613 static void
13614 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
13615         struct lpfc_queue *speq)
13616 {
13617         struct lpfc_queue *cq = NULL, *childq;
13618         uint16_t cqid;
13619
13620         /* Get the reference to the corresponding CQ */
13621         cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
13622
13623         list_for_each_entry(childq, &speq->child_list, list) {
13624                 if (childq->queue_id == cqid) {
13625                         cq = childq;
13626                         break;
13627                 }
13628         }
13629         if (unlikely(!cq)) {
13630                 if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
13631                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13632                                         "0365 Slow-path CQ identifier "
13633                                         "(%d) does not exist\n", cqid);
13634                 return;
13635         }
13636
13637         /* Save EQ associated with this CQ */
13638         cq->assoc_qp = speq;
13639
13640         if (!queue_work_on(cq->chann, phba->wq, &cq->spwork))
13641                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13642                                 "0390 Cannot schedule soft IRQ "
13643                                 "for CQ eqcqid=%d, cqid=%d on CPU %d\n",
13644                                 cqid, cq->queue_id, raw_smp_processor_id());
13645 }
13646
13647 /**
13648  * __lpfc_sli4_process_cq - Process elements of a CQ
13649  * @phba: Pointer to HBA context object.
13650  * @cq: Pointer to CQ to be processed
13651  * @handler: Routine to process each cqe
13652  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
13653  *
13654  * This routine processes completion queue entries in a CQ. While a valid
13655  * queue element is found, the handler is called. During processing checks
13656  * are made for periodic doorbell writes to let the hardware know of
13657  * element consumption.
13658  *
13659  * If the max limit on cqes to process is hit, or there are no more valid
13660  * entries, the loop stops. If we processed a sufficient number of elements,
13661  * meaning there is sufficient load, rather than rearming and generating
13662  * another interrupt, a cq rescheduling delay will be set. A delay of 0
13663  * indicates no rescheduling.
13664  *
13665  * Returns True if work scheduled, False otherwise.
13666  **/
13667 static bool
13668 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
13669         bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
13670                         struct lpfc_cqe *), unsigned long *delay)
13671 {
13672         struct lpfc_cqe *cqe;
13673         bool workposted = false;
13674         int count = 0, consumed = 0;
13675         bool arm = true;
13676
13677         /* default - no reschedule */
13678         *delay = 0;
13679
13680         if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
13681                 goto rearm_and_exit;
13682
13683         /* Process all the entries to the CQ */
13684         cq->q_flag = 0;
13685         cqe = lpfc_sli4_cq_get(cq);
13686         while (cqe) {
13687                 workposted |= handler(phba, cq, cqe);
13688                 __lpfc_sli4_consume_cqe(phba, cq, cqe);
13689
13690                 consumed++;
13691                 if (!(++count % cq->max_proc_limit))
13692                         break;
13693
13694                 if (!(count % cq->notify_interval)) {
13695                         phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
13696                                                 LPFC_QUEUE_NOARM);
13697                         consumed = 0;
13698                         cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
13699                 }
13700
13701                 if (count == LPFC_NVMET_CQ_NOTIFY)
13702                         cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
13703
13704                 cqe = lpfc_sli4_cq_get(cq);
13705         }
13706         if (count >= phba->cfg_cq_poll_threshold) {
13707                 *delay = 1;
13708                 arm = false;
13709         }
13710
13711         /* Track the max number of CQEs processed in 1 EQ */
13712         if (count > cq->CQ_max_cqe)
13713                 cq->CQ_max_cqe = count;
13714
13715         cq->assoc_qp->EQ_cqe_cnt += count;
13716
13717         /* Catch the no cq entry condition */
13718         if (unlikely(count == 0))
13719                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13720                                 "0369 No entry from completion queue "
13721                                 "qid=%d\n", cq->queue_id);
13722
13723         cq->queue_claimed = 0;
13724
13725 rearm_and_exit:
13726         phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
13727                         arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
13728
13729         return workposted;
13730 }
13731
13732 /**
13733  * lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
13734  * @cq: pointer to CQ to process
13735  *
13736  * This routine calls the cq processing routine with a handler specific
13737  * to the type of queue bound to it.
13738  *
13739  * The CQ routine returns two values: the first is the calling status,
13740  * which indicates whether work was queued to the  background discovery
13741  * thread. If true, the routine should wakeup the discovery thread;
13742  * the second is the delay parameter. If non-zero, rather than rearming
13743  * the CQ and yet another interrupt, the CQ handler should be queued so
13744  * that it is processed in a subsequent polling action. The value of
13745  * the delay indicates when to reschedule it.
13746  **/
13747 static void
13748 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
13749 {
13750         struct lpfc_hba *phba = cq->phba;
13751         unsigned long delay;
13752         bool workposted = false;
13753
13754         /* Process and rearm the CQ */
13755         switch (cq->type) {
13756         case LPFC_MCQ:
13757                 workposted |= __lpfc_sli4_process_cq(phba, cq,
13758                                                 lpfc_sli4_sp_handle_mcqe,
13759                                                 &delay);
13760                 break;
13761         case LPFC_WCQ:
13762                 if (cq->subtype == LPFC_IO)
13763                         workposted |= __lpfc_sli4_process_cq(phba, cq,
13764                                                 lpfc_sli4_fp_handle_cqe,
13765                                                 &delay);
13766                 else
13767                         workposted |= __lpfc_sli4_process_cq(phba, cq,
13768                                                 lpfc_sli4_sp_handle_cqe,
13769                                                 &delay);
13770                 break;
13771         default:
13772                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13773                                 "0370 Invalid completion queue type (%d)\n",
13774                                 cq->type);
13775                 return;
13776         }
13777
13778         if (delay) {
13779                 if (!queue_delayed_work_on(cq->chann, phba->wq,
13780                                            &cq->sched_spwork, delay))
13781                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13782                                 "0394 Cannot schedule soft IRQ "
13783                                 "for cqid=%d on CPU %d\n",
13784                                 cq->queue_id, cq->chann);
13785         }
13786
13787         /* wake up worker thread if there are works to be done */
13788         if (workposted)
13789                 lpfc_worker_wake_up(phba);
13790 }
13791
13792 /**
13793  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
13794  *   interrupt
13795  * @work: pointer to work element
13796  *
13797  * translates from the work handler and calls the slow-path handler.
13798  **/
13799 static void
13800 lpfc_sli4_sp_process_cq(struct work_struct *work)
13801 {
13802         struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
13803
13804         __lpfc_sli4_sp_process_cq(cq);
13805 }
13806
13807 /**
13808  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
13809  * @work: pointer to work element
13810  *
13811  * translates from the work handler and calls the slow-path handler.
13812  **/
13813 static void
13814 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
13815 {
13816         struct lpfc_queue *cq = container_of(to_delayed_work(work),
13817                                         struct lpfc_queue, sched_spwork);
13818
13819         __lpfc_sli4_sp_process_cq(cq);
13820 }
13821
13822 /**
13823  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
13824  * @phba: Pointer to HBA context object.
13825  * @cq: Pointer to associated CQ
13826  * @wcqe: Pointer to work-queue completion queue entry.
13827  *
13828  * This routine process a fast-path work queue completion entry from fast-path
13829  * event queue for FCP command response completion.
13830  **/
13831 static void
13832 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13833                              struct lpfc_wcqe_complete *wcqe)
13834 {
13835         struct lpfc_sli_ring *pring = cq->pring;
13836         struct lpfc_iocbq *cmdiocbq;
13837         struct lpfc_iocbq irspiocbq;
13838         unsigned long iflags;
13839
13840         /* Check for response status */
13841         if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
13842                 /* If resource errors reported from HBA, reduce queue
13843                  * depth of the SCSI device.
13844                  */
13845                 if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
13846                      IOSTAT_LOCAL_REJECT)) &&
13847                     ((wcqe->parameter & IOERR_PARAM_MASK) ==
13848                      IOERR_NO_RESOURCES))
13849                         phba->lpfc_rampdown_queue_depth(phba);
13850
13851                 /* Log the error status */
13852                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13853                                 "0373 FCP CQE error: status=x%x: "
13854                                 "CQE: %08x %08x %08x %08x\n",
13855                                 bf_get(lpfc_wcqe_c_status, wcqe),
13856                                 wcqe->word0, wcqe->total_data_placed,
13857                                 wcqe->parameter, wcqe->word3);
13858         }
13859
13860         /* Look up the FCP command IOCB and create pseudo response IOCB */
13861         spin_lock_irqsave(&pring->ring_lock, iflags);
13862         pring->stats.iocb_event++;
13863         spin_unlock_irqrestore(&pring->ring_lock, iflags);
13864         cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
13865                                 bf_get(lpfc_wcqe_c_request_tag, wcqe));
13866         if (unlikely(!cmdiocbq)) {
13867                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13868                                 "0374 FCP complete with no corresponding "
13869                                 "cmdiocb: iotag (%d)\n",
13870                                 bf_get(lpfc_wcqe_c_request_tag, wcqe));
13871                 return;
13872         }
13873 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
13874         cmdiocbq->isr_timestamp = cq->isr_timestamp;
13875 #endif
13876         if (cmdiocbq->iocb_cmpl == NULL) {
13877                 if (cmdiocbq->wqe_cmpl) {
13878                         if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
13879                                 spin_lock_irqsave(&phba->hbalock, iflags);
13880                                 cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
13881                                 spin_unlock_irqrestore(&phba->hbalock, iflags);
13882                         }
13883
13884                         /* Pass the cmd_iocb and the wcqe to the upper layer */
13885                         (cmdiocbq->wqe_cmpl)(phba, cmdiocbq, wcqe);
13886                         return;
13887                 }
13888                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13889                                 "0375 FCP cmdiocb not callback function "
13890                                 "iotag: (%d)\n",
13891                                 bf_get(lpfc_wcqe_c_request_tag, wcqe));
13892                 return;
13893         }
13894
13895         /* Fake the irspiocb and copy necessary response information */
13896         lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
13897
13898         if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
13899                 spin_lock_irqsave(&phba->hbalock, iflags);
13900                 cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
13901                 spin_unlock_irqrestore(&phba->hbalock, iflags);
13902         }
13903
13904         /* Pass the cmd_iocb and the rsp state to the upper layer */
13905         (cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
13906 }
13907
13908 /**
13909  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
13910  * @phba: Pointer to HBA context object.
13911  * @cq: Pointer to completion queue.
13912  * @wcqe: Pointer to work-queue completion queue entry.
13913  *
13914  * This routine handles an fast-path WQ entry consumed event by invoking the
13915  * proper WQ release routine to the slow-path WQ.
13916  **/
13917 static void
13918 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13919                              struct lpfc_wcqe_release *wcqe)
13920 {
13921         struct lpfc_queue *childwq;
13922         bool wqid_matched = false;
13923         uint16_t hba_wqid;
13924
13925         /* Check for fast-path FCP work queue release */
13926         hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
13927         list_for_each_entry(childwq, &cq->child_list, list) {
13928                 if (childwq->queue_id == hba_wqid) {
13929                         lpfc_sli4_wq_release(childwq,
13930                                         bf_get(lpfc_wcqe_r_wqe_index, wcqe));
13931                         if (childwq->q_flag & HBA_NVMET_WQFULL)
13932                                 lpfc_nvmet_wqfull_process(phba, childwq);
13933                         wqid_matched = true;
13934                         break;
13935                 }
13936         }
13937         /* Report warning log message if no match found */
13938         if (wqid_matched != true)
13939                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
13940                                 "2580 Fast-path wqe consume event carries "
13941                                 "miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
13942 }
13943
13944 /**
13945  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
13946  * @phba: Pointer to HBA context object.
13947  * @rcqe: Pointer to receive-queue completion queue entry.
13948  *
13949  * This routine process a receive-queue completion queue entry.
13950  *
13951  * Return: true if work posted to worker thread, otherwise false.
13952  **/
13953 static bool
13954 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
13955                             struct lpfc_rcqe *rcqe)
13956 {
13957         bool workposted = false;
13958         struct lpfc_queue *hrq;
13959         struct lpfc_queue *drq;
13960         struct rqb_dmabuf *dma_buf;
13961         struct fc_frame_header *fc_hdr;
13962         struct lpfc_nvmet_tgtport *tgtp;
13963         uint32_t status, rq_id;
13964         unsigned long iflags;
13965         uint32_t fctl, idx;
13966
13967         if ((phba->nvmet_support == 0) ||
13968             (phba->sli4_hba.nvmet_cqset == NULL))
13969                 return workposted;
13970
13971         idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
13972         hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
13973         drq = phba->sli4_hba.nvmet_mrq_data[idx];
13974
13975         /* sanity check on queue memory */
13976         if (unlikely(!hrq) || unlikely(!drq))
13977                 return workposted;
13978
13979         if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
13980                 rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
13981         else
13982                 rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
13983
13984         if ((phba->nvmet_support == 0) ||
13985             (rq_id != hrq->queue_id))
13986                 return workposted;
13987
13988         status = bf_get(lpfc_rcqe_status, rcqe);
13989         switch (status) {
13990         case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
13991                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
13992                                 "6126 Receive Frame Truncated!!\n");
13993                 /* fall through */
13994         case FC_STATUS_RQ_SUCCESS:
13995                 spin_lock_irqsave(&phba->hbalock, iflags);
13996                 lpfc_sli4_rq_release(hrq, drq);
13997                 dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
13998                 if (!dma_buf) {
13999                         hrq->RQ_no_buf_found++;
14000                         spin_unlock_irqrestore(&phba->hbalock, iflags);
14001                         goto out;
14002                 }
14003                 spin_unlock_irqrestore(&phba->hbalock, iflags);
14004                 hrq->RQ_rcv_buf++;
14005                 hrq->RQ_buf_posted--;
14006                 fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14007
14008                 /* Just some basic sanity checks on FCP Command frame */
14009                 fctl = (fc_hdr->fh_f_ctl[0] << 16 |
14010                 fc_hdr->fh_f_ctl[1] << 8 |
14011                 fc_hdr->fh_f_ctl[2]);
14012                 if (((fctl &
14013                     (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
14014                     (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
14015                     (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
14016                         goto drop;
14017
14018                 if (fc_hdr->fh_type == FC_TYPE_FCP) {
14019                         dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
14020                         lpfc_nvmet_unsol_fcp_event(
14021                                 phba, idx, dma_buf, cq->isr_timestamp,
14022                                 cq->q_flag & HBA_NVMET_CQ_NOTIFY);
14023                         return false;
14024                 }
14025 drop:
14026                 lpfc_rq_buf_free(phba, &dma_buf->hbuf);
14027                 break;
14028         case FC_STATUS_INSUFF_BUF_FRM_DISC:
14029                 if (phba->nvmet_support) {
14030                         tgtp = phba->targetport->private;
14031                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI | LOG_NVME,
14032                                         "6401 RQE Error x%x, posted %d err_cnt "
14033                                         "%d: %x %x %x\n",
14034                                         status, hrq->RQ_buf_posted,
14035                                         hrq->RQ_no_posted_buf,
14036                                         atomic_read(&tgtp->rcv_fcp_cmd_in),
14037                                         atomic_read(&tgtp->rcv_fcp_cmd_out),
14038                                         atomic_read(&tgtp->xmt_fcp_release));
14039                 }
14040                 /* fallthrough */
14041
14042         case FC_STATUS_INSUFF_BUF_NEED_BUF:
14043                 hrq->RQ_no_posted_buf++;
14044                 /* Post more buffers if possible */
14045                 break;
14046         }
14047 out:
14048         return workposted;
14049 }
14050
14051 /**
14052  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
14053  * @phba: adapter with cq
14054  * @cq: Pointer to the completion queue.
14055  * @eqe: Pointer to fast-path completion queue entry.
14056  *
14057  * This routine process a fast-path work queue completion entry from fast-path
14058  * event queue for FCP command response completion.
14059  *
14060  * Return: true if work posted to worker thread, otherwise false.
14061  **/
14062 static bool
14063 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14064                          struct lpfc_cqe *cqe)
14065 {
14066         struct lpfc_wcqe_release wcqe;
14067         bool workposted = false;
14068
14069         /* Copy the work queue CQE and convert endian order if needed */
14070         lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
14071
14072         /* Check and process for different type of WCQE and dispatch */
14073         switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
14074         case CQE_CODE_COMPL_WQE:
14075         case CQE_CODE_NVME_ERSP:
14076                 cq->CQ_wq++;
14077                 /* Process the WQ complete event */
14078                 phba->last_completion_time = jiffies;
14079                 if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
14080                         lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
14081                                 (struct lpfc_wcqe_complete *)&wcqe);
14082                 break;
14083         case CQE_CODE_RELEASE_WQE:
14084                 cq->CQ_release_wqe++;
14085                 /* Process the WQ release event */
14086                 lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
14087                                 (struct lpfc_wcqe_release *)&wcqe);
14088                 break;
14089         case CQE_CODE_XRI_ABORTED:
14090                 cq->CQ_xri_aborted++;
14091                 /* Process the WQ XRI abort event */
14092                 phba->last_completion_time = jiffies;
14093                 workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14094                                 (struct sli4_wcqe_xri_aborted *)&wcqe);
14095                 break;
14096         case CQE_CODE_RECEIVE_V1:
14097         case CQE_CODE_RECEIVE:
14098                 phba->last_completion_time = jiffies;
14099                 if (cq->subtype == LPFC_NVMET) {
14100                         workposted = lpfc_sli4_nvmet_handle_rcqe(
14101                                 phba, cq, (struct lpfc_rcqe *)&wcqe);
14102                 }
14103                 break;
14104         default:
14105                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14106                                 "0144 Not a valid CQE code: x%x\n",
14107                                 bf_get(lpfc_wcqe_c_code, &wcqe));
14108                 break;
14109         }
14110         return workposted;
14111 }
14112
14113 /**
14114  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
14115  * @phba: Pointer to HBA context object.
14116  * @eqe: Pointer to fast-path event queue entry.
14117  *
14118  * This routine process a event queue entry from the fast-path event queue.
14119  * It will check the MajorCode and MinorCode to determine this is for a
14120  * completion event on a completion queue, if not, an error shall be logged
14121  * and just return. Otherwise, it will get to the corresponding completion
14122  * queue and process all the entries on the completion queue, rearm the
14123  * completion queue, and then return.
14124  **/
14125 static void
14126 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
14127                          struct lpfc_eqe *eqe)
14128 {
14129         struct lpfc_queue *cq = NULL;
14130         uint32_t qidx = eq->hdwq;
14131         uint16_t cqid, id;
14132
14133         if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
14134                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14135                                 "0366 Not a valid completion "
14136                                 "event: majorcode=x%x, minorcode=x%x\n",
14137                                 bf_get_le32(lpfc_eqe_major_code, eqe),
14138                                 bf_get_le32(lpfc_eqe_minor_code, eqe));
14139                 return;
14140         }
14141
14142         /* Get the reference to the corresponding CQ */
14143         cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14144
14145         /* Use the fast lookup method first */
14146         if (cqid <= phba->sli4_hba.cq_max) {
14147                 cq = phba->sli4_hba.cq_lookup[cqid];
14148                 if (cq)
14149                         goto  work_cq;
14150         }
14151
14152         /* Next check for NVMET completion */
14153         if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
14154                 id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
14155                 if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
14156                         /* Process NVMET unsol rcv */
14157                         cq = phba->sli4_hba.nvmet_cqset[cqid - id];
14158                         goto  process_cq;
14159                 }
14160         }
14161
14162         if (phba->sli4_hba.nvmels_cq &&
14163             (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
14164                 /* Process NVME unsol rcv */
14165                 cq = phba->sli4_hba.nvmels_cq;
14166         }
14167
14168         /* Otherwise this is a Slow path event */
14169         if (cq == NULL) {
14170                 lpfc_sli4_sp_handle_eqe(phba, eqe,
14171                                         phba->sli4_hba.hdwq[qidx].hba_eq);
14172                 return;
14173         }
14174
14175 process_cq:
14176         if (unlikely(cqid != cq->queue_id)) {
14177                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14178                                 "0368 Miss-matched fast-path completion "
14179                                 "queue identifier: eqcqid=%d, fcpcqid=%d\n",
14180                                 cqid, cq->queue_id);
14181                 return;
14182         }
14183
14184 work_cq:
14185 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
14186         if (phba->ktime_on)
14187                 cq->isr_timestamp = ktime_get_ns();
14188         else
14189                 cq->isr_timestamp = 0;
14190 #endif
14191         if (!queue_work_on(cq->chann, phba->wq, &cq->irqwork))
14192                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14193                                 "0363 Cannot schedule soft IRQ "
14194                                 "for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14195                                 cqid, cq->queue_id, raw_smp_processor_id());
14196 }
14197
14198 /**
14199  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
14200  * @cq: Pointer to CQ to be processed
14201  *
14202  * This routine calls the cq processing routine with the handler for
14203  * fast path CQEs.
14204  *
14205  * The CQ routine returns two values: the first is the calling status,
14206  * which indicates whether work was queued to the  background discovery
14207  * thread. If true, the routine should wakeup the discovery thread;
14208  * the second is the delay parameter. If non-zero, rather than rearming
14209  * the CQ and yet another interrupt, the CQ handler should be queued so
14210  * that it is processed in a subsequent polling action. The value of
14211  * the delay indicates when to reschedule it.
14212  **/
14213 static void
14214 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq)
14215 {
14216         struct lpfc_hba *phba = cq->phba;
14217         unsigned long delay;
14218         bool workposted = false;
14219
14220         /* process and rearm the CQ */
14221         workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
14222                                              &delay);
14223
14224         if (delay) {
14225                 if (!queue_delayed_work_on(cq->chann, phba->wq,
14226                                            &cq->sched_irqwork, delay))
14227                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14228                                 "0367 Cannot schedule soft IRQ "
14229                                 "for cqid=%d on CPU %d\n",
14230                                 cq->queue_id, cq->chann);
14231         }
14232
14233         /* wake up worker thread if there are works to be done */
14234         if (workposted)
14235                 lpfc_worker_wake_up(phba);
14236 }
14237
14238 /**
14239  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
14240  *   interrupt
14241  * @work: pointer to work element
14242  *
14243  * translates from the work handler and calls the fast-path handler.
14244  **/
14245 static void
14246 lpfc_sli4_hba_process_cq(struct work_struct *work)
14247 {
14248         struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
14249
14250         __lpfc_sli4_hba_process_cq(cq);
14251 }
14252
14253 /**
14254  * lpfc_sli4_hba_process_cq - fast-path work handler when started by timer
14255  * @work: pointer to work element
14256  *
14257  * translates from the work handler and calls the fast-path handler.
14258  **/
14259 static void
14260 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
14261 {
14262         struct lpfc_queue *cq = container_of(to_delayed_work(work),
14263                                         struct lpfc_queue, sched_irqwork);
14264
14265         __lpfc_sli4_hba_process_cq(cq);
14266 }
14267
14268 /**
14269  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
14270  * @irq: Interrupt number.
14271  * @dev_id: The device context pointer.
14272  *
14273  * This function is directly called from the PCI layer as an interrupt
14274  * service routine when device with SLI-4 interface spec is enabled with
14275  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
14276  * ring event in the HBA. However, when the device is enabled with either
14277  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
14278  * device-level interrupt handler. When the PCI slot is in error recovery
14279  * or the HBA is undergoing initialization, the interrupt handler will not
14280  * process the interrupt. The SCSI FCP fast-path ring event are handled in
14281  * the intrrupt context. This function is called without any lock held.
14282  * It gets the hbalock to access and update SLI data structures. Note that,
14283  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
14284  * equal to that of FCP CQ index.
14285  *
14286  * The link attention and ELS ring attention events are handled
14287  * by the worker thread. The interrupt handler signals the worker thread
14288  * and returns for these events. This function is called without any lock
14289  * held. It gets the hbalock to access and update SLI data structures.
14290  *
14291  * This function returns IRQ_HANDLED when interrupt is handled else it
14292  * returns IRQ_NONE.
14293  **/
14294 irqreturn_t
14295 lpfc_sli4_hba_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 *fpeq;
14300         unsigned long iflag;
14301         int ecount = 0;
14302         int hba_eqidx;
14303         struct lpfc_eq_intr_info *eqi;
14304         uint32_t icnt;
14305
14306         /* Get the driver's phba structure from the dev_id */
14307         hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
14308         phba = hba_eq_hdl->phba;
14309         hba_eqidx = hba_eq_hdl->idx;
14310
14311         if (unlikely(!phba))
14312                 return IRQ_NONE;
14313         if (unlikely(!phba->sli4_hba.hdwq))
14314                 return IRQ_NONE;
14315
14316         /* Get to the EQ struct associated with this vector */
14317         fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
14318         if (unlikely(!fpeq))
14319                 return IRQ_NONE;
14320
14321         /* Check device state for handling interrupt */
14322         if (unlikely(lpfc_intr_state_check(phba))) {
14323                 /* Check again for link_state with lock held */
14324                 spin_lock_irqsave(&phba->hbalock, iflag);
14325                 if (phba->link_state < LPFC_LINK_DOWN)
14326                         /* Flush, clear interrupt, and rearm the EQ */
14327                         lpfc_sli4_eqcq_flush(phba, fpeq);
14328                 spin_unlock_irqrestore(&phba->hbalock, iflag);
14329                 return IRQ_NONE;
14330         }
14331
14332         eqi = phba->sli4_hba.eq_info;
14333         icnt = this_cpu_inc_return(eqi->icnt);
14334         fpeq->last_cpu = raw_smp_processor_id();
14335
14336         if (icnt > LPFC_EQD_ISR_TRIGGER &&
14337             fpeq->q_flag & HBA_EQ_DELAY_CHK &&
14338             phba->cfg_auto_imax &&
14339             fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
14340             phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
14341                 lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
14342
14343         /* process and rearm the EQ */
14344         ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
14345
14346         if (unlikely(ecount == 0)) {
14347                 fpeq->EQ_no_entry++;
14348                 if (phba->intr_type == MSIX)
14349                         /* MSI-X treated interrupt served as no EQ share INT */
14350                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14351                                         "0358 MSI-X interrupt with no EQE\n");
14352                 else
14353                         /* Non MSI-X treated on interrupt as EQ share INT */
14354                         return IRQ_NONE;
14355         }
14356
14357         return IRQ_HANDLED;
14358 } /* lpfc_sli4_fp_intr_handler */
14359
14360 /**
14361  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
14362  * @irq: Interrupt number.
14363  * @dev_id: The device context pointer.
14364  *
14365  * This function is the device-level interrupt handler to device with SLI-4
14366  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
14367  * interrupt mode is enabled and there is an event in the HBA which requires
14368  * driver attention. This function invokes the slow-path interrupt attention
14369  * handling function and fast-path interrupt attention handling function in
14370  * turn to process the relevant HBA attention events. This function is called
14371  * without any lock held. It gets the hbalock to access and update SLI data
14372  * structures.
14373  *
14374  * This function returns IRQ_HANDLED when interrupt is handled, else it
14375  * returns IRQ_NONE.
14376  **/
14377 irqreturn_t
14378 lpfc_sli4_intr_handler(int irq, void *dev_id)
14379 {
14380         struct lpfc_hba  *phba;
14381         irqreturn_t hba_irq_rc;
14382         bool hba_handled = false;
14383         int qidx;
14384
14385         /* Get the driver's phba structure from the dev_id */
14386         phba = (struct lpfc_hba *)dev_id;
14387
14388         if (unlikely(!phba))
14389                 return IRQ_NONE;
14390
14391         /*
14392          * Invoke fast-path host attention interrupt handling as appropriate.
14393          */
14394         for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
14395                 hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
14396                                         &phba->sli4_hba.hba_eq_hdl[qidx]);
14397                 if (hba_irq_rc == IRQ_HANDLED)
14398                         hba_handled |= true;
14399         }
14400
14401         return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
14402 } /* lpfc_sli4_intr_handler */
14403
14404 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
14405 {
14406         struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
14407         struct lpfc_queue *eq;
14408         int i = 0;
14409
14410         rcu_read_lock();
14411
14412         list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
14413                 i += lpfc_sli4_poll_eq(eq, LPFC_POLL_SLOWPATH);
14414         if (!list_empty(&phba->poll_list))
14415                 mod_timer(&phba->cpuhp_poll_timer,
14416                           jiffies + msecs_to_jiffies(LPFC_POLL_HB));
14417
14418         rcu_read_unlock();
14419 }
14420
14421 inline int lpfc_sli4_poll_eq(struct lpfc_queue *eq, uint8_t path)
14422 {
14423         struct lpfc_hba *phba = eq->phba;
14424         int i = 0;
14425
14426         /*
14427          * Unlocking an irq is one of the entry point to check
14428          * for re-schedule, but we are good for io submission
14429          * path as midlayer does a get_cpu to glue us in. Flush
14430          * out the invalidate queue so we can see the updated
14431          * value for flag.
14432          */
14433         smp_rmb();
14434
14435         if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
14436                 /* We will not likely get the completion for the caller
14437                  * during this iteration but i guess that's fine.
14438                  * Future io's coming on this eq should be able to
14439                  * pick it up.  As for the case of single io's, they
14440                  * will be handled through a sched from polling timer
14441                  * function which is currently triggered every 1msec.
14442                  */
14443                 i = lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM);
14444
14445         return i;
14446 }
14447
14448 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
14449 {
14450         struct lpfc_hba *phba = eq->phba;
14451
14452         /* kickstart slowpath processing if needed */
14453         if (list_empty(&phba->poll_list))
14454                 mod_timer(&phba->cpuhp_poll_timer,
14455                           jiffies + msecs_to_jiffies(LPFC_POLL_HB));
14456
14457         list_add_rcu(&eq->_poll_list, &phba->poll_list);
14458         synchronize_rcu();
14459 }
14460
14461 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
14462 {
14463         struct lpfc_hba *phba = eq->phba;
14464
14465         /* Disable slowpath processing for this eq.  Kick start the eq
14466          * by RE-ARMING the eq's ASAP
14467          */
14468         list_del_rcu(&eq->_poll_list);
14469         synchronize_rcu();
14470
14471         if (list_empty(&phba->poll_list))
14472                 del_timer_sync(&phba->cpuhp_poll_timer);
14473 }
14474
14475 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
14476 {
14477         struct lpfc_queue *eq, *next;
14478
14479         list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
14480                 list_del(&eq->_poll_list);
14481
14482         INIT_LIST_HEAD(&phba->poll_list);
14483         synchronize_rcu();
14484 }
14485
14486 static inline void
14487 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
14488 {
14489         if (mode == eq->mode)
14490                 return;
14491         /*
14492          * currently this function is only called during a hotplug
14493          * event and the cpu on which this function is executing
14494          * is going offline.  By now the hotplug has instructed
14495          * the scheduler to remove this cpu from cpu active mask.
14496          * So we don't need to work about being put aside by the
14497          * scheduler for a high priority process.  Yes, the inte-
14498          * rrupts could come but they are known to retire ASAP.
14499          */
14500
14501         /* Disable polling in the fastpath */
14502         WRITE_ONCE(eq->mode, mode);
14503         /* flush out the store buffer */
14504         smp_wmb();
14505
14506         /*
14507          * Add this eq to the polling list and start polling. For
14508          * a grace period both interrupt handler and poller will
14509          * try to process the eq _but_ that's fine.  We have a
14510          * synchronization mechanism in place (queue_claimed) to
14511          * deal with it.  This is just a draining phase for int-
14512          * errupt handler (not eq's) as we have guranteed through
14513          * barrier that all the CPUs have seen the new CQ_POLLED
14514          * state. which will effectively disable the REARMING of
14515          * the EQ.  The whole idea is eq's die off eventually as
14516          * we are not rearming EQ's anymore.
14517          */
14518         mode ? lpfc_sli4_add_to_poll_list(eq) :
14519                lpfc_sli4_remove_from_poll_list(eq);
14520 }
14521
14522 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
14523 {
14524         __lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
14525 }
14526
14527 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
14528 {
14529         struct lpfc_hba *phba = eq->phba;
14530
14531         __lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
14532
14533         /* Kick start for the pending io's in h/w.
14534          * Once we switch back to interrupt processing on a eq
14535          * the io path completion will only arm eq's when it
14536          * receives a completion.  But since eq's are in disa-
14537          * rmed state it doesn't receive a completion.  This
14538          * creates a deadlock scenaro.
14539          */
14540         phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
14541 }
14542
14543 /**
14544  * lpfc_sli4_queue_free - free a queue structure and associated memory
14545  * @queue: The queue structure to free.
14546  *
14547  * This function frees a queue structure and the DMAable memory used for
14548  * the host resident queue. This function must be called after destroying the
14549  * queue on the HBA.
14550  **/
14551 void
14552 lpfc_sli4_queue_free(struct lpfc_queue *queue)
14553 {
14554         struct lpfc_dmabuf *dmabuf;
14555
14556         if (!queue)
14557                 return;
14558
14559         if (!list_empty(&queue->wq_list))
14560                 list_del(&queue->wq_list);
14561
14562         while (!list_empty(&queue->page_list)) {
14563                 list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
14564                                  list);
14565                 dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
14566                                   dmabuf->virt, dmabuf->phys);
14567                 kfree(dmabuf);
14568         }
14569         if (queue->rqbp) {
14570                 lpfc_free_rq_buffer(queue->phba, queue);
14571                 kfree(queue->rqbp);
14572         }
14573
14574         if (!list_empty(&queue->cpu_list))
14575                 list_del(&queue->cpu_list);
14576
14577         kfree(queue);
14578         return;
14579 }
14580
14581 /**
14582  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
14583  * @phba: The HBA that this queue is being created on.
14584  * @page_size: The size of a queue page
14585  * @entry_size: The size of each queue entry for this queue.
14586  * @entry count: The number of entries that this queue will handle.
14587  * @cpu: The cpu that will primarily utilize this queue.
14588  *
14589  * This function allocates a queue structure and the DMAable memory used for
14590  * the host resident queue. This function must be called before creating the
14591  * queue on the HBA.
14592  **/
14593 struct lpfc_queue *
14594 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
14595                       uint32_t entry_size, uint32_t entry_count, int cpu)
14596 {
14597         struct lpfc_queue *queue;
14598         struct lpfc_dmabuf *dmabuf;
14599         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
14600         uint16_t x, pgcnt;
14601
14602         if (!phba->sli4_hba.pc_sli4_params.supported)
14603                 hw_page_size = page_size;
14604
14605         pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
14606
14607         /* If needed, Adjust page count to match the max the adapter supports */
14608         if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
14609                 pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
14610
14611         queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
14612                              GFP_KERNEL, cpu_to_node(cpu));
14613         if (!queue)
14614                 return NULL;
14615
14616         INIT_LIST_HEAD(&queue->list);
14617         INIT_LIST_HEAD(&queue->_poll_list);
14618         INIT_LIST_HEAD(&queue->wq_list);
14619         INIT_LIST_HEAD(&queue->wqfull_list);
14620         INIT_LIST_HEAD(&queue->page_list);
14621         INIT_LIST_HEAD(&queue->child_list);
14622         INIT_LIST_HEAD(&queue->cpu_list);
14623
14624         /* Set queue parameters now.  If the system cannot provide memory
14625          * resources, the free routine needs to know what was allocated.
14626          */
14627         queue->page_count = pgcnt;
14628         queue->q_pgs = (void **)&queue[1];
14629         queue->entry_cnt_per_pg = hw_page_size / entry_size;
14630         queue->entry_size = entry_size;
14631         queue->entry_count = entry_count;
14632         queue->page_size = hw_page_size;
14633         queue->phba = phba;
14634
14635         for (x = 0; x < queue->page_count; x++) {
14636                 dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
14637                                       dev_to_node(&phba->pcidev->dev));
14638                 if (!dmabuf)
14639                         goto out_fail;
14640                 dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
14641                                                   hw_page_size, &dmabuf->phys,
14642                                                   GFP_KERNEL);
14643                 if (!dmabuf->virt) {
14644                         kfree(dmabuf);
14645                         goto out_fail;
14646                 }
14647                 dmabuf->buffer_tag = x;
14648                 list_add_tail(&dmabuf->list, &queue->page_list);
14649                 /* use lpfc_sli4_qe to index a paritcular entry in this page */
14650                 queue->q_pgs[x] = dmabuf->virt;
14651         }
14652         INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
14653         INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
14654         INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
14655         INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
14656
14657         /* notify_interval will be set during q creation */
14658
14659         return queue;
14660 out_fail:
14661         lpfc_sli4_queue_free(queue);
14662         return NULL;
14663 }
14664
14665 /**
14666  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
14667  * @phba: HBA structure that indicates port to create a queue on.
14668  * @pci_barset: PCI BAR set flag.
14669  *
14670  * This function shall perform iomap of the specified PCI BAR address to host
14671  * memory address if not already done so and return it. The returned host
14672  * memory address can be NULL.
14673  */
14674 static void __iomem *
14675 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
14676 {
14677         if (!phba->pcidev)
14678                 return NULL;
14679
14680         switch (pci_barset) {
14681         case WQ_PCI_BAR_0_AND_1:
14682                 return phba->pci_bar0_memmap_p;
14683         case WQ_PCI_BAR_2_AND_3:
14684                 return phba->pci_bar2_memmap_p;
14685         case WQ_PCI_BAR_4_AND_5:
14686                 return phba->pci_bar4_memmap_p;
14687         default:
14688                 break;
14689         }
14690         return NULL;
14691 }
14692
14693 /**
14694  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
14695  * @phba: HBA structure that EQs are on.
14696  * @startq: The starting EQ index to modify
14697  * @numq: The number of EQs (consecutive indexes) to modify
14698  * @usdelay: amount of delay
14699  *
14700  * This function revises the EQ delay on 1 or more EQs. The EQ delay
14701  * is set either by writing to a register (if supported by the SLI Port)
14702  * or by mailbox command. The mailbox command allows several EQs to be
14703  * updated at once.
14704  *
14705  * The @phba struct is used to send a mailbox command to HBA. The @startq
14706  * is used to get the starting EQ index to change. The @numq value is
14707  * used to specify how many consecutive EQ indexes, starting at EQ index,
14708  * are to be changed. This function is asynchronous and will wait for any
14709  * mailbox commands to finish before returning.
14710  *
14711  * On success this function will return a zero. If unable to allocate
14712  * enough memory this function will return -ENOMEM. If a mailbox command
14713  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
14714  * have had their delay multipler changed.
14715  **/
14716 void
14717 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
14718                          uint32_t numq, uint32_t usdelay)
14719 {
14720         struct lpfc_mbx_modify_eq_delay *eq_delay;
14721         LPFC_MBOXQ_t *mbox;
14722         struct lpfc_queue *eq;
14723         int cnt = 0, rc, length;
14724         uint32_t shdr_status, shdr_add_status;
14725         uint32_t dmult;
14726         int qidx;
14727         union lpfc_sli4_cfg_shdr *shdr;
14728
14729         if (startq >= phba->cfg_irq_chann)
14730                 return;
14731
14732         if (usdelay > 0xFFFF) {
14733                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
14734                                 "6429 usdelay %d too large. Scaled down to "
14735                                 "0xFFFF.\n", usdelay);
14736                 usdelay = 0xFFFF;
14737         }
14738
14739         /* set values by EQ_DELAY register if supported */
14740         if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
14741                 for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
14742                         eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
14743                         if (!eq)
14744                                 continue;
14745
14746                         lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
14747
14748                         if (++cnt >= numq)
14749                                 break;
14750                 }
14751                 return;
14752         }
14753
14754         /* Otherwise, set values by mailbox cmd */
14755
14756         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14757         if (!mbox) {
14758                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_FCP | LOG_NVME,
14759                                 "6428 Failed allocating mailbox cmd buffer."
14760                                 " EQ delay was not set.\n");
14761                 return;
14762         }
14763         length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
14764                   sizeof(struct lpfc_sli4_cfg_mhdr));
14765         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14766                          LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
14767                          length, LPFC_SLI4_MBX_EMBED);
14768         eq_delay = &mbox->u.mqe.un.eq_delay;
14769
14770         /* Calculate delay multiper from maximum interrupt per second */
14771         dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
14772         if (dmult)
14773                 dmult--;
14774         if (dmult > LPFC_DMULT_MAX)
14775                 dmult = LPFC_DMULT_MAX;
14776
14777         for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
14778                 eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
14779                 if (!eq)
14780                         continue;
14781                 eq->q_mode = usdelay;
14782                 eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
14783                 eq_delay->u.request.eq[cnt].phase = 0;
14784                 eq_delay->u.request.eq[cnt].delay_multi = dmult;
14785
14786                 if (++cnt >= numq)
14787                         break;
14788         }
14789         eq_delay->u.request.num_eq = cnt;
14790
14791         mbox->vport = phba->pport;
14792         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14793         mbox->ctx_buf = NULL;
14794         mbox->ctx_ndlp = NULL;
14795         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14796         shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
14797         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14798         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14799         if (shdr_status || shdr_add_status || rc) {
14800                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14801                                 "2512 MODIFY_EQ_DELAY mailbox failed with "
14802                                 "status x%x add_status x%x, mbx status x%x\n",
14803                                 shdr_status, shdr_add_status, rc);
14804         }
14805         mempool_free(mbox, phba->mbox_mem_pool);
14806         return;
14807 }
14808
14809 /**
14810  * lpfc_eq_create - Create an Event Queue on the HBA
14811  * @phba: HBA structure that indicates port to create a queue on.
14812  * @eq: The queue structure to use to create the event queue.
14813  * @imax: The maximum interrupt per second limit.
14814  *
14815  * This function creates an event queue, as detailed in @eq, on a port,
14816  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
14817  *
14818  * The @phba struct is used to send mailbox command to HBA. The @eq struct
14819  * is used to get the entry count and entry size that are necessary to
14820  * determine the number of pages to allocate and use for this queue. This
14821  * function will send the EQ_CREATE mailbox command to the HBA to setup the
14822  * event queue. This function is asynchronous and will wait for the mailbox
14823  * command to finish before continuing.
14824  *
14825  * On success this function will return a zero. If unable to allocate enough
14826  * memory this function will return -ENOMEM. If the queue create mailbox command
14827  * fails this function will return -ENXIO.
14828  **/
14829 int
14830 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
14831 {
14832         struct lpfc_mbx_eq_create *eq_create;
14833         LPFC_MBOXQ_t *mbox;
14834         int rc, length, status = 0;
14835         struct lpfc_dmabuf *dmabuf;
14836         uint32_t shdr_status, shdr_add_status;
14837         union lpfc_sli4_cfg_shdr *shdr;
14838         uint16_t dmult;
14839         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
14840
14841         /* sanity check on queue memory */
14842         if (!eq)
14843                 return -ENODEV;
14844         if (!phba->sli4_hba.pc_sli4_params.supported)
14845                 hw_page_size = SLI4_PAGE_SIZE;
14846
14847         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14848         if (!mbox)
14849                 return -ENOMEM;
14850         length = (sizeof(struct lpfc_mbx_eq_create) -
14851                   sizeof(struct lpfc_sli4_cfg_mhdr));
14852         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14853                          LPFC_MBOX_OPCODE_EQ_CREATE,
14854                          length, LPFC_SLI4_MBX_EMBED);
14855         eq_create = &mbox->u.mqe.un.eq_create;
14856         shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
14857         bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
14858                eq->page_count);
14859         bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
14860                LPFC_EQE_SIZE);
14861         bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
14862
14863         /* Use version 2 of CREATE_EQ if eqav is set */
14864         if (phba->sli4_hba.pc_sli4_params.eqav) {
14865                 bf_set(lpfc_mbox_hdr_version, &shdr->request,
14866                        LPFC_Q_CREATE_VERSION_2);
14867                 bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
14868                        phba->sli4_hba.pc_sli4_params.eqav);
14869         }
14870
14871         /* don't setup delay multiplier using EQ_CREATE */
14872         dmult = 0;
14873         bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
14874                dmult);
14875         switch (eq->entry_count) {
14876         default:
14877                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
14878                                 "0360 Unsupported EQ count. (%d)\n",
14879                                 eq->entry_count);
14880                 if (eq->entry_count < 256) {
14881                         status = -EINVAL;
14882                         goto out;
14883                 }
14884                 /* fall through - otherwise default to smallest count */
14885         case 256:
14886                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14887                        LPFC_EQ_CNT_256);
14888                 break;
14889         case 512:
14890                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14891                        LPFC_EQ_CNT_512);
14892                 break;
14893         case 1024:
14894                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14895                        LPFC_EQ_CNT_1024);
14896                 break;
14897         case 2048:
14898                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14899                        LPFC_EQ_CNT_2048);
14900                 break;
14901         case 4096:
14902                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
14903                        LPFC_EQ_CNT_4096);
14904                 break;
14905         }
14906         list_for_each_entry(dmabuf, &eq->page_list, list) {
14907                 memset(dmabuf->virt, 0, hw_page_size);
14908                 eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
14909                                         putPaddrLow(dmabuf->phys);
14910                 eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
14911                                         putPaddrHigh(dmabuf->phys);
14912         }
14913         mbox->vport = phba->pport;
14914         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
14915         mbox->ctx_buf = NULL;
14916         mbox->ctx_ndlp = NULL;
14917         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
14918         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
14919         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
14920         if (shdr_status || shdr_add_status || rc) {
14921                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
14922                                 "2500 EQ_CREATE mailbox failed with "
14923                                 "status x%x add_status x%x, mbx status x%x\n",
14924                                 shdr_status, shdr_add_status, rc);
14925                 status = -ENXIO;
14926         }
14927         eq->type = LPFC_EQ;
14928         eq->subtype = LPFC_NONE;
14929         eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
14930         if (eq->queue_id == 0xFFFF)
14931                 status = -ENXIO;
14932         eq->host_index = 0;
14933         eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
14934         eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
14935 out:
14936         mempool_free(mbox, phba->mbox_mem_pool);
14937         return status;
14938 }
14939
14940 /**
14941  * lpfc_cq_create - Create a Completion Queue on the HBA
14942  * @phba: HBA structure that indicates port to create a queue on.
14943  * @cq: The queue structure to use to create the completion queue.
14944  * @eq: The event queue to bind this completion queue to.
14945  *
14946  * This function creates a completion queue, as detailed in @wq, on a port,
14947  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
14948  *
14949  * The @phba struct is used to send mailbox command to HBA. The @cq struct
14950  * is used to get the entry count and entry size that are necessary to
14951  * determine the number of pages to allocate and use for this queue. The @eq
14952  * is used to indicate which event queue to bind this completion queue to. This
14953  * function will send the CQ_CREATE mailbox command to the HBA to setup the
14954  * completion queue. This function is asynchronous and will wait for the mailbox
14955  * command to finish before continuing.
14956  *
14957  * On success this function will return a zero. If unable to allocate enough
14958  * memory this function will return -ENOMEM. If the queue create mailbox command
14959  * fails this function will return -ENXIO.
14960  **/
14961 int
14962 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
14963                struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
14964 {
14965         struct lpfc_mbx_cq_create *cq_create;
14966         struct lpfc_dmabuf *dmabuf;
14967         LPFC_MBOXQ_t *mbox;
14968         int rc, length, status = 0;
14969         uint32_t shdr_status, shdr_add_status;
14970         union lpfc_sli4_cfg_shdr *shdr;
14971
14972         /* sanity check on queue memory */
14973         if (!cq || !eq)
14974                 return -ENODEV;
14975
14976         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
14977         if (!mbox)
14978                 return -ENOMEM;
14979         length = (sizeof(struct lpfc_mbx_cq_create) -
14980                   sizeof(struct lpfc_sli4_cfg_mhdr));
14981         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
14982                          LPFC_MBOX_OPCODE_CQ_CREATE,
14983                          length, LPFC_SLI4_MBX_EMBED);
14984         cq_create = &mbox->u.mqe.un.cq_create;
14985         shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
14986         bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
14987                     cq->page_count);
14988         bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
14989         bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
14990         bf_set(lpfc_mbox_hdr_version, &shdr->request,
14991                phba->sli4_hba.pc_sli4_params.cqv);
14992         if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
14993                 bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
14994                        (cq->page_size / SLI4_PAGE_SIZE));
14995                 bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
14996                        eq->queue_id);
14997                 bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
14998                        phba->sli4_hba.pc_sli4_params.cqav);
14999         } else {
15000                 bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
15001                        eq->queue_id);
15002         }
15003         switch (cq->entry_count) {
15004         case 2048:
15005         case 4096:
15006                 if (phba->sli4_hba.pc_sli4_params.cqv ==
15007                     LPFC_Q_CREATE_VERSION_2) {
15008                         cq_create->u.request.context.lpfc_cq_context_count =
15009                                 cq->entry_count;
15010                         bf_set(lpfc_cq_context_count,
15011                                &cq_create->u.request.context,
15012                                LPFC_CQ_CNT_WORD7);
15013                         break;
15014                 }
15015                 /* fall through */
15016         default:
15017                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15018                                 "0361 Unsupported CQ count: "
15019                                 "entry cnt %d sz %d pg cnt %d\n",
15020                                 cq->entry_count, cq->entry_size,
15021                                 cq->page_count);
15022                 if (cq->entry_count < 256) {
15023                         status = -EINVAL;
15024                         goto out;
15025                 }
15026                 /* fall through - otherwise default to smallest count */
15027         case 256:
15028                 bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15029                        LPFC_CQ_CNT_256);
15030                 break;
15031         case 512:
15032                 bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15033                        LPFC_CQ_CNT_512);
15034                 break;
15035         case 1024:
15036                 bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
15037                        LPFC_CQ_CNT_1024);
15038                 break;
15039         }
15040         list_for_each_entry(dmabuf, &cq->page_list, list) {
15041                 memset(dmabuf->virt, 0, cq->page_size);
15042                 cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15043                                         putPaddrLow(dmabuf->phys);
15044                 cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15045                                         putPaddrHigh(dmabuf->phys);
15046         }
15047         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15048
15049         /* The IOCTL status is embedded in the mailbox subheader. */
15050         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15051         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15052         if (shdr_status || shdr_add_status || rc) {
15053                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15054                                 "2501 CQ_CREATE mailbox failed with "
15055                                 "status x%x add_status x%x, mbx status x%x\n",
15056                                 shdr_status, shdr_add_status, rc);
15057                 status = -ENXIO;
15058                 goto out;
15059         }
15060         cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15061         if (cq->queue_id == 0xFFFF) {
15062                 status = -ENXIO;
15063                 goto out;
15064         }
15065         /* link the cq onto the parent eq child list */
15066         list_add_tail(&cq->list, &eq->child_list);
15067         /* Set up completion queue's type and subtype */
15068         cq->type = type;
15069         cq->subtype = subtype;
15070         cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
15071         cq->assoc_qid = eq->queue_id;
15072         cq->assoc_qp = eq;
15073         cq->host_index = 0;
15074         cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
15075         cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
15076
15077         if (cq->queue_id > phba->sli4_hba.cq_max)
15078                 phba->sli4_hba.cq_max = cq->queue_id;
15079 out:
15080         mempool_free(mbox, phba->mbox_mem_pool);
15081         return status;
15082 }
15083
15084 /**
15085  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
15086  * @phba: HBA structure that indicates port to create a queue on.
15087  * @cqp: The queue structure array to use to create the completion queues.
15088  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
15089  *
15090  * This function creates a set of  completion queue, s to support MRQ
15091  * as detailed in @cqp, on a port,
15092  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
15093  *
15094  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15095  * is used to get the entry count and entry size that are necessary to
15096  * determine the number of pages to allocate and use for this queue. The @eq
15097  * is used to indicate which event queue to bind this completion queue to. This
15098  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
15099  * completion queue. This function is asynchronous and will wait for the mailbox
15100  * command to finish before continuing.
15101  *
15102  * On success this function will return a zero. If unable to allocate enough
15103  * memory this function will return -ENOMEM. If the queue create mailbox command
15104  * fails this function will return -ENXIO.
15105  **/
15106 int
15107 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
15108                    struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
15109                    uint32_t subtype)
15110 {
15111         struct lpfc_queue *cq;
15112         struct lpfc_queue *eq;
15113         struct lpfc_mbx_cq_create_set *cq_set;
15114         struct lpfc_dmabuf *dmabuf;
15115         LPFC_MBOXQ_t *mbox;
15116         int rc, length, alloclen, status = 0;
15117         int cnt, idx, numcq, page_idx = 0;
15118         uint32_t shdr_status, shdr_add_status;
15119         union lpfc_sli4_cfg_shdr *shdr;
15120         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15121
15122         /* sanity check on queue memory */
15123         numcq = phba->cfg_nvmet_mrq;
15124         if (!cqp || !hdwq || !numcq)
15125                 return -ENODEV;
15126
15127         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15128         if (!mbox)
15129                 return -ENOMEM;
15130
15131         length = sizeof(struct lpfc_mbx_cq_create_set);
15132         length += ((numcq * cqp[0]->page_count) *
15133                    sizeof(struct dma_address));
15134         alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15135                         LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
15136                         LPFC_SLI4_MBX_NEMBED);
15137         if (alloclen < length) {
15138                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15139                                 "3098 Allocated DMA memory size (%d) is "
15140                                 "less than the requested DMA memory size "
15141                                 "(%d)\n", alloclen, length);
15142                 status = -ENOMEM;
15143                 goto out;
15144         }
15145         cq_set = mbox->sge_array->addr[0];
15146         shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
15147         bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
15148
15149         for (idx = 0; idx < numcq; idx++) {
15150                 cq = cqp[idx];
15151                 eq = hdwq[idx].hba_eq;
15152                 if (!cq || !eq) {
15153                         status = -ENOMEM;
15154                         goto out;
15155                 }
15156                 if (!phba->sli4_hba.pc_sli4_params.supported)
15157                         hw_page_size = cq->page_size;
15158
15159                 switch (idx) {
15160                 case 0:
15161                         bf_set(lpfc_mbx_cq_create_set_page_size,
15162                                &cq_set->u.request,
15163                                (hw_page_size / SLI4_PAGE_SIZE));
15164                         bf_set(lpfc_mbx_cq_create_set_num_pages,
15165                                &cq_set->u.request, cq->page_count);
15166                         bf_set(lpfc_mbx_cq_create_set_evt,
15167                                &cq_set->u.request, 1);
15168                         bf_set(lpfc_mbx_cq_create_set_valid,
15169                                &cq_set->u.request, 1);
15170                         bf_set(lpfc_mbx_cq_create_set_cqe_size,
15171                                &cq_set->u.request, 0);
15172                         bf_set(lpfc_mbx_cq_create_set_num_cq,
15173                                &cq_set->u.request, numcq);
15174                         bf_set(lpfc_mbx_cq_create_set_autovalid,
15175                                &cq_set->u.request,
15176                                phba->sli4_hba.pc_sli4_params.cqav);
15177                         switch (cq->entry_count) {
15178                         case 2048:
15179                         case 4096:
15180                                 if (phba->sli4_hba.pc_sli4_params.cqv ==
15181                                     LPFC_Q_CREATE_VERSION_2) {
15182                                         bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15183                                                &cq_set->u.request,
15184                                                 cq->entry_count);
15185                                         bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15186                                                &cq_set->u.request,
15187                                                LPFC_CQ_CNT_WORD7);
15188                                         break;
15189                                 }
15190                                 /* fall through */
15191                         default:
15192                                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15193                                                 "3118 Bad CQ count. (%d)\n",
15194                                                 cq->entry_count);
15195                                 if (cq->entry_count < 256) {
15196                                         status = -EINVAL;
15197                                         goto out;
15198                                 }
15199                                 /* fall through - otherwise default to smallest */
15200                         case 256:
15201                                 bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15202                                        &cq_set->u.request, LPFC_CQ_CNT_256);
15203                                 break;
15204                         case 512:
15205                                 bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15206                                        &cq_set->u.request, LPFC_CQ_CNT_512);
15207                                 break;
15208                         case 1024:
15209                                 bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
15210                                        &cq_set->u.request, LPFC_CQ_CNT_1024);
15211                                 break;
15212                         }
15213                         bf_set(lpfc_mbx_cq_create_set_eq_id0,
15214                                &cq_set->u.request, eq->queue_id);
15215                         break;
15216                 case 1:
15217                         bf_set(lpfc_mbx_cq_create_set_eq_id1,
15218                                &cq_set->u.request, eq->queue_id);
15219                         break;
15220                 case 2:
15221                         bf_set(lpfc_mbx_cq_create_set_eq_id2,
15222                                &cq_set->u.request, eq->queue_id);
15223                         break;
15224                 case 3:
15225                         bf_set(lpfc_mbx_cq_create_set_eq_id3,
15226                                &cq_set->u.request, eq->queue_id);
15227                         break;
15228                 case 4:
15229                         bf_set(lpfc_mbx_cq_create_set_eq_id4,
15230                                &cq_set->u.request, eq->queue_id);
15231                         break;
15232                 case 5:
15233                         bf_set(lpfc_mbx_cq_create_set_eq_id5,
15234                                &cq_set->u.request, eq->queue_id);
15235                         break;
15236                 case 6:
15237                         bf_set(lpfc_mbx_cq_create_set_eq_id6,
15238                                &cq_set->u.request, eq->queue_id);
15239                         break;
15240                 case 7:
15241                         bf_set(lpfc_mbx_cq_create_set_eq_id7,
15242                                &cq_set->u.request, eq->queue_id);
15243                         break;
15244                 case 8:
15245                         bf_set(lpfc_mbx_cq_create_set_eq_id8,
15246                                &cq_set->u.request, eq->queue_id);
15247                         break;
15248                 case 9:
15249                         bf_set(lpfc_mbx_cq_create_set_eq_id9,
15250                                &cq_set->u.request, eq->queue_id);
15251                         break;
15252                 case 10:
15253                         bf_set(lpfc_mbx_cq_create_set_eq_id10,
15254                                &cq_set->u.request, eq->queue_id);
15255                         break;
15256                 case 11:
15257                         bf_set(lpfc_mbx_cq_create_set_eq_id11,
15258                                &cq_set->u.request, eq->queue_id);
15259                         break;
15260                 case 12:
15261                         bf_set(lpfc_mbx_cq_create_set_eq_id12,
15262                                &cq_set->u.request, eq->queue_id);
15263                         break;
15264                 case 13:
15265                         bf_set(lpfc_mbx_cq_create_set_eq_id13,
15266                                &cq_set->u.request, eq->queue_id);
15267                         break;
15268                 case 14:
15269                         bf_set(lpfc_mbx_cq_create_set_eq_id14,
15270                                &cq_set->u.request, eq->queue_id);
15271                         break;
15272                 case 15:
15273                         bf_set(lpfc_mbx_cq_create_set_eq_id15,
15274                                &cq_set->u.request, eq->queue_id);
15275                         break;
15276                 }
15277
15278                 /* link the cq onto the parent eq child list */
15279                 list_add_tail(&cq->list, &eq->child_list);
15280                 /* Set up completion queue's type and subtype */
15281                 cq->type = type;
15282                 cq->subtype = subtype;
15283                 cq->assoc_qid = eq->queue_id;
15284                 cq->assoc_qp = eq;
15285                 cq->host_index = 0;
15286                 cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
15287                 cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
15288                                          cq->entry_count);
15289                 cq->chann = idx;
15290
15291                 rc = 0;
15292                 list_for_each_entry(dmabuf, &cq->page_list, list) {
15293                         memset(dmabuf->virt, 0, hw_page_size);
15294                         cnt = page_idx + dmabuf->buffer_tag;
15295                         cq_set->u.request.page[cnt].addr_lo =
15296                                         putPaddrLow(dmabuf->phys);
15297                         cq_set->u.request.page[cnt].addr_hi =
15298                                         putPaddrHigh(dmabuf->phys);
15299                         rc++;
15300                 }
15301                 page_idx += rc;
15302         }
15303
15304         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15305
15306         /* The IOCTL status is embedded in the mailbox subheader. */
15307         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15308         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15309         if (shdr_status || shdr_add_status || rc) {
15310                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15311                                 "3119 CQ_CREATE_SET mailbox failed with "
15312                                 "status x%x add_status x%x, mbx status x%x\n",
15313                                 shdr_status, shdr_add_status, rc);
15314                 status = -ENXIO;
15315                 goto out;
15316         }
15317         rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
15318         if (rc == 0xFFFF) {
15319                 status = -ENXIO;
15320                 goto out;
15321         }
15322
15323         for (idx = 0; idx < numcq; idx++) {
15324                 cq = cqp[idx];
15325                 cq->queue_id = rc + idx;
15326                 if (cq->queue_id > phba->sli4_hba.cq_max)
15327                         phba->sli4_hba.cq_max = cq->queue_id;
15328         }
15329
15330 out:
15331         lpfc_sli4_mbox_cmd_free(phba, mbox);
15332         return status;
15333 }
15334
15335 /**
15336  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
15337  * @phba: HBA structure that indicates port to create a queue on.
15338  * @mq: The queue structure to use to create the mailbox queue.
15339  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
15340  * @cq: The completion queue to associate with this cq.
15341  *
15342  * This function provides failback (fb) functionality when the
15343  * mq_create_ext fails on older FW generations.  It's purpose is identical
15344  * to mq_create_ext otherwise.
15345  *
15346  * This routine cannot fail as all attributes were previously accessed and
15347  * initialized in mq_create_ext.
15348  **/
15349 static void
15350 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
15351                        LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
15352 {
15353         struct lpfc_mbx_mq_create *mq_create;
15354         struct lpfc_dmabuf *dmabuf;
15355         int length;
15356
15357         length = (sizeof(struct lpfc_mbx_mq_create) -
15358                   sizeof(struct lpfc_sli4_cfg_mhdr));
15359         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15360                          LPFC_MBOX_OPCODE_MQ_CREATE,
15361                          length, LPFC_SLI4_MBX_EMBED);
15362         mq_create = &mbox->u.mqe.un.mq_create;
15363         bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
15364                mq->page_count);
15365         bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
15366                cq->queue_id);
15367         bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
15368         switch (mq->entry_count) {
15369         case 16:
15370                 bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15371                        LPFC_MQ_RING_SIZE_16);
15372                 break;
15373         case 32:
15374                 bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15375                        LPFC_MQ_RING_SIZE_32);
15376                 break;
15377         case 64:
15378                 bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15379                        LPFC_MQ_RING_SIZE_64);
15380                 break;
15381         case 128:
15382                 bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
15383                        LPFC_MQ_RING_SIZE_128);
15384                 break;
15385         }
15386         list_for_each_entry(dmabuf, &mq->page_list, list) {
15387                 mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15388                         putPaddrLow(dmabuf->phys);
15389                 mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15390                         putPaddrHigh(dmabuf->phys);
15391         }
15392 }
15393
15394 /**
15395  * lpfc_mq_create - Create a mailbox Queue on the HBA
15396  * @phba: HBA structure that indicates port to create a queue on.
15397  * @mq: The queue structure to use to create the mailbox queue.
15398  * @cq: The completion queue to associate with this cq.
15399  * @subtype: The queue's subtype.
15400  *
15401  * This function creates a mailbox queue, as detailed in @mq, on a port,
15402  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
15403  *
15404  * The @phba struct is used to send mailbox command to HBA. The @cq struct
15405  * is used to get the entry count and entry size that are necessary to
15406  * determine the number of pages to allocate and use for this queue. This
15407  * function will send the MQ_CREATE mailbox command to the HBA to setup the
15408  * mailbox queue. This function is asynchronous and will wait for the mailbox
15409  * command to finish before continuing.
15410  *
15411  * On success this function will return a zero. If unable to allocate enough
15412  * memory this function will return -ENOMEM. If the queue create mailbox command
15413  * fails this function will return -ENXIO.
15414  **/
15415 int32_t
15416 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
15417                struct lpfc_queue *cq, uint32_t subtype)
15418 {
15419         struct lpfc_mbx_mq_create *mq_create;
15420         struct lpfc_mbx_mq_create_ext *mq_create_ext;
15421         struct lpfc_dmabuf *dmabuf;
15422         LPFC_MBOXQ_t *mbox;
15423         int rc, length, status = 0;
15424         uint32_t shdr_status, shdr_add_status;
15425         union lpfc_sli4_cfg_shdr *shdr;
15426         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15427
15428         /* sanity check on queue memory */
15429         if (!mq || !cq)
15430                 return -ENODEV;
15431         if (!phba->sli4_hba.pc_sli4_params.supported)
15432                 hw_page_size = SLI4_PAGE_SIZE;
15433
15434         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15435         if (!mbox)
15436                 return -ENOMEM;
15437         length = (sizeof(struct lpfc_mbx_mq_create_ext) -
15438                   sizeof(struct lpfc_sli4_cfg_mhdr));
15439         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15440                          LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
15441                          length, LPFC_SLI4_MBX_EMBED);
15442
15443         mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
15444         shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
15445         bf_set(lpfc_mbx_mq_create_ext_num_pages,
15446                &mq_create_ext->u.request, mq->page_count);
15447         bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
15448                &mq_create_ext->u.request, 1);
15449         bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
15450                &mq_create_ext->u.request, 1);
15451         bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
15452                &mq_create_ext->u.request, 1);
15453         bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
15454                &mq_create_ext->u.request, 1);
15455         bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
15456                &mq_create_ext->u.request, 1);
15457         bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
15458         bf_set(lpfc_mbox_hdr_version, &shdr->request,
15459                phba->sli4_hba.pc_sli4_params.mqv);
15460         if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
15461                 bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
15462                        cq->queue_id);
15463         else
15464                 bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
15465                        cq->queue_id);
15466         switch (mq->entry_count) {
15467         default:
15468                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15469                                 "0362 Unsupported MQ count. (%d)\n",
15470                                 mq->entry_count);
15471                 if (mq->entry_count < 16) {
15472                         status = -EINVAL;
15473                         goto out;
15474                 }
15475                 /* fall through - otherwise default to smallest count */
15476         case 16:
15477                 bf_set(lpfc_mq_context_ring_size,
15478                        &mq_create_ext->u.request.context,
15479                        LPFC_MQ_RING_SIZE_16);
15480                 break;
15481         case 32:
15482                 bf_set(lpfc_mq_context_ring_size,
15483                        &mq_create_ext->u.request.context,
15484                        LPFC_MQ_RING_SIZE_32);
15485                 break;
15486         case 64:
15487                 bf_set(lpfc_mq_context_ring_size,
15488                        &mq_create_ext->u.request.context,
15489                        LPFC_MQ_RING_SIZE_64);
15490                 break;
15491         case 128:
15492                 bf_set(lpfc_mq_context_ring_size,
15493                        &mq_create_ext->u.request.context,
15494                        LPFC_MQ_RING_SIZE_128);
15495                 break;
15496         }
15497         list_for_each_entry(dmabuf, &mq->page_list, list) {
15498                 memset(dmabuf->virt, 0, hw_page_size);
15499                 mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
15500                                         putPaddrLow(dmabuf->phys);
15501                 mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
15502                                         putPaddrHigh(dmabuf->phys);
15503         }
15504         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15505         mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
15506                               &mq_create_ext->u.response);
15507         if (rc != MBX_SUCCESS) {
15508                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15509                                 "2795 MQ_CREATE_EXT failed with "
15510                                 "status x%x. Failback to MQ_CREATE.\n",
15511                                 rc);
15512                 lpfc_mq_create_fb_init(phba, mq, mbox, cq);
15513                 mq_create = &mbox->u.mqe.un.mq_create;
15514                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15515                 shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
15516                 mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
15517                                       &mq_create->u.response);
15518         }
15519
15520         /* The IOCTL status is embedded in the mailbox subheader. */
15521         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15522         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15523         if (shdr_status || shdr_add_status || rc) {
15524                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15525                                 "2502 MQ_CREATE mailbox failed with "
15526                                 "status x%x add_status x%x, mbx status x%x\n",
15527                                 shdr_status, shdr_add_status, rc);
15528                 status = -ENXIO;
15529                 goto out;
15530         }
15531         if (mq->queue_id == 0xFFFF) {
15532                 status = -ENXIO;
15533                 goto out;
15534         }
15535         mq->type = LPFC_MQ;
15536         mq->assoc_qid = cq->queue_id;
15537         mq->subtype = subtype;
15538         mq->host_index = 0;
15539         mq->hba_index = 0;
15540
15541         /* link the mq onto the parent cq child list */
15542         list_add_tail(&mq->list, &cq->child_list);
15543 out:
15544         mempool_free(mbox, phba->mbox_mem_pool);
15545         return status;
15546 }
15547
15548 /**
15549  * lpfc_wq_create - Create a Work Queue on the HBA
15550  * @phba: HBA structure that indicates port to create a queue on.
15551  * @wq: The queue structure to use to create the work queue.
15552  * @cq: The completion queue to bind this work queue to.
15553  * @subtype: The subtype of the work queue indicating its functionality.
15554  *
15555  * This function creates a work queue, as detailed in @wq, on a port, described
15556  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
15557  *
15558  * The @phba struct is used to send mailbox command to HBA. The @wq struct
15559  * is used to get the entry count and entry size that are necessary to
15560  * determine the number of pages to allocate and use for this queue. The @cq
15561  * is used to indicate which completion queue to bind this work queue to. This
15562  * function will send the WQ_CREATE mailbox command to the HBA to setup the
15563  * work queue. This function is asynchronous and will wait for the mailbox
15564  * command to finish before continuing.
15565  *
15566  * On success this function will return a zero. If unable to allocate enough
15567  * memory this function will return -ENOMEM. If the queue create mailbox command
15568  * fails this function will return -ENXIO.
15569  **/
15570 int
15571 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
15572                struct lpfc_queue *cq, uint32_t subtype)
15573 {
15574         struct lpfc_mbx_wq_create *wq_create;
15575         struct lpfc_dmabuf *dmabuf;
15576         LPFC_MBOXQ_t *mbox;
15577         int rc, length, status = 0;
15578         uint32_t shdr_status, shdr_add_status;
15579         union lpfc_sli4_cfg_shdr *shdr;
15580         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15581         struct dma_address *page;
15582         void __iomem *bar_memmap_p;
15583         uint32_t db_offset;
15584         uint16_t pci_barset;
15585         uint8_t dpp_barset;
15586         uint32_t dpp_offset;
15587         unsigned long pg_addr;
15588         uint8_t wq_create_version;
15589
15590         /* sanity check on queue memory */
15591         if (!wq || !cq)
15592                 return -ENODEV;
15593         if (!phba->sli4_hba.pc_sli4_params.supported)
15594                 hw_page_size = wq->page_size;
15595
15596         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15597         if (!mbox)
15598                 return -ENOMEM;
15599         length = (sizeof(struct lpfc_mbx_wq_create) -
15600                   sizeof(struct lpfc_sli4_cfg_mhdr));
15601         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15602                          LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
15603                          length, LPFC_SLI4_MBX_EMBED);
15604         wq_create = &mbox->u.mqe.un.wq_create;
15605         shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
15606         bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
15607                     wq->page_count);
15608         bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
15609                     cq->queue_id);
15610
15611         /* wqv is the earliest version supported, NOT the latest */
15612         bf_set(lpfc_mbox_hdr_version, &shdr->request,
15613                phba->sli4_hba.pc_sli4_params.wqv);
15614
15615         if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
15616             (wq->page_size > SLI4_PAGE_SIZE))
15617                 wq_create_version = LPFC_Q_CREATE_VERSION_1;
15618         else
15619                 wq_create_version = LPFC_Q_CREATE_VERSION_0;
15620
15621
15622         if (phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT)
15623                 wq_create_version = LPFC_Q_CREATE_VERSION_1;
15624         else
15625                 wq_create_version = LPFC_Q_CREATE_VERSION_0;
15626
15627         switch (wq_create_version) {
15628         case LPFC_Q_CREATE_VERSION_1:
15629                 bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
15630                        wq->entry_count);
15631                 bf_set(lpfc_mbox_hdr_version, &shdr->request,
15632                        LPFC_Q_CREATE_VERSION_1);
15633
15634                 switch (wq->entry_size) {
15635                 default:
15636                 case 64:
15637                         bf_set(lpfc_mbx_wq_create_wqe_size,
15638                                &wq_create->u.request_1,
15639                                LPFC_WQ_WQE_SIZE_64);
15640                         break;
15641                 case 128:
15642                         bf_set(lpfc_mbx_wq_create_wqe_size,
15643                                &wq_create->u.request_1,
15644                                LPFC_WQ_WQE_SIZE_128);
15645                         break;
15646                 }
15647                 /* Request DPP by default */
15648                 bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
15649                 bf_set(lpfc_mbx_wq_create_page_size,
15650                        &wq_create->u.request_1,
15651                        (wq->page_size / SLI4_PAGE_SIZE));
15652                 page = wq_create->u.request_1.page;
15653                 break;
15654         default:
15655                 page = wq_create->u.request.page;
15656                 break;
15657         }
15658
15659         list_for_each_entry(dmabuf, &wq->page_list, list) {
15660                 memset(dmabuf->virt, 0, hw_page_size);
15661                 page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
15662                 page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
15663         }
15664
15665         if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
15666                 bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
15667
15668         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15669         /* The IOCTL status is embedded in the mailbox subheader. */
15670         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15671         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15672         if (shdr_status || shdr_add_status || rc) {
15673                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15674                                 "2503 WQ_CREATE mailbox failed with "
15675                                 "status x%x add_status x%x, mbx status x%x\n",
15676                                 shdr_status, shdr_add_status, rc);
15677                 status = -ENXIO;
15678                 goto out;
15679         }
15680
15681         if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
15682                 wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
15683                                         &wq_create->u.response);
15684         else
15685                 wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
15686                                         &wq_create->u.response_1);
15687
15688         if (wq->queue_id == 0xFFFF) {
15689                 status = -ENXIO;
15690                 goto out;
15691         }
15692
15693         wq->db_format = LPFC_DB_LIST_FORMAT;
15694         if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
15695                 if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
15696                         wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
15697                                                &wq_create->u.response);
15698                         if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
15699                             (wq->db_format != LPFC_DB_RING_FORMAT)) {
15700                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15701                                                 "3265 WQ[%d] doorbell format "
15702                                                 "not supported: x%x\n",
15703                                                 wq->queue_id, wq->db_format);
15704                                 status = -EINVAL;
15705                                 goto out;
15706                         }
15707                         pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
15708                                             &wq_create->u.response);
15709                         bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15710                                                                    pci_barset);
15711                         if (!bar_memmap_p) {
15712                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15713                                                 "3263 WQ[%d] failed to memmap "
15714                                                 "pci barset:x%x\n",
15715                                                 wq->queue_id, pci_barset);
15716                                 status = -ENOMEM;
15717                                 goto out;
15718                         }
15719                         db_offset = wq_create->u.response.doorbell_offset;
15720                         if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
15721                             (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
15722                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15723                                                 "3252 WQ[%d] doorbell offset "
15724                                                 "not supported: x%x\n",
15725                                                 wq->queue_id, db_offset);
15726                                 status = -EINVAL;
15727                                 goto out;
15728                         }
15729                         wq->db_regaddr = bar_memmap_p + db_offset;
15730                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15731                                         "3264 WQ[%d]: barset:x%x, offset:x%x, "
15732                                         "format:x%x\n", wq->queue_id,
15733                                         pci_barset, db_offset, wq->db_format);
15734                 } else
15735                         wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
15736         } else {
15737                 /* Check if DPP was honored by the firmware */
15738                 wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
15739                                     &wq_create->u.response_1);
15740                 if (wq->dpp_enable) {
15741                         pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
15742                                             &wq_create->u.response_1);
15743                         bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15744                                                                    pci_barset);
15745                         if (!bar_memmap_p) {
15746                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15747                                                 "3267 WQ[%d] failed to memmap "
15748                                                 "pci barset:x%x\n",
15749                                                 wq->queue_id, pci_barset);
15750                                 status = -ENOMEM;
15751                                 goto out;
15752                         }
15753                         db_offset = wq_create->u.response_1.doorbell_offset;
15754                         wq->db_regaddr = bar_memmap_p + db_offset;
15755                         wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
15756                                             &wq_create->u.response_1);
15757                         dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
15758                                             &wq_create->u.response_1);
15759                         bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
15760                                                                    dpp_barset);
15761                         if (!bar_memmap_p) {
15762                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15763                                                 "3268 WQ[%d] failed to memmap "
15764                                                 "pci barset:x%x\n",
15765                                                 wq->queue_id, dpp_barset);
15766                                 status = -ENOMEM;
15767                                 goto out;
15768                         }
15769                         dpp_offset = wq_create->u.response_1.dpp_offset;
15770                         wq->dpp_regaddr = bar_memmap_p + dpp_offset;
15771                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15772                                         "3271 WQ[%d]: barset:x%x, offset:x%x, "
15773                                         "dpp_id:x%x dpp_barset:x%x "
15774                                         "dpp_offset:x%x\n",
15775                                         wq->queue_id, pci_barset, db_offset,
15776                                         wq->dpp_id, dpp_barset, dpp_offset);
15777
15778                         /* Enable combined writes for DPP aperture */
15779                         pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
15780 #ifdef CONFIG_X86
15781                         rc = set_memory_wc(pg_addr, 1);
15782                         if (rc) {
15783                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15784                                         "3272 Cannot setup Combined "
15785                                         "Write on WQ[%d] - disable DPP\n",
15786                                         wq->queue_id);
15787                                 phba->cfg_enable_dpp = 0;
15788                         }
15789 #else
15790                         phba->cfg_enable_dpp = 0;
15791 #endif
15792                 } else
15793                         wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
15794         }
15795         wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
15796         if (wq->pring == NULL) {
15797                 status = -ENOMEM;
15798                 goto out;
15799         }
15800         wq->type = LPFC_WQ;
15801         wq->assoc_qid = cq->queue_id;
15802         wq->subtype = subtype;
15803         wq->host_index = 0;
15804         wq->hba_index = 0;
15805         wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
15806
15807         /* link the wq onto the parent cq child list */
15808         list_add_tail(&wq->list, &cq->child_list);
15809 out:
15810         mempool_free(mbox, phba->mbox_mem_pool);
15811         return status;
15812 }
15813
15814 /**
15815  * lpfc_rq_create - Create a Receive Queue on the HBA
15816  * @phba: HBA structure that indicates port to create a queue on.
15817  * @hrq: The queue structure to use to create the header receive queue.
15818  * @drq: The queue structure to use to create the data receive queue.
15819  * @cq: The completion queue to bind this work queue to.
15820  *
15821  * This function creates a receive buffer queue pair , as detailed in @hrq and
15822  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
15823  * to the HBA.
15824  *
15825  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
15826  * struct is used to get the entry count that is necessary to determine the
15827  * number of pages to use for this queue. The @cq is used to indicate which
15828  * completion queue to bind received buffers that are posted to these queues to.
15829  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
15830  * receive queue pair. This function is asynchronous and will wait for the
15831  * mailbox command to finish before continuing.
15832  *
15833  * On success this function will return a zero. If unable to allocate enough
15834  * memory this function will return -ENOMEM. If the queue create mailbox command
15835  * fails this function will return -ENXIO.
15836  **/
15837 int
15838 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
15839                struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
15840 {
15841         struct lpfc_mbx_rq_create *rq_create;
15842         struct lpfc_dmabuf *dmabuf;
15843         LPFC_MBOXQ_t *mbox;
15844         int rc, length, status = 0;
15845         uint32_t shdr_status, shdr_add_status;
15846         union lpfc_sli4_cfg_shdr *shdr;
15847         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15848         void __iomem *bar_memmap_p;
15849         uint32_t db_offset;
15850         uint16_t pci_barset;
15851
15852         /* sanity check on queue memory */
15853         if (!hrq || !drq || !cq)
15854                 return -ENODEV;
15855         if (!phba->sli4_hba.pc_sli4_params.supported)
15856                 hw_page_size = SLI4_PAGE_SIZE;
15857
15858         if (hrq->entry_count != drq->entry_count)
15859                 return -EINVAL;
15860         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15861         if (!mbox)
15862                 return -ENOMEM;
15863         length = (sizeof(struct lpfc_mbx_rq_create) -
15864                   sizeof(struct lpfc_sli4_cfg_mhdr));
15865         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
15866                          LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
15867                          length, LPFC_SLI4_MBX_EMBED);
15868         rq_create = &mbox->u.mqe.un.rq_create;
15869         shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
15870         bf_set(lpfc_mbox_hdr_version, &shdr->request,
15871                phba->sli4_hba.pc_sli4_params.rqv);
15872         if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
15873                 bf_set(lpfc_rq_context_rqe_count_1,
15874                        &rq_create->u.request.context,
15875                        hrq->entry_count);
15876                 rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
15877                 bf_set(lpfc_rq_context_rqe_size,
15878                        &rq_create->u.request.context,
15879                        LPFC_RQE_SIZE_8);
15880                 bf_set(lpfc_rq_context_page_size,
15881                        &rq_create->u.request.context,
15882                        LPFC_RQ_PAGE_SIZE_4096);
15883         } else {
15884                 switch (hrq->entry_count) {
15885                 default:
15886                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
15887                                         "2535 Unsupported RQ count. (%d)\n",
15888                                         hrq->entry_count);
15889                         if (hrq->entry_count < 512) {
15890                                 status = -EINVAL;
15891                                 goto out;
15892                         }
15893                         /* fall through - otherwise default to smallest count */
15894                 case 512:
15895                         bf_set(lpfc_rq_context_rqe_count,
15896                                &rq_create->u.request.context,
15897                                LPFC_RQ_RING_SIZE_512);
15898                         break;
15899                 case 1024:
15900                         bf_set(lpfc_rq_context_rqe_count,
15901                                &rq_create->u.request.context,
15902                                LPFC_RQ_RING_SIZE_1024);
15903                         break;
15904                 case 2048:
15905                         bf_set(lpfc_rq_context_rqe_count,
15906                                &rq_create->u.request.context,
15907                                LPFC_RQ_RING_SIZE_2048);
15908                         break;
15909                 case 4096:
15910                         bf_set(lpfc_rq_context_rqe_count,
15911                                &rq_create->u.request.context,
15912                                LPFC_RQ_RING_SIZE_4096);
15913                         break;
15914                 }
15915                 bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
15916                        LPFC_HDR_BUF_SIZE);
15917         }
15918         bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
15919                cq->queue_id);
15920         bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
15921                hrq->page_count);
15922         list_for_each_entry(dmabuf, &hrq->page_list, list) {
15923                 memset(dmabuf->virt, 0, hw_page_size);
15924                 rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
15925                                         putPaddrLow(dmabuf->phys);
15926                 rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
15927                                         putPaddrHigh(dmabuf->phys);
15928         }
15929         if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
15930                 bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
15931
15932         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
15933         /* The IOCTL status is embedded in the mailbox subheader. */
15934         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
15935         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
15936         if (shdr_status || shdr_add_status || rc) {
15937                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15938                                 "2504 RQ_CREATE mailbox failed with "
15939                                 "status x%x add_status x%x, mbx status x%x\n",
15940                                 shdr_status, shdr_add_status, rc);
15941                 status = -ENXIO;
15942                 goto out;
15943         }
15944         hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
15945         if (hrq->queue_id == 0xFFFF) {
15946                 status = -ENXIO;
15947                 goto out;
15948         }
15949
15950         if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
15951                 hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
15952                                         &rq_create->u.response);
15953                 if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
15954                     (hrq->db_format != LPFC_DB_RING_FORMAT)) {
15955                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15956                                         "3262 RQ [%d] doorbell format not "
15957                                         "supported: x%x\n", hrq->queue_id,
15958                                         hrq->db_format);
15959                         status = -EINVAL;
15960                         goto out;
15961                 }
15962
15963                 pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
15964                                     &rq_create->u.response);
15965                 bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
15966                 if (!bar_memmap_p) {
15967                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15968                                         "3269 RQ[%d] failed to memmap pci "
15969                                         "barset:x%x\n", hrq->queue_id,
15970                                         pci_barset);
15971                         status = -ENOMEM;
15972                         goto out;
15973                 }
15974
15975                 db_offset = rq_create->u.response.doorbell_offset;
15976                 if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
15977                     (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
15978                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
15979                                         "3270 RQ[%d] doorbell offset not "
15980                                         "supported: x%x\n", hrq->queue_id,
15981                                         db_offset);
15982                         status = -EINVAL;
15983                         goto out;
15984                 }
15985                 hrq->db_regaddr = bar_memmap_p + db_offset;
15986                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
15987                                 "3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
15988                                 "format:x%x\n", hrq->queue_id, pci_barset,
15989                                 db_offset, hrq->db_format);
15990         } else {
15991                 hrq->db_format = LPFC_DB_RING_FORMAT;
15992                 hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
15993         }
15994         hrq->type = LPFC_HRQ;
15995         hrq->assoc_qid = cq->queue_id;
15996         hrq->subtype = subtype;
15997         hrq->host_index = 0;
15998         hrq->hba_index = 0;
15999         hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16000
16001         /* now create the data queue */
16002         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16003                          LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
16004                          length, LPFC_SLI4_MBX_EMBED);
16005         bf_set(lpfc_mbox_hdr_version, &shdr->request,
16006                phba->sli4_hba.pc_sli4_params.rqv);
16007         if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
16008                 bf_set(lpfc_rq_context_rqe_count_1,
16009                        &rq_create->u.request.context, hrq->entry_count);
16010                 if (subtype == LPFC_NVMET)
16011                         rq_create->u.request.context.buffer_size =
16012                                 LPFC_NVMET_DATA_BUF_SIZE;
16013                 else
16014                         rq_create->u.request.context.buffer_size =
16015                                 LPFC_DATA_BUF_SIZE;
16016                 bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
16017                        LPFC_RQE_SIZE_8);
16018                 bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
16019                        (PAGE_SIZE/SLI4_PAGE_SIZE));
16020         } else {
16021                 switch (drq->entry_count) {
16022                 default:
16023                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16024                                         "2536 Unsupported RQ count. (%d)\n",
16025                                         drq->entry_count);
16026                         if (drq->entry_count < 512) {
16027                                 status = -EINVAL;
16028                                 goto out;
16029                         }
16030                         /* fall through - otherwise default to smallest count */
16031                 case 512:
16032                         bf_set(lpfc_rq_context_rqe_count,
16033                                &rq_create->u.request.context,
16034                                LPFC_RQ_RING_SIZE_512);
16035                         break;
16036                 case 1024:
16037                         bf_set(lpfc_rq_context_rqe_count,
16038                                &rq_create->u.request.context,
16039                                LPFC_RQ_RING_SIZE_1024);
16040                         break;
16041                 case 2048:
16042                         bf_set(lpfc_rq_context_rqe_count,
16043                                &rq_create->u.request.context,
16044                                LPFC_RQ_RING_SIZE_2048);
16045                         break;
16046                 case 4096:
16047                         bf_set(lpfc_rq_context_rqe_count,
16048                                &rq_create->u.request.context,
16049                                LPFC_RQ_RING_SIZE_4096);
16050                         break;
16051                 }
16052                 if (subtype == LPFC_NVMET)
16053                         bf_set(lpfc_rq_context_buf_size,
16054                                &rq_create->u.request.context,
16055                                LPFC_NVMET_DATA_BUF_SIZE);
16056                 else
16057                         bf_set(lpfc_rq_context_buf_size,
16058                                &rq_create->u.request.context,
16059                                LPFC_DATA_BUF_SIZE);
16060         }
16061         bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
16062                cq->queue_id);
16063         bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
16064                drq->page_count);
16065         list_for_each_entry(dmabuf, &drq->page_list, list) {
16066                 rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16067                                         putPaddrLow(dmabuf->phys);
16068                 rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16069                                         putPaddrHigh(dmabuf->phys);
16070         }
16071         if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16072                 bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
16073         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16074         /* The IOCTL status is embedded in the mailbox subheader. */
16075         shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
16076         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16077         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16078         if (shdr_status || shdr_add_status || rc) {
16079                 status = -ENXIO;
16080                 goto out;
16081         }
16082         drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16083         if (drq->queue_id == 0xFFFF) {
16084                 status = -ENXIO;
16085                 goto out;
16086         }
16087         drq->type = LPFC_DRQ;
16088         drq->assoc_qid = cq->queue_id;
16089         drq->subtype = subtype;
16090         drq->host_index = 0;
16091         drq->hba_index = 0;
16092         drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16093
16094         /* link the header and data RQs onto the parent cq child list */
16095         list_add_tail(&hrq->list, &cq->child_list);
16096         list_add_tail(&drq->list, &cq->child_list);
16097
16098 out:
16099         mempool_free(mbox, phba->mbox_mem_pool);
16100         return status;
16101 }
16102
16103 /**
16104  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
16105  * @phba: HBA structure that indicates port to create a queue on.
16106  * @hrqp: The queue structure array to use to create the header receive queues.
16107  * @drqp: The queue structure array to use to create the data receive queues.
16108  * @cqp: The completion queue array to bind these receive queues to.
16109  *
16110  * This function creates a receive buffer queue pair , as detailed in @hrq and
16111  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
16112  * to the HBA.
16113  *
16114  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
16115  * struct is used to get the entry count that is necessary to determine the
16116  * number of pages to use for this queue. The @cq is used to indicate which
16117  * completion queue to bind received buffers that are posted to these queues to.
16118  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
16119  * receive queue pair. This function is asynchronous and will wait for the
16120  * mailbox command to finish before continuing.
16121  *
16122  * On success this function will return a zero. If unable to allocate enough
16123  * memory this function will return -ENOMEM. If the queue create mailbox command
16124  * fails this function will return -ENXIO.
16125  **/
16126 int
16127 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
16128                 struct lpfc_queue **drqp, struct lpfc_queue **cqp,
16129                 uint32_t subtype)
16130 {
16131         struct lpfc_queue *hrq, *drq, *cq;
16132         struct lpfc_mbx_rq_create_v2 *rq_create;
16133         struct lpfc_dmabuf *dmabuf;
16134         LPFC_MBOXQ_t *mbox;
16135         int rc, length, alloclen, status = 0;
16136         int cnt, idx, numrq, page_idx = 0;
16137         uint32_t shdr_status, shdr_add_status;
16138         union lpfc_sli4_cfg_shdr *shdr;
16139         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16140
16141         numrq = phba->cfg_nvmet_mrq;
16142         /* sanity check on array memory */
16143         if (!hrqp || !drqp || !cqp || !numrq)
16144                 return -ENODEV;
16145         if (!phba->sli4_hba.pc_sli4_params.supported)
16146                 hw_page_size = SLI4_PAGE_SIZE;
16147
16148         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16149         if (!mbox)
16150                 return -ENOMEM;
16151
16152         length = sizeof(struct lpfc_mbx_rq_create_v2);
16153         length += ((2 * numrq * hrqp[0]->page_count) *
16154                    sizeof(struct dma_address));
16155
16156         alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16157                                     LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
16158                                     LPFC_SLI4_MBX_NEMBED);
16159         if (alloclen < length) {
16160                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16161                                 "3099 Allocated DMA memory size (%d) is "
16162                                 "less than the requested DMA memory size "
16163                                 "(%d)\n", alloclen, length);
16164                 status = -ENOMEM;
16165                 goto out;
16166         }
16167
16168
16169
16170         rq_create = mbox->sge_array->addr[0];
16171         shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
16172
16173         bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
16174         cnt = 0;
16175
16176         for (idx = 0; idx < numrq; idx++) {
16177                 hrq = hrqp[idx];
16178                 drq = drqp[idx];
16179                 cq  = cqp[idx];
16180
16181                 /* sanity check on queue memory */
16182                 if (!hrq || !drq || !cq) {
16183                         status = -ENODEV;
16184                         goto out;
16185                 }
16186
16187                 if (hrq->entry_count != drq->entry_count) {
16188                         status = -EINVAL;
16189                         goto out;
16190                 }
16191
16192                 if (idx == 0) {
16193                         bf_set(lpfc_mbx_rq_create_num_pages,
16194                                &rq_create->u.request,
16195                                hrq->page_count);
16196                         bf_set(lpfc_mbx_rq_create_rq_cnt,
16197                                &rq_create->u.request, (numrq * 2));
16198                         bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
16199                                1);
16200                         bf_set(lpfc_rq_context_base_cq,
16201                                &rq_create->u.request.context,
16202                                cq->queue_id);
16203                         bf_set(lpfc_rq_context_data_size,
16204                                &rq_create->u.request.context,
16205                                LPFC_NVMET_DATA_BUF_SIZE);
16206                         bf_set(lpfc_rq_context_hdr_size,
16207                                &rq_create->u.request.context,
16208                                LPFC_HDR_BUF_SIZE);
16209                         bf_set(lpfc_rq_context_rqe_count_1,
16210                                &rq_create->u.request.context,
16211                                hrq->entry_count);
16212                         bf_set(lpfc_rq_context_rqe_size,
16213                                &rq_create->u.request.context,
16214                                LPFC_RQE_SIZE_8);
16215                         bf_set(lpfc_rq_context_page_size,
16216                                &rq_create->u.request.context,
16217                                (PAGE_SIZE/SLI4_PAGE_SIZE));
16218                 }
16219                 rc = 0;
16220                 list_for_each_entry(dmabuf, &hrq->page_list, list) {
16221                         memset(dmabuf->virt, 0, hw_page_size);
16222                         cnt = page_idx + dmabuf->buffer_tag;
16223                         rq_create->u.request.page[cnt].addr_lo =
16224                                         putPaddrLow(dmabuf->phys);
16225                         rq_create->u.request.page[cnt].addr_hi =
16226                                         putPaddrHigh(dmabuf->phys);
16227                         rc++;
16228                 }
16229                 page_idx += rc;
16230
16231                 rc = 0;
16232                 list_for_each_entry(dmabuf, &drq->page_list, list) {
16233                         memset(dmabuf->virt, 0, hw_page_size);
16234                         cnt = page_idx + dmabuf->buffer_tag;
16235                         rq_create->u.request.page[cnt].addr_lo =
16236                                         putPaddrLow(dmabuf->phys);
16237                         rq_create->u.request.page[cnt].addr_hi =
16238                                         putPaddrHigh(dmabuf->phys);
16239                         rc++;
16240                 }
16241                 page_idx += rc;
16242
16243                 hrq->db_format = LPFC_DB_RING_FORMAT;
16244                 hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16245                 hrq->type = LPFC_HRQ;
16246                 hrq->assoc_qid = cq->queue_id;
16247                 hrq->subtype = subtype;
16248                 hrq->host_index = 0;
16249                 hrq->hba_index = 0;
16250                 hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16251
16252                 drq->db_format = LPFC_DB_RING_FORMAT;
16253                 drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
16254                 drq->type = LPFC_DRQ;
16255                 drq->assoc_qid = cq->queue_id;
16256                 drq->subtype = subtype;
16257                 drq->host_index = 0;
16258                 drq->hba_index = 0;
16259                 drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
16260
16261                 list_add_tail(&hrq->list, &cq->child_list);
16262                 list_add_tail(&drq->list, &cq->child_list);
16263         }
16264
16265         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16266         /* The IOCTL status is embedded in the mailbox subheader. */
16267         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16268         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16269         if (shdr_status || shdr_add_status || rc) {
16270                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16271                                 "3120 RQ_CREATE mailbox failed with "
16272                                 "status x%x add_status x%x, mbx status x%x\n",
16273                                 shdr_status, shdr_add_status, rc);
16274                 status = -ENXIO;
16275                 goto out;
16276         }
16277         rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
16278         if (rc == 0xFFFF) {
16279                 status = -ENXIO;
16280                 goto out;
16281         }
16282
16283         /* Initialize all RQs with associated queue id */
16284         for (idx = 0; idx < numrq; idx++) {
16285                 hrq = hrqp[idx];
16286                 hrq->queue_id = rc + (2 * idx);
16287                 drq = drqp[idx];
16288                 drq->queue_id = rc + (2 * idx) + 1;
16289         }
16290
16291 out:
16292         lpfc_sli4_mbox_cmd_free(phba, mbox);
16293         return status;
16294 }
16295
16296 /**
16297  * lpfc_eq_destroy - Destroy an event Queue on the HBA
16298  * @eq: The queue structure associated with the queue to destroy.
16299  *
16300  * This function destroys a queue, as detailed in @eq by sending an mailbox
16301  * command, specific to the type of queue, to the HBA.
16302  *
16303  * The @eq struct is used to get the queue ID of the queue to destroy.
16304  *
16305  * On success this function will return a zero. If the queue destroy mailbox
16306  * command fails this function will return -ENXIO.
16307  **/
16308 int
16309 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
16310 {
16311         LPFC_MBOXQ_t *mbox;
16312         int rc, length, status = 0;
16313         uint32_t shdr_status, shdr_add_status;
16314         union lpfc_sli4_cfg_shdr *shdr;
16315
16316         /* sanity check on queue memory */
16317         if (!eq)
16318                 return -ENODEV;
16319
16320         mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
16321         if (!mbox)
16322                 return -ENOMEM;
16323         length = (sizeof(struct lpfc_mbx_eq_destroy) -
16324                   sizeof(struct lpfc_sli4_cfg_mhdr));
16325         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16326                          LPFC_MBOX_OPCODE_EQ_DESTROY,
16327                          length, LPFC_SLI4_MBX_EMBED);
16328         bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
16329                eq->queue_id);
16330         mbox->vport = eq->phba->pport;
16331         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16332
16333         rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
16334         /* The IOCTL status is embedded in the mailbox subheader. */
16335         shdr = (union lpfc_sli4_cfg_shdr *)
16336                 &mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
16337         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16338         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16339         if (shdr_status || shdr_add_status || rc) {
16340                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16341                                 "2505 EQ_DESTROY mailbox failed with "
16342                                 "status x%x add_status x%x, mbx status x%x\n",
16343                                 shdr_status, shdr_add_status, rc);
16344                 status = -ENXIO;
16345         }
16346
16347         /* Remove eq from any list */
16348         list_del_init(&eq->list);
16349         mempool_free(mbox, eq->phba->mbox_mem_pool);
16350         return status;
16351 }
16352
16353 /**
16354  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
16355  * @cq: The queue structure associated with the queue to destroy.
16356  *
16357  * This function destroys a queue, as detailed in @cq by sending an mailbox
16358  * command, specific to the type of queue, to the HBA.
16359  *
16360  * The @cq struct is used to get the queue ID of the queue to destroy.
16361  *
16362  * On success this function will return a zero. If the queue destroy mailbox
16363  * command fails this function will return -ENXIO.
16364  **/
16365 int
16366 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
16367 {
16368         LPFC_MBOXQ_t *mbox;
16369         int rc, length, status = 0;
16370         uint32_t shdr_status, shdr_add_status;
16371         union lpfc_sli4_cfg_shdr *shdr;
16372
16373         /* sanity check on queue memory */
16374         if (!cq)
16375                 return -ENODEV;
16376         mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
16377         if (!mbox)
16378                 return -ENOMEM;
16379         length = (sizeof(struct lpfc_mbx_cq_destroy) -
16380                   sizeof(struct lpfc_sli4_cfg_mhdr));
16381         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16382                          LPFC_MBOX_OPCODE_CQ_DESTROY,
16383                          length, LPFC_SLI4_MBX_EMBED);
16384         bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
16385                cq->queue_id);
16386         mbox->vport = cq->phba->pport;
16387         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16388         rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
16389         /* The IOCTL status is embedded in the mailbox subheader. */
16390         shdr = (union lpfc_sli4_cfg_shdr *)
16391                 &mbox->u.mqe.un.wq_create.header.cfg_shdr;
16392         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16393         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16394         if (shdr_status || shdr_add_status || rc) {
16395                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16396                                 "2506 CQ_DESTROY mailbox failed with "
16397                                 "status x%x add_status x%x, mbx status x%x\n",
16398                                 shdr_status, shdr_add_status, rc);
16399                 status = -ENXIO;
16400         }
16401         /* Remove cq from any list */
16402         list_del_init(&cq->list);
16403         mempool_free(mbox, cq->phba->mbox_mem_pool);
16404         return status;
16405 }
16406
16407 /**
16408  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
16409  * @qm: The queue structure associated with the queue to destroy.
16410  *
16411  * This function destroys a queue, as detailed in @mq by sending an mailbox
16412  * command, specific to the type of queue, to the HBA.
16413  *
16414  * The @mq struct is used to get the queue ID of the queue to destroy.
16415  *
16416  * On success this function will return a zero. If the queue destroy mailbox
16417  * command fails this function will return -ENXIO.
16418  **/
16419 int
16420 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
16421 {
16422         LPFC_MBOXQ_t *mbox;
16423         int rc, length, status = 0;
16424         uint32_t shdr_status, shdr_add_status;
16425         union lpfc_sli4_cfg_shdr *shdr;
16426
16427         /* sanity check on queue memory */
16428         if (!mq)
16429                 return -ENODEV;
16430         mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
16431         if (!mbox)
16432                 return -ENOMEM;
16433         length = (sizeof(struct lpfc_mbx_mq_destroy) -
16434                   sizeof(struct lpfc_sli4_cfg_mhdr));
16435         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16436                          LPFC_MBOX_OPCODE_MQ_DESTROY,
16437                          length, LPFC_SLI4_MBX_EMBED);
16438         bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
16439                mq->queue_id);
16440         mbox->vport = mq->phba->pport;
16441         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16442         rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
16443         /* The IOCTL status is embedded in the mailbox subheader. */
16444         shdr = (union lpfc_sli4_cfg_shdr *)
16445                 &mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
16446         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16447         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16448         if (shdr_status || shdr_add_status || rc) {
16449                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16450                                 "2507 MQ_DESTROY mailbox failed with "
16451                                 "status x%x add_status x%x, mbx status x%x\n",
16452                                 shdr_status, shdr_add_status, rc);
16453                 status = -ENXIO;
16454         }
16455         /* Remove mq from any list */
16456         list_del_init(&mq->list);
16457         mempool_free(mbox, mq->phba->mbox_mem_pool);
16458         return status;
16459 }
16460
16461 /**
16462  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
16463  * @wq: The queue structure associated with the queue to destroy.
16464  *
16465  * This function destroys a queue, as detailed in @wq by sending an mailbox
16466  * command, specific to the type of queue, to the HBA.
16467  *
16468  * The @wq struct is used to get the queue ID of the queue to destroy.
16469  *
16470  * On success this function will return a zero. If the queue destroy mailbox
16471  * command fails this function will return -ENXIO.
16472  **/
16473 int
16474 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
16475 {
16476         LPFC_MBOXQ_t *mbox;
16477         int rc, length, status = 0;
16478         uint32_t shdr_status, shdr_add_status;
16479         union lpfc_sli4_cfg_shdr *shdr;
16480
16481         /* sanity check on queue memory */
16482         if (!wq)
16483                 return -ENODEV;
16484         mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
16485         if (!mbox)
16486                 return -ENOMEM;
16487         length = (sizeof(struct lpfc_mbx_wq_destroy) -
16488                   sizeof(struct lpfc_sli4_cfg_mhdr));
16489         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16490                          LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
16491                          length, LPFC_SLI4_MBX_EMBED);
16492         bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
16493                wq->queue_id);
16494         mbox->vport = wq->phba->pport;
16495         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16496         rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
16497         shdr = (union lpfc_sli4_cfg_shdr *)
16498                 &mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
16499         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16500         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16501         if (shdr_status || shdr_add_status || rc) {
16502                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16503                                 "2508 WQ_DESTROY mailbox failed with "
16504                                 "status x%x add_status x%x, mbx status x%x\n",
16505                                 shdr_status, shdr_add_status, rc);
16506                 status = -ENXIO;
16507         }
16508         /* Remove wq from any list */
16509         list_del_init(&wq->list);
16510         kfree(wq->pring);
16511         wq->pring = NULL;
16512         mempool_free(mbox, wq->phba->mbox_mem_pool);
16513         return status;
16514 }
16515
16516 /**
16517  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
16518  * @rq: The queue structure associated with the queue to destroy.
16519  *
16520  * This function destroys a queue, as detailed in @rq by sending an mailbox
16521  * command, specific to the type of queue, to the HBA.
16522  *
16523  * The @rq struct is used to get the queue ID of the queue to destroy.
16524  *
16525  * On success this function will return a zero. If the queue destroy mailbox
16526  * command fails this function will return -ENXIO.
16527  **/
16528 int
16529 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
16530                 struct lpfc_queue *drq)
16531 {
16532         LPFC_MBOXQ_t *mbox;
16533         int rc, length, status = 0;
16534         uint32_t shdr_status, shdr_add_status;
16535         union lpfc_sli4_cfg_shdr *shdr;
16536
16537         /* sanity check on queue memory */
16538         if (!hrq || !drq)
16539                 return -ENODEV;
16540         mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
16541         if (!mbox)
16542                 return -ENOMEM;
16543         length = (sizeof(struct lpfc_mbx_rq_destroy) -
16544                   sizeof(struct lpfc_sli4_cfg_mhdr));
16545         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16546                          LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
16547                          length, LPFC_SLI4_MBX_EMBED);
16548         bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
16549                hrq->queue_id);
16550         mbox->vport = hrq->phba->pport;
16551         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16552         rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
16553         /* The IOCTL status is embedded in the mailbox subheader. */
16554         shdr = (union lpfc_sli4_cfg_shdr *)
16555                 &mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
16556         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16557         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16558         if (shdr_status || shdr_add_status || rc) {
16559                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16560                                 "2509 RQ_DESTROY mailbox failed with "
16561                                 "status x%x add_status x%x, mbx status x%x\n",
16562                                 shdr_status, shdr_add_status, rc);
16563                 if (rc != MBX_TIMEOUT)
16564                         mempool_free(mbox, hrq->phba->mbox_mem_pool);
16565                 return -ENXIO;
16566         }
16567         bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
16568                drq->queue_id);
16569         rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
16570         shdr = (union lpfc_sli4_cfg_shdr *)
16571                 &mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
16572         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16573         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16574         if (shdr_status || shdr_add_status || rc) {
16575                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16576                                 "2510 RQ_DESTROY mailbox failed with "
16577                                 "status x%x add_status x%x, mbx status x%x\n",
16578                                 shdr_status, shdr_add_status, rc);
16579                 status = -ENXIO;
16580         }
16581         list_del_init(&hrq->list);
16582         list_del_init(&drq->list);
16583         mempool_free(mbox, hrq->phba->mbox_mem_pool);
16584         return status;
16585 }
16586
16587 /**
16588  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
16589  * @phba: The virtual port for which this call being executed.
16590  * @pdma_phys_addr0: Physical address of the 1st SGL page.
16591  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
16592  * @xritag: the xritag that ties this io to the SGL pages.
16593  *
16594  * This routine will post the sgl pages for the IO that has the xritag
16595  * that is in the iocbq structure. The xritag is assigned during iocbq
16596  * creation and persists for as long as the driver is loaded.
16597  * if the caller has fewer than 256 scatter gather segments to map then
16598  * pdma_phys_addr1 should be 0.
16599  * If the caller needs to map more than 256 scatter gather segment then
16600  * pdma_phys_addr1 should be a valid physical address.
16601  * physical address for SGLs must be 64 byte aligned.
16602  * If you are going to map 2 SGL's then the first one must have 256 entries
16603  * the second sgl can have between 1 and 256 entries.
16604  *
16605  * Return codes:
16606  *      0 - Success
16607  *      -ENXIO, -ENOMEM - Failure
16608  **/
16609 int
16610 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
16611                 dma_addr_t pdma_phys_addr0,
16612                 dma_addr_t pdma_phys_addr1,
16613                 uint16_t xritag)
16614 {
16615         struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
16616         LPFC_MBOXQ_t *mbox;
16617         int rc;
16618         uint32_t shdr_status, shdr_add_status;
16619         uint32_t mbox_tmo;
16620         union lpfc_sli4_cfg_shdr *shdr;
16621
16622         if (xritag == NO_XRI) {
16623                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16624                                 "0364 Invalid param:\n");
16625                 return -EINVAL;
16626         }
16627
16628         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16629         if (!mbox)
16630                 return -ENOMEM;
16631
16632         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16633                         LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
16634                         sizeof(struct lpfc_mbx_post_sgl_pages) -
16635                         sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
16636
16637         post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
16638                                 &mbox->u.mqe.un.post_sgl_pages;
16639         bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
16640         bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
16641
16642         post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo =
16643                                 cpu_to_le32(putPaddrLow(pdma_phys_addr0));
16644         post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
16645                                 cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
16646
16647         post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo =
16648                                 cpu_to_le32(putPaddrLow(pdma_phys_addr1));
16649         post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
16650                                 cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
16651         if (!phba->sli4_hba.intr_enable)
16652                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16653         else {
16654                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
16655                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
16656         }
16657         /* The IOCTL status is embedded in the mailbox subheader. */
16658         shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
16659         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16660         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16661         if (rc != MBX_TIMEOUT)
16662                 mempool_free(mbox, phba->mbox_mem_pool);
16663         if (shdr_status || shdr_add_status || rc) {
16664                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16665                                 "2511 POST_SGL mailbox failed with "
16666                                 "status x%x add_status x%x, mbx status x%x\n",
16667                                 shdr_status, shdr_add_status, rc);
16668         }
16669         return 0;
16670 }
16671
16672 /**
16673  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
16674  * @phba: pointer to lpfc hba data structure.
16675  *
16676  * This routine is invoked to post rpi header templates to the
16677  * HBA consistent with the SLI-4 interface spec.  This routine
16678  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
16679  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
16680  *
16681  * Returns
16682  *      A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
16683  *      LPFC_RPI_ALLOC_ERROR if no rpis are available.
16684  **/
16685 static uint16_t
16686 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
16687 {
16688         unsigned long xri;
16689
16690         /*
16691          * Fetch the next logical xri.  Because this index is logical,
16692          * the driver starts at 0 each time.
16693          */
16694         spin_lock_irq(&phba->hbalock);
16695         xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
16696                                  phba->sli4_hba.max_cfg_param.max_xri, 0);
16697         if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
16698                 spin_unlock_irq(&phba->hbalock);
16699                 return NO_XRI;
16700         } else {
16701                 set_bit(xri, phba->sli4_hba.xri_bmask);
16702                 phba->sli4_hba.max_cfg_param.xri_used++;
16703         }
16704         spin_unlock_irq(&phba->hbalock);
16705         return xri;
16706 }
16707
16708 /**
16709  * lpfc_sli4_free_xri - Release an xri for reuse.
16710  * @phba: pointer to lpfc hba data structure.
16711  *
16712  * This routine is invoked to release an xri to the pool of
16713  * available rpis maintained by the driver.
16714  **/
16715 static void
16716 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
16717 {
16718         if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
16719                 phba->sli4_hba.max_cfg_param.xri_used--;
16720         }
16721 }
16722
16723 /**
16724  * lpfc_sli4_free_xri - Release an xri for reuse.
16725  * @phba: pointer to lpfc hba data structure.
16726  *
16727  * This routine is invoked to release an xri to the pool of
16728  * available rpis maintained by the driver.
16729  **/
16730 void
16731 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
16732 {
16733         spin_lock_irq(&phba->hbalock);
16734         __lpfc_sli4_free_xri(phba, xri);
16735         spin_unlock_irq(&phba->hbalock);
16736 }
16737
16738 /**
16739  * lpfc_sli4_next_xritag - Get an xritag for the io
16740  * @phba: Pointer to HBA context object.
16741  *
16742  * This function gets an xritag for the iocb. If there is no unused xritag
16743  * it will return 0xffff.
16744  * The function returns the allocated xritag if successful, else returns zero.
16745  * Zero is not a valid xritag.
16746  * The caller is not required to hold any lock.
16747  **/
16748 uint16_t
16749 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
16750 {
16751         uint16_t xri_index;
16752
16753         xri_index = lpfc_sli4_alloc_xri(phba);
16754         if (xri_index == NO_XRI)
16755                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
16756                                 "2004 Failed to allocate XRI.last XRITAG is %d"
16757                                 " Max XRI is %d, Used XRI is %d\n",
16758                                 xri_index,
16759                                 phba->sli4_hba.max_cfg_param.max_xri,
16760                                 phba->sli4_hba.max_cfg_param.xri_used);
16761         return xri_index;
16762 }
16763
16764 /**
16765  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
16766  * @phba: pointer to lpfc hba data structure.
16767  * @post_sgl_list: pointer to els sgl entry list.
16768  * @count: number of els sgl entries on the list.
16769  *
16770  * This routine is invoked to post a block of driver's sgl pages to the
16771  * HBA using non-embedded mailbox command. No Lock is held. This routine
16772  * is only called when the driver is loading and after all IO has been
16773  * stopped.
16774  **/
16775 static int
16776 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
16777                             struct list_head *post_sgl_list,
16778                             int post_cnt)
16779 {
16780         struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
16781         struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
16782         struct sgl_page_pairs *sgl_pg_pairs;
16783         void *viraddr;
16784         LPFC_MBOXQ_t *mbox;
16785         uint32_t reqlen, alloclen, pg_pairs;
16786         uint32_t mbox_tmo;
16787         uint16_t xritag_start = 0;
16788         int rc = 0;
16789         uint32_t shdr_status, shdr_add_status;
16790         union lpfc_sli4_cfg_shdr *shdr;
16791
16792         reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
16793                  sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
16794         if (reqlen > SLI4_PAGE_SIZE) {
16795                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16796                                 "2559 Block sgl registration required DMA "
16797                                 "size (%d) great than a page\n", reqlen);
16798                 return -ENOMEM;
16799         }
16800
16801         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16802         if (!mbox)
16803                 return -ENOMEM;
16804
16805         /* Allocate DMA memory and set up the non-embedded mailbox command */
16806         alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16807                          LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
16808                          LPFC_SLI4_MBX_NEMBED);
16809
16810         if (alloclen < reqlen) {
16811                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16812                                 "0285 Allocated DMA memory size (%d) is "
16813                                 "less than the requested DMA memory "
16814                                 "size (%d)\n", alloclen, reqlen);
16815                 lpfc_sli4_mbox_cmd_free(phba, mbox);
16816                 return -ENOMEM;
16817         }
16818         /* Set up the SGL pages in the non-embedded DMA pages */
16819         viraddr = mbox->sge_array->addr[0];
16820         sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
16821         sgl_pg_pairs = &sgl->sgl_pg_pairs;
16822
16823         pg_pairs = 0;
16824         list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
16825                 /* Set up the sge entry */
16826                 sgl_pg_pairs->sgl_pg0_addr_lo =
16827                                 cpu_to_le32(putPaddrLow(sglq_entry->phys));
16828                 sgl_pg_pairs->sgl_pg0_addr_hi =
16829                                 cpu_to_le32(putPaddrHigh(sglq_entry->phys));
16830                 sgl_pg_pairs->sgl_pg1_addr_lo =
16831                                 cpu_to_le32(putPaddrLow(0));
16832                 sgl_pg_pairs->sgl_pg1_addr_hi =
16833                                 cpu_to_le32(putPaddrHigh(0));
16834
16835                 /* Keep the first xritag on the list */
16836                 if (pg_pairs == 0)
16837                         xritag_start = sglq_entry->sli4_xritag;
16838                 sgl_pg_pairs++;
16839                 pg_pairs++;
16840         }
16841
16842         /* Complete initialization and perform endian conversion. */
16843         bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
16844         bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
16845         sgl->word0 = cpu_to_le32(sgl->word0);
16846
16847         if (!phba->sli4_hba.intr_enable)
16848                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16849         else {
16850                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
16851                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
16852         }
16853         shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
16854         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16855         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16856         if (rc != MBX_TIMEOUT)
16857                 lpfc_sli4_mbox_cmd_free(phba, mbox);
16858         if (shdr_status || shdr_add_status || rc) {
16859                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16860                                 "2513 POST_SGL_BLOCK mailbox command failed "
16861                                 "status x%x add_status x%x mbx status x%x\n",
16862                                 shdr_status, shdr_add_status, rc);
16863                 rc = -ENXIO;
16864         }
16865         return rc;
16866 }
16867
16868 /**
16869  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
16870  * @phba: pointer to lpfc hba data structure.
16871  * @nblist: pointer to nvme buffer list.
16872  * @count: number of scsi buffers on the list.
16873  *
16874  * This routine is invoked to post a block of @count scsi sgl pages from a
16875  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
16876  * No Lock is held.
16877  *
16878  **/
16879 static int
16880 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
16881                             int count)
16882 {
16883         struct lpfc_io_buf *lpfc_ncmd;
16884         struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
16885         struct sgl_page_pairs *sgl_pg_pairs;
16886         void *viraddr;
16887         LPFC_MBOXQ_t *mbox;
16888         uint32_t reqlen, alloclen, pg_pairs;
16889         uint32_t mbox_tmo;
16890         uint16_t xritag_start = 0;
16891         int rc = 0;
16892         uint32_t shdr_status, shdr_add_status;
16893         dma_addr_t pdma_phys_bpl1;
16894         union lpfc_sli4_cfg_shdr *shdr;
16895
16896         /* Calculate the requested length of the dma memory */
16897         reqlen = count * sizeof(struct sgl_page_pairs) +
16898                  sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
16899         if (reqlen > SLI4_PAGE_SIZE) {
16900                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
16901                                 "6118 Block sgl registration required DMA "
16902                                 "size (%d) great than a page\n", reqlen);
16903                 return -ENOMEM;
16904         }
16905         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16906         if (!mbox) {
16907                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16908                                 "6119 Failed to allocate mbox cmd memory\n");
16909                 return -ENOMEM;
16910         }
16911
16912         /* Allocate DMA memory and set up the non-embedded mailbox command */
16913         alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16914                                     LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
16915                                     reqlen, LPFC_SLI4_MBX_NEMBED);
16916
16917         if (alloclen < reqlen) {
16918                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
16919                                 "6120 Allocated DMA memory size (%d) is "
16920                                 "less than the requested DMA memory "
16921                                 "size (%d)\n", alloclen, reqlen);
16922                 lpfc_sli4_mbox_cmd_free(phba, mbox);
16923                 return -ENOMEM;
16924         }
16925
16926         /* Get the first SGE entry from the non-embedded DMA memory */
16927         viraddr = mbox->sge_array->addr[0];
16928
16929         /* Set up the SGL pages in the non-embedded DMA pages */
16930         sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
16931         sgl_pg_pairs = &sgl->sgl_pg_pairs;
16932
16933         pg_pairs = 0;
16934         list_for_each_entry(lpfc_ncmd, nblist, list) {
16935                 /* Set up the sge entry */
16936                 sgl_pg_pairs->sgl_pg0_addr_lo =
16937                         cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
16938                 sgl_pg_pairs->sgl_pg0_addr_hi =
16939                         cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
16940                 if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
16941                         pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
16942                                                 SGL_PAGE_SIZE;
16943                 else
16944                         pdma_phys_bpl1 = 0;
16945                 sgl_pg_pairs->sgl_pg1_addr_lo =
16946                         cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
16947                 sgl_pg_pairs->sgl_pg1_addr_hi =
16948                         cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
16949                 /* Keep the first xritag on the list */
16950                 if (pg_pairs == 0)
16951                         xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
16952                 sgl_pg_pairs++;
16953                 pg_pairs++;
16954         }
16955         bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
16956         bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
16957         /* Perform endian conversion if necessary */
16958         sgl->word0 = cpu_to_le32(sgl->word0);
16959
16960         if (!phba->sli4_hba.intr_enable) {
16961                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16962         } else {
16963                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
16964                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
16965         }
16966         shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
16967         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16968         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16969         if (rc != MBX_TIMEOUT)
16970                 lpfc_sli4_mbox_cmd_free(phba, mbox);
16971         if (shdr_status || shdr_add_status || rc) {
16972                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
16973                                 "6125 POST_SGL_BLOCK mailbox command failed "
16974                                 "status x%x add_status x%x mbx status x%x\n",
16975                                 shdr_status, shdr_add_status, rc);
16976                 rc = -ENXIO;
16977         }
16978         return rc;
16979 }
16980
16981 /**
16982  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
16983  * @phba: pointer to lpfc hba data structure.
16984  * @post_nblist: pointer to the nvme buffer list.
16985  *
16986  * This routine walks a list of nvme buffers that was passed in. It attempts
16987  * to construct blocks of nvme buffer sgls which contains contiguous xris and
16988  * uses the non-embedded SGL block post mailbox commands to post to the port.
16989  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
16990  * embedded SGL post mailbox command for posting. The @post_nblist passed in
16991  * must be local list, thus no lock is needed when manipulate the list.
16992  *
16993  * Returns: 0 = failure, non-zero number of successfully posted buffers.
16994  **/
16995 int
16996 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
16997                            struct list_head *post_nblist, int sb_count)
16998 {
16999         struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
17000         int status, sgl_size;
17001         int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
17002         dma_addr_t pdma_phys_sgl1;
17003         int last_xritag = NO_XRI;
17004         int cur_xritag;
17005         LIST_HEAD(prep_nblist);
17006         LIST_HEAD(blck_nblist);
17007         LIST_HEAD(nvme_nblist);
17008
17009         /* sanity check */
17010         if (sb_count <= 0)
17011                 return -EINVAL;
17012
17013         sgl_size = phba->cfg_sg_dma_buf_size;
17014         list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
17015                 list_del_init(&lpfc_ncmd->list);
17016                 block_cnt++;
17017                 if ((last_xritag != NO_XRI) &&
17018                     (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
17019                         /* a hole in xri block, form a sgl posting block */
17020                         list_splice_init(&prep_nblist, &blck_nblist);
17021                         post_cnt = block_cnt - 1;
17022                         /* prepare list for next posting block */
17023                         list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17024                         block_cnt = 1;
17025                 } else {
17026                         /* prepare list for next posting block */
17027                         list_add_tail(&lpfc_ncmd->list, &prep_nblist);
17028                         /* enough sgls for non-embed sgl mbox command */
17029                         if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
17030                                 list_splice_init(&prep_nblist, &blck_nblist);
17031                                 post_cnt = block_cnt;
17032                                 block_cnt = 0;
17033                         }
17034                 }
17035                 num_posting++;
17036                 last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
17037
17038                 /* end of repost sgl list condition for NVME buffers */
17039                 if (num_posting == sb_count) {
17040                         if (post_cnt == 0) {
17041                                 /* last sgl posting block */
17042                                 list_splice_init(&prep_nblist, &blck_nblist);
17043                                 post_cnt = block_cnt;
17044                         } else if (block_cnt == 1) {
17045                                 /* last single sgl with non-contiguous xri */
17046                                 if (sgl_size > SGL_PAGE_SIZE)
17047                                         pdma_phys_sgl1 =
17048                                                 lpfc_ncmd->dma_phys_sgl +
17049                                                 SGL_PAGE_SIZE;
17050                                 else
17051                                         pdma_phys_sgl1 = 0;
17052                                 cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
17053                                 status = lpfc_sli4_post_sgl(
17054                                                 phba, lpfc_ncmd->dma_phys_sgl,
17055                                                 pdma_phys_sgl1, cur_xritag);
17056                                 if (status) {
17057                                         /* Post error.  Buffer unavailable. */
17058                                         lpfc_ncmd->flags |=
17059                                                 LPFC_SBUF_NOT_POSTED;
17060                                 } else {
17061                                         /* Post success. Bffer available. */
17062                                         lpfc_ncmd->flags &=
17063                                                 ~LPFC_SBUF_NOT_POSTED;
17064                                         lpfc_ncmd->status = IOSTAT_SUCCESS;
17065                                         num_posted++;
17066                                 }
17067                                 /* success, put on NVME buffer sgl list */
17068                                 list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
17069                         }
17070                 }
17071
17072                 /* continue until a nembed page worth of sgls */
17073                 if (post_cnt == 0)
17074                         continue;
17075
17076                 /* post block of NVME buffer list sgls */
17077                 status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
17078                                                      post_cnt);
17079
17080                 /* don't reset xirtag due to hole in xri block */
17081                 if (block_cnt == 0)
17082                         last_xritag = NO_XRI;
17083
17084                 /* reset NVME buffer post count for next round of posting */
17085                 post_cnt = 0;
17086
17087                 /* put posted NVME buffer-sgl posted on NVME buffer sgl list */
17088                 while (!list_empty(&blck_nblist)) {
17089                         list_remove_head(&blck_nblist, lpfc_ncmd,
17090                                          struct lpfc_io_buf, list);
17091                         if (status) {
17092                                 /* Post error.  Mark buffer unavailable. */
17093                                 lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
17094                         } else {
17095                                 /* Post success, Mark buffer available. */
17096                                 lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
17097                                 lpfc_ncmd->status = IOSTAT_SUCCESS;
17098                                 num_posted++;
17099                         }
17100                         list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
17101                 }
17102         }
17103         /* Push NVME buffers with sgl posted to the available list */
17104         lpfc_io_buf_replenish(phba, &nvme_nblist);
17105
17106         return num_posted;
17107 }
17108
17109 /**
17110  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
17111  * @phba: pointer to lpfc_hba struct that the frame was received on
17112  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17113  *
17114  * This function checks the fields in the @fc_hdr to see if the FC frame is a
17115  * valid type of frame that the LPFC driver will handle. This function will
17116  * return a zero if the frame is a valid frame or a non zero value when the
17117  * frame does not pass the check.
17118  **/
17119 static int
17120 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
17121 {
17122         /*  make rctl_names static to save stack space */
17123         struct fc_vft_header *fc_vft_hdr;
17124         uint32_t *header = (uint32_t *) fc_hdr;
17125
17126 #define FC_RCTL_MDS_DIAGS       0xF4
17127
17128         switch (fc_hdr->fh_r_ctl) {
17129         case FC_RCTL_DD_UNCAT:          /* uncategorized information */
17130         case FC_RCTL_DD_SOL_DATA:       /* solicited data */
17131         case FC_RCTL_DD_UNSOL_CTL:      /* unsolicited control */
17132         case FC_RCTL_DD_SOL_CTL:        /* solicited control or reply */
17133         case FC_RCTL_DD_UNSOL_DATA:     /* unsolicited data */
17134         case FC_RCTL_DD_DATA_DESC:      /* data descriptor */
17135         case FC_RCTL_DD_UNSOL_CMD:      /* unsolicited command */
17136         case FC_RCTL_DD_CMD_STATUS:     /* command status */
17137         case FC_RCTL_ELS_REQ:   /* extended link services request */
17138         case FC_RCTL_ELS_REP:   /* extended link services reply */
17139         case FC_RCTL_ELS4_REQ:  /* FC-4 ELS request */
17140         case FC_RCTL_ELS4_REP:  /* FC-4 ELS reply */
17141         case FC_RCTL_BA_NOP:    /* basic link service NOP */
17142         case FC_RCTL_BA_ABTS:   /* basic link service abort */
17143         case FC_RCTL_BA_RMC:    /* remove connection */
17144         case FC_RCTL_BA_ACC:    /* basic accept */
17145         case FC_RCTL_BA_RJT:    /* basic reject */
17146         case FC_RCTL_BA_PRMT:
17147         case FC_RCTL_ACK_1:     /* acknowledge_1 */
17148         case FC_RCTL_ACK_0:     /* acknowledge_0 */
17149         case FC_RCTL_P_RJT:     /* port reject */
17150         case FC_RCTL_F_RJT:     /* fabric reject */
17151         case FC_RCTL_P_BSY:     /* port busy */
17152         case FC_RCTL_F_BSY:     /* fabric busy to data frame */
17153         case FC_RCTL_F_BSYL:    /* fabric busy to link control frame */
17154         case FC_RCTL_LCR:       /* link credit reset */
17155         case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
17156         case FC_RCTL_END:       /* end */
17157                 break;
17158         case FC_RCTL_VFTH:      /* Virtual Fabric tagging Header */
17159                 fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17160                 fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
17161                 return lpfc_fc_frame_check(phba, fc_hdr);
17162         default:
17163                 goto drop;
17164         }
17165
17166         switch (fc_hdr->fh_type) {
17167         case FC_TYPE_BLS:
17168         case FC_TYPE_ELS:
17169         case FC_TYPE_FCP:
17170         case FC_TYPE_CT:
17171         case FC_TYPE_NVME:
17172                 break;
17173         case FC_TYPE_IP:
17174         case FC_TYPE_ILS:
17175         default:
17176                 goto drop;
17177         }
17178
17179         lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
17180                         "2538 Received frame rctl:x%x, type:x%x, "
17181                         "frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
17182                         fc_hdr->fh_r_ctl, fc_hdr->fh_type,
17183                         be32_to_cpu(header[0]), be32_to_cpu(header[1]),
17184                         be32_to_cpu(header[2]), be32_to_cpu(header[3]),
17185                         be32_to_cpu(header[4]), be32_to_cpu(header[5]),
17186                         be32_to_cpu(header[6]));
17187         return 0;
17188 drop:
17189         lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
17190                         "2539 Dropped frame rctl:x%x type:x%x\n",
17191                         fc_hdr->fh_r_ctl, fc_hdr->fh_type);
17192         return 1;
17193 }
17194
17195 /**
17196  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
17197  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17198  *
17199  * This function processes the FC header to retrieve the VFI from the VF
17200  * header, if one exists. This function will return the VFI if one exists
17201  * or 0 if no VSAN Header exists.
17202  **/
17203 static uint32_t
17204 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
17205 {
17206         struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
17207
17208         if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
17209                 return 0;
17210         return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
17211 }
17212
17213 /**
17214  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
17215  * @phba: Pointer to the HBA structure to search for the vport on
17216  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
17217  * @fcfi: The FC Fabric ID that the frame came from
17218  *
17219  * This function searches the @phba for a vport that matches the content of the
17220  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
17221  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
17222  * returns the matching vport pointer or NULL if unable to match frame to a
17223  * vport.
17224  **/
17225 static struct lpfc_vport *
17226 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
17227                        uint16_t fcfi, uint32_t did)
17228 {
17229         struct lpfc_vport **vports;
17230         struct lpfc_vport *vport = NULL;
17231         int i;
17232
17233         if (did == Fabric_DID)
17234                 return phba->pport;
17235         if ((phba->pport->fc_flag & FC_PT2PT) &&
17236                 !(phba->link_state == LPFC_HBA_READY))
17237                 return phba->pport;
17238
17239         vports = lpfc_create_vport_work_array(phba);
17240         if (vports != NULL) {
17241                 for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
17242                         if (phba->fcf.fcfi == fcfi &&
17243                             vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
17244                             vports[i]->fc_myDID == did) {
17245                                 vport = vports[i];
17246                                 break;
17247                         }
17248                 }
17249         }
17250         lpfc_destroy_vport_work_array(phba, vports);
17251         return vport;
17252 }
17253
17254 /**
17255  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
17256  * @vport: The vport to work on.
17257  *
17258  * This function updates the receive sequence time stamp for this vport. The
17259  * receive sequence time stamp indicates the time that the last frame of the
17260  * the sequence that has been idle for the longest amount of time was received.
17261  * the driver uses this time stamp to indicate if any received sequences have
17262  * timed out.
17263  **/
17264 static void
17265 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
17266 {
17267         struct lpfc_dmabuf *h_buf;
17268         struct hbq_dmabuf *dmabuf = NULL;
17269
17270         /* get the oldest sequence on the rcv list */
17271         h_buf = list_get_first(&vport->rcv_buffer_list,
17272                                struct lpfc_dmabuf, list);
17273         if (!h_buf)
17274                 return;
17275         dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17276         vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
17277 }
17278
17279 /**
17280  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
17281  * @vport: The vport that the received sequences were sent to.
17282  *
17283  * This function cleans up all outstanding received sequences. This is called
17284  * by the driver when a link event or user action invalidates all the received
17285  * sequences.
17286  **/
17287 void
17288 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
17289 {
17290         struct lpfc_dmabuf *h_buf, *hnext;
17291         struct lpfc_dmabuf *d_buf, *dnext;
17292         struct hbq_dmabuf *dmabuf = NULL;
17293
17294         /* start with the oldest sequence on the rcv list */
17295         list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17296                 dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17297                 list_del_init(&dmabuf->hbuf.list);
17298                 list_for_each_entry_safe(d_buf, dnext,
17299                                          &dmabuf->dbuf.list, list) {
17300                         list_del_init(&d_buf->list);
17301                         lpfc_in_buf_free(vport->phba, d_buf);
17302                 }
17303                 lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17304         }
17305 }
17306
17307 /**
17308  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
17309  * @vport: The vport that the received sequences were sent to.
17310  *
17311  * This function determines whether any received sequences have timed out by
17312  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
17313  * indicates that there is at least one timed out sequence this routine will
17314  * go through the received sequences one at a time from most inactive to most
17315  * active to determine which ones need to be cleaned up. Once it has determined
17316  * that a sequence needs to be cleaned up it will simply free up the resources
17317  * without sending an abort.
17318  **/
17319 void
17320 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
17321 {
17322         struct lpfc_dmabuf *h_buf, *hnext;
17323         struct lpfc_dmabuf *d_buf, *dnext;
17324         struct hbq_dmabuf *dmabuf = NULL;
17325         unsigned long timeout;
17326         int abort_count = 0;
17327
17328         timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17329                    vport->rcv_buffer_time_stamp);
17330         if (list_empty(&vport->rcv_buffer_list) ||
17331             time_before(jiffies, timeout))
17332                 return;
17333         /* start with the oldest sequence on the rcv list */
17334         list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
17335                 dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17336                 timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
17337                            dmabuf->time_stamp);
17338                 if (time_before(jiffies, timeout))
17339                         break;
17340                 abort_count++;
17341                 list_del_init(&dmabuf->hbuf.list);
17342                 list_for_each_entry_safe(d_buf, dnext,
17343                                          &dmabuf->dbuf.list, list) {
17344                         list_del_init(&d_buf->list);
17345                         lpfc_in_buf_free(vport->phba, d_buf);
17346                 }
17347                 lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
17348         }
17349         if (abort_count)
17350                 lpfc_update_rcv_time_stamp(vport);
17351 }
17352
17353 /**
17354  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
17355  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
17356  *
17357  * This function searches through the existing incomplete sequences that have
17358  * been sent to this @vport. If the frame matches one of the incomplete
17359  * sequences then the dbuf in the @dmabuf is added to the list of frames that
17360  * make up that sequence. If no sequence is found that matches this frame then
17361  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
17362  * This function returns a pointer to the first dmabuf in the sequence list that
17363  * the frame was linked to.
17364  **/
17365 static struct hbq_dmabuf *
17366 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
17367 {
17368         struct fc_frame_header *new_hdr;
17369         struct fc_frame_header *temp_hdr;
17370         struct lpfc_dmabuf *d_buf;
17371         struct lpfc_dmabuf *h_buf;
17372         struct hbq_dmabuf *seq_dmabuf = NULL;
17373         struct hbq_dmabuf *temp_dmabuf = NULL;
17374         uint8_t found = 0;
17375
17376         INIT_LIST_HEAD(&dmabuf->dbuf.list);
17377         dmabuf->time_stamp = jiffies;
17378         new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17379
17380         /* Use the hdr_buf to find the sequence that this frame belongs to */
17381         list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
17382                 temp_hdr = (struct fc_frame_header *)h_buf->virt;
17383                 if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
17384                     (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
17385                     (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
17386                         continue;
17387                 /* found a pending sequence that matches this frame */
17388                 seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17389                 break;
17390         }
17391         if (!seq_dmabuf) {
17392                 /*
17393                  * This indicates first frame received for this sequence.
17394                  * Queue the buffer on the vport's rcv_buffer_list.
17395                  */
17396                 list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
17397                 lpfc_update_rcv_time_stamp(vport);
17398                 return dmabuf;
17399         }
17400         temp_hdr = seq_dmabuf->hbuf.virt;
17401         if (be16_to_cpu(new_hdr->fh_seq_cnt) <
17402                 be16_to_cpu(temp_hdr->fh_seq_cnt)) {
17403                 list_del_init(&seq_dmabuf->hbuf.list);
17404                 list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
17405                 list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
17406                 lpfc_update_rcv_time_stamp(vport);
17407                 return dmabuf;
17408         }
17409         /* move this sequence to the tail to indicate a young sequence */
17410         list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
17411         seq_dmabuf->time_stamp = jiffies;
17412         lpfc_update_rcv_time_stamp(vport);
17413         if (list_empty(&seq_dmabuf->dbuf.list)) {
17414                 temp_hdr = dmabuf->hbuf.virt;
17415                 list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
17416                 return seq_dmabuf;
17417         }
17418         /* find the correct place in the sequence to insert this frame */
17419         d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
17420         while (!found) {
17421                 temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17422                 temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
17423                 /*
17424                  * If the frame's sequence count is greater than the frame on
17425                  * the list then insert the frame right after this frame
17426                  */
17427                 if (be16_to_cpu(new_hdr->fh_seq_cnt) >
17428                         be16_to_cpu(temp_hdr->fh_seq_cnt)) {
17429                         list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
17430                         found = 1;
17431                         break;
17432                 }
17433
17434                 if (&d_buf->list == &seq_dmabuf->dbuf.list)
17435                         break;
17436                 d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
17437         }
17438
17439         if (found)
17440                 return seq_dmabuf;
17441         return NULL;
17442 }
17443
17444 /**
17445  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
17446  * @vport: pointer to a vitural port
17447  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17448  *
17449  * This function tries to abort from the partially assembed sequence, described
17450  * by the information from basic abbort @dmabuf. It checks to see whether such
17451  * partially assembled sequence held by the driver. If so, it shall free up all
17452  * the frames from the partially assembled sequence.
17453  *
17454  * Return
17455  * true  -- if there is matching partially assembled sequence present and all
17456  *          the frames freed with the sequence;
17457  * false -- if there is no matching partially assembled sequence present so
17458  *          nothing got aborted in the lower layer driver
17459  **/
17460 static bool
17461 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
17462                             struct hbq_dmabuf *dmabuf)
17463 {
17464         struct fc_frame_header *new_hdr;
17465         struct fc_frame_header *temp_hdr;
17466         struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
17467         struct hbq_dmabuf *seq_dmabuf = NULL;
17468
17469         /* Use the hdr_buf to find the sequence that matches this frame */
17470         INIT_LIST_HEAD(&dmabuf->dbuf.list);
17471         INIT_LIST_HEAD(&dmabuf->hbuf.list);
17472         new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17473         list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
17474                 temp_hdr = (struct fc_frame_header *)h_buf->virt;
17475                 if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
17476                     (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
17477                     (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
17478                         continue;
17479                 /* found a pending sequence that matches this frame */
17480                 seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
17481                 break;
17482         }
17483
17484         /* Free up all the frames from the partially assembled sequence */
17485         if (seq_dmabuf) {
17486                 list_for_each_entry_safe(d_buf, n_buf,
17487                                          &seq_dmabuf->dbuf.list, list) {
17488                         list_del_init(&d_buf->list);
17489                         lpfc_in_buf_free(vport->phba, d_buf);
17490                 }
17491                 return true;
17492         }
17493         return false;
17494 }
17495
17496 /**
17497  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
17498  * @vport: pointer to a vitural port
17499  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17500  *
17501  * This function tries to abort from the assembed sequence from upper level
17502  * protocol, described by the information from basic abbort @dmabuf. It
17503  * checks to see whether such pending context exists at upper level protocol.
17504  * If so, it shall clean up the pending context.
17505  *
17506  * Return
17507  * true  -- if there is matching pending context of the sequence cleaned
17508  *          at ulp;
17509  * false -- if there is no matching pending context of the sequence present
17510  *          at ulp.
17511  **/
17512 static bool
17513 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
17514 {
17515         struct lpfc_hba *phba = vport->phba;
17516         int handled;
17517
17518         /* Accepting abort at ulp with SLI4 only */
17519         if (phba->sli_rev < LPFC_SLI_REV4)
17520                 return false;
17521
17522         /* Register all caring upper level protocols to attend abort */
17523         handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
17524         if (handled)
17525                 return true;
17526
17527         return false;
17528 }
17529
17530 /**
17531  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
17532  * @phba: Pointer to HBA context object.
17533  * @cmd_iocbq: pointer to the command iocbq structure.
17534  * @rsp_iocbq: pointer to the response iocbq structure.
17535  *
17536  * This function handles the sequence abort response iocb command complete
17537  * event. It properly releases the memory allocated to the sequence abort
17538  * accept iocb.
17539  **/
17540 static void
17541 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
17542                              struct lpfc_iocbq *cmd_iocbq,
17543                              struct lpfc_iocbq *rsp_iocbq)
17544 {
17545         struct lpfc_nodelist *ndlp;
17546
17547         if (cmd_iocbq) {
17548                 ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
17549                 lpfc_nlp_put(ndlp);
17550                 lpfc_nlp_not_used(ndlp);
17551                 lpfc_sli_release_iocbq(phba, cmd_iocbq);
17552         }
17553
17554         /* Failure means BLS ABORT RSP did not get delivered to remote node*/
17555         if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
17556                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17557                         "3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
17558                         rsp_iocbq->iocb.ulpStatus,
17559                         rsp_iocbq->iocb.un.ulpWord[4]);
17560 }
17561
17562 /**
17563  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
17564  * @phba: Pointer to HBA context object.
17565  * @xri: xri id in transaction.
17566  *
17567  * This function validates the xri maps to the known range of XRIs allocated an
17568  * used by the driver.
17569  **/
17570 uint16_t
17571 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
17572                       uint16_t xri)
17573 {
17574         uint16_t i;
17575
17576         for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
17577                 if (xri == phba->sli4_hba.xri_ids[i])
17578                         return i;
17579         }
17580         return NO_XRI;
17581 }
17582
17583 /**
17584  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
17585  * @phba: Pointer to HBA context object.
17586  * @fc_hdr: pointer to a FC frame header.
17587  *
17588  * This function sends a basic response to a previous unsol sequence abort
17589  * event after aborting the sequence handling.
17590  **/
17591 void
17592 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
17593                         struct fc_frame_header *fc_hdr, bool aborted)
17594 {
17595         struct lpfc_hba *phba = vport->phba;
17596         struct lpfc_iocbq *ctiocb = NULL;
17597         struct lpfc_nodelist *ndlp;
17598         uint16_t oxid, rxid, xri, lxri;
17599         uint32_t sid, fctl;
17600         IOCB_t *icmd;
17601         int rc;
17602
17603         if (!lpfc_is_link_up(phba))
17604                 return;
17605
17606         sid = sli4_sid_from_fc_hdr(fc_hdr);
17607         oxid = be16_to_cpu(fc_hdr->fh_ox_id);
17608         rxid = be16_to_cpu(fc_hdr->fh_rx_id);
17609
17610         ndlp = lpfc_findnode_did(vport, sid);
17611         if (!ndlp) {
17612                 ndlp = lpfc_nlp_init(vport, sid);
17613                 if (!ndlp) {
17614                         lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
17615                                          "1268 Failed to allocate ndlp for "
17616                                          "oxid:x%x SID:x%x\n", oxid, sid);
17617                         return;
17618                 }
17619                 /* Put ndlp onto pport node list */
17620                 lpfc_enqueue_node(vport, ndlp);
17621         } else if (!NLP_CHK_NODE_ACT(ndlp)) {
17622                 /* re-setup ndlp without removing from node list */
17623                 ndlp = lpfc_enable_node(vport, ndlp, NLP_STE_UNUSED_NODE);
17624                 if (!ndlp) {
17625                         lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
17626                                          "3275 Failed to active ndlp found "
17627                                          "for oxid:x%x SID:x%x\n", oxid, sid);
17628                         return;
17629                 }
17630         }
17631
17632         /* Allocate buffer for rsp iocb */
17633         ctiocb = lpfc_sli_get_iocbq(phba);
17634         if (!ctiocb)
17635                 return;
17636
17637         /* Extract the F_CTL field from FC_HDR */
17638         fctl = sli4_fctl_from_fc_hdr(fc_hdr);
17639
17640         icmd = &ctiocb->iocb;
17641         icmd->un.xseq64.bdl.bdeSize = 0;
17642         icmd->un.xseq64.bdl.ulpIoTag32 = 0;
17643         icmd->un.xseq64.w5.hcsw.Dfctl = 0;
17644         icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
17645         icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
17646
17647         /* Fill in the rest of iocb fields */
17648         icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
17649         icmd->ulpBdeCount = 0;
17650         icmd->ulpLe = 1;
17651         icmd->ulpClass = CLASS3;
17652         icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
17653         ctiocb->context1 = lpfc_nlp_get(ndlp);
17654
17655         ctiocb->vport = phba->pport;
17656         ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
17657         ctiocb->sli4_lxritag = NO_XRI;
17658         ctiocb->sli4_xritag = NO_XRI;
17659
17660         if (fctl & FC_FC_EX_CTX)
17661                 /* Exchange responder sent the abort so we
17662                  * own the oxid.
17663                  */
17664                 xri = oxid;
17665         else
17666                 xri = rxid;
17667         lxri = lpfc_sli4_xri_inrange(phba, xri);
17668         if (lxri != NO_XRI)
17669                 lpfc_set_rrq_active(phba, ndlp, lxri,
17670                         (xri == oxid) ? rxid : oxid, 0);
17671         /* For BA_ABTS from exchange responder, if the logical xri with
17672          * the oxid maps to the FCP XRI range, the port no longer has
17673          * that exchange context, send a BLS_RJT. Override the IOCB for
17674          * a BA_RJT.
17675          */
17676         if ((fctl & FC_FC_EX_CTX) &&
17677             (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
17678                 icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
17679                 bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
17680                 bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
17681                 bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
17682         }
17683
17684         /* If BA_ABTS failed to abort a partially assembled receive sequence,
17685          * the driver no longer has that exchange, send a BLS_RJT. Override
17686          * the IOCB for a BA_RJT.
17687          */
17688         if (aborted == false) {
17689                 icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
17690                 bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
17691                 bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
17692                 bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
17693         }
17694
17695         if (fctl & FC_FC_EX_CTX) {
17696                 /* ABTS sent by responder to CT exchange, construction
17697                  * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
17698                  * field and RX_ID from ABTS for RX_ID field.
17699                  */
17700                 bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
17701         } else {
17702                 /* ABTS sent by initiator to CT exchange, construction
17703                  * of BA_ACC will need to allocate a new XRI as for the
17704                  * XRI_TAG field.
17705                  */
17706                 bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
17707         }
17708         bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
17709         bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
17710
17711         /* Xmit CT abts response on exchange <xid> */
17712         lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
17713                          "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
17714                          icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
17715
17716         rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
17717         if (rc == IOCB_ERROR) {
17718                 lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
17719                                  "2925 Failed to issue CT ABTS RSP x%x on "
17720                                  "xri x%x, Data x%x\n",
17721                                  icmd->un.xseq64.w5.hcsw.Rctl, oxid,
17722                                  phba->link_state);
17723                 lpfc_nlp_put(ndlp);
17724                 ctiocb->context1 = NULL;
17725                 lpfc_sli_release_iocbq(phba, ctiocb);
17726         }
17727 }
17728
17729 /**
17730  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
17731  * @vport: Pointer to the vport on which this sequence was received
17732  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17733  *
17734  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
17735  * receive sequence is only partially assembed by the driver, it shall abort
17736  * the partially assembled frames for the sequence. Otherwise, if the
17737  * unsolicited receive sequence has been completely assembled and passed to
17738  * the Upper Layer Protocol (UPL), it then mark the per oxid status for the
17739  * unsolicited sequence has been aborted. After that, it will issue a basic
17740  * accept to accept the abort.
17741  **/
17742 static void
17743 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
17744                              struct hbq_dmabuf *dmabuf)
17745 {
17746         struct lpfc_hba *phba = vport->phba;
17747         struct fc_frame_header fc_hdr;
17748         uint32_t fctl;
17749         bool aborted;
17750
17751         /* Make a copy of fc_hdr before the dmabuf being released */
17752         memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
17753         fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
17754
17755         if (fctl & FC_FC_EX_CTX) {
17756                 /* ABTS by responder to exchange, no cleanup needed */
17757                 aborted = true;
17758         } else {
17759                 /* ABTS by initiator to exchange, need to do cleanup */
17760                 aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
17761                 if (aborted == false)
17762                         aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
17763         }
17764         lpfc_in_buf_free(phba, &dmabuf->dbuf);
17765
17766         if (phba->nvmet_support) {
17767                 lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
17768                 return;
17769         }
17770
17771         /* Respond with BA_ACC or BA_RJT accordingly */
17772         lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
17773 }
17774
17775 /**
17776  * lpfc_seq_complete - Indicates if a sequence is complete
17777  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17778  *
17779  * This function checks the sequence, starting with the frame described by
17780  * @dmabuf, to see if all the frames associated with this sequence are present.
17781  * the frames associated with this sequence are linked to the @dmabuf using the
17782  * dbuf list. This function looks for two major things. 1) That the first frame
17783  * has a sequence count of zero. 2) There is a frame with last frame of sequence
17784  * set. 3) That there are no holes in the sequence count. The function will
17785  * return 1 when the sequence is complete, otherwise it will return 0.
17786  **/
17787 static int
17788 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
17789 {
17790         struct fc_frame_header *hdr;
17791         struct lpfc_dmabuf *d_buf;
17792         struct hbq_dmabuf *seq_dmabuf;
17793         uint32_t fctl;
17794         int seq_count = 0;
17795
17796         hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
17797         /* make sure first fame of sequence has a sequence count of zero */
17798         if (hdr->fh_seq_cnt != seq_count)
17799                 return 0;
17800         fctl = (hdr->fh_f_ctl[0] << 16 |
17801                 hdr->fh_f_ctl[1] << 8 |
17802                 hdr->fh_f_ctl[2]);
17803         /* If last frame of sequence we can return success. */
17804         if (fctl & FC_FC_END_SEQ)
17805                 return 1;
17806         list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
17807                 seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17808                 hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
17809                 /* If there is a hole in the sequence count then fail. */
17810                 if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
17811                         return 0;
17812                 fctl = (hdr->fh_f_ctl[0] << 16 |
17813                         hdr->fh_f_ctl[1] << 8 |
17814                         hdr->fh_f_ctl[2]);
17815                 /* If last frame of sequence we can return success. */
17816                 if (fctl & FC_FC_END_SEQ)
17817                         return 1;
17818         }
17819         return 0;
17820 }
17821
17822 /**
17823  * lpfc_prep_seq - Prep sequence for ULP processing
17824  * @vport: Pointer to the vport on which this sequence was received
17825  * @dmabuf: pointer to a dmabuf that describes the FC sequence
17826  *
17827  * This function takes a sequence, described by a list of frames, and creates
17828  * a list of iocbq structures to describe the sequence. This iocbq list will be
17829  * used to issue to the generic unsolicited sequence handler. This routine
17830  * returns a pointer to the first iocbq in the list. If the function is unable
17831  * to allocate an iocbq then it throw out the received frames that were not
17832  * able to be described and return a pointer to the first iocbq. If unable to
17833  * allocate any iocbqs (including the first) this function will return NULL.
17834  **/
17835 static struct lpfc_iocbq *
17836 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
17837 {
17838         struct hbq_dmabuf *hbq_buf;
17839         struct lpfc_dmabuf *d_buf, *n_buf;
17840         struct lpfc_iocbq *first_iocbq, *iocbq;
17841         struct fc_frame_header *fc_hdr;
17842         uint32_t sid;
17843         uint32_t len, tot_len;
17844         struct ulp_bde64 *pbde;
17845
17846         fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
17847         /* remove from receive buffer list */
17848         list_del_init(&seq_dmabuf->hbuf.list);
17849         lpfc_update_rcv_time_stamp(vport);
17850         /* get the Remote Port's SID */
17851         sid = sli4_sid_from_fc_hdr(fc_hdr);
17852         tot_len = 0;
17853         /* Get an iocbq struct to fill in. */
17854         first_iocbq = lpfc_sli_get_iocbq(vport->phba);
17855         if (first_iocbq) {
17856                 /* Initialize the first IOCB. */
17857                 first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
17858                 first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
17859                 first_iocbq->vport = vport;
17860
17861                 /* Check FC Header to see what TYPE of frame we are rcv'ing */
17862                 if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
17863                         first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
17864                         first_iocbq->iocb.un.rcvels.parmRo =
17865                                 sli4_did_from_fc_hdr(fc_hdr);
17866                         first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
17867                 } else
17868                         first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
17869                 first_iocbq->iocb.ulpContext = NO_XRI;
17870                 first_iocbq->iocb.unsli3.rcvsli3.ox_id =
17871                         be16_to_cpu(fc_hdr->fh_ox_id);
17872                 /* iocbq is prepped for internal consumption.  Physical vpi. */
17873                 first_iocbq->iocb.unsli3.rcvsli3.vpi =
17874                         vport->phba->vpi_ids[vport->vpi];
17875                 /* put the first buffer into the first IOCBq */
17876                 tot_len = bf_get(lpfc_rcqe_length,
17877                                        &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
17878
17879                 first_iocbq->context2 = &seq_dmabuf->dbuf;
17880                 first_iocbq->context3 = NULL;
17881                 first_iocbq->iocb.ulpBdeCount = 1;
17882                 if (tot_len > LPFC_DATA_BUF_SIZE)
17883                         first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
17884                                                         LPFC_DATA_BUF_SIZE;
17885                 else
17886                         first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
17887
17888                 first_iocbq->iocb.un.rcvels.remoteID = sid;
17889
17890                 first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
17891         }
17892         iocbq = first_iocbq;
17893         /*
17894          * Each IOCBq can have two Buffers assigned, so go through the list
17895          * of buffers for this sequence and save two buffers in each IOCBq
17896          */
17897         list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
17898                 if (!iocbq) {
17899                         lpfc_in_buf_free(vport->phba, d_buf);
17900                         continue;
17901                 }
17902                 if (!iocbq->context3) {
17903                         iocbq->context3 = d_buf;
17904                         iocbq->iocb.ulpBdeCount++;
17905                         /* We need to get the size out of the right CQE */
17906                         hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17907                         len = bf_get(lpfc_rcqe_length,
17908                                        &hbq_buf->cq_event.cqe.rcqe_cmpl);
17909                         pbde = (struct ulp_bde64 *)
17910                                         &iocbq->iocb.unsli3.sli3Words[4];
17911                         if (len > LPFC_DATA_BUF_SIZE)
17912                                 pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
17913                         else
17914                                 pbde->tus.f.bdeSize = len;
17915
17916                         iocbq->iocb.unsli3.rcvsli3.acc_len += len;
17917                         tot_len += len;
17918                 } else {
17919                         iocbq = lpfc_sli_get_iocbq(vport->phba);
17920                         if (!iocbq) {
17921                                 if (first_iocbq) {
17922                                         first_iocbq->iocb.ulpStatus =
17923                                                         IOSTAT_FCP_RSP_ERROR;
17924                                         first_iocbq->iocb.un.ulpWord[4] =
17925                                                         IOERR_NO_RESOURCES;
17926                                 }
17927                                 lpfc_in_buf_free(vport->phba, d_buf);
17928                                 continue;
17929                         }
17930                         /* We need to get the size out of the right CQE */
17931                         hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
17932                         len = bf_get(lpfc_rcqe_length,
17933                                        &hbq_buf->cq_event.cqe.rcqe_cmpl);
17934                         iocbq->context2 = d_buf;
17935                         iocbq->context3 = NULL;
17936                         iocbq->iocb.ulpBdeCount = 1;
17937                         if (len > LPFC_DATA_BUF_SIZE)
17938                                 iocbq->iocb.un.cont64[0].tus.f.bdeSize =
17939                                                         LPFC_DATA_BUF_SIZE;
17940                         else
17941                                 iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
17942
17943                         tot_len += len;
17944                         iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
17945
17946                         iocbq->iocb.un.rcvels.remoteID = sid;
17947                         list_add_tail(&iocbq->list, &first_iocbq->list);
17948                 }
17949         }
17950         /* Free the sequence's header buffer */
17951         if (!first_iocbq)
17952                 lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
17953
17954         return first_iocbq;
17955 }
17956
17957 static void
17958 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
17959                           struct hbq_dmabuf *seq_dmabuf)
17960 {
17961         struct fc_frame_header *fc_hdr;
17962         struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
17963         struct lpfc_hba *phba = vport->phba;
17964
17965         fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
17966         iocbq = lpfc_prep_seq(vport, seq_dmabuf);
17967         if (!iocbq) {
17968                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17969                                 "2707 Ring %d handler: Failed to allocate "
17970                                 "iocb Rctl x%x Type x%x received\n",
17971                                 LPFC_ELS_RING,
17972                                 fc_hdr->fh_r_ctl, fc_hdr->fh_type);
17973                 return;
17974         }
17975         if (!lpfc_complete_unsol_iocb(phba,
17976                                       phba->sli4_hba.els_wq->pring,
17977                                       iocbq, fc_hdr->fh_r_ctl,
17978                                       fc_hdr->fh_type))
17979                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
17980                                 "2540 Ring %d handler: unexpected Rctl "
17981                                 "x%x Type x%x received\n",
17982                                 LPFC_ELS_RING,
17983                                 fc_hdr->fh_r_ctl, fc_hdr->fh_type);
17984
17985         /* Free iocb created in lpfc_prep_seq */
17986         list_for_each_entry_safe(curr_iocb, next_iocb,
17987                 &iocbq->list, list) {
17988                 list_del_init(&curr_iocb->list);
17989                 lpfc_sli_release_iocbq(phba, curr_iocb);
17990         }
17991         lpfc_sli_release_iocbq(phba, iocbq);
17992 }
17993
17994 static void
17995 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
17996                             struct lpfc_iocbq *rspiocb)
17997 {
17998         struct lpfc_dmabuf *pcmd = cmdiocb->context2;
17999
18000         if (pcmd && pcmd->virt)
18001                 dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
18002         kfree(pcmd);
18003         lpfc_sli_release_iocbq(phba, cmdiocb);
18004         lpfc_drain_txq(phba);
18005 }
18006
18007 static void
18008 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
18009                               struct hbq_dmabuf *dmabuf)
18010 {
18011         struct fc_frame_header *fc_hdr;
18012         struct lpfc_hba *phba = vport->phba;
18013         struct lpfc_iocbq *iocbq = NULL;
18014         union  lpfc_wqe *wqe;
18015         struct lpfc_dmabuf *pcmd = NULL;
18016         uint32_t frame_len;
18017         int rc;
18018         unsigned long iflags;
18019
18020         fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18021         frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
18022
18023         /* Send the received frame back */
18024         iocbq = lpfc_sli_get_iocbq(phba);
18025         if (!iocbq) {
18026                 /* Queue cq event and wakeup worker thread to process it */
18027                 spin_lock_irqsave(&phba->hbalock, iflags);
18028                 list_add_tail(&dmabuf->cq_event.list,
18029                               &phba->sli4_hba.sp_queue_event);
18030                 phba->hba_flag |= HBA_SP_QUEUE_EVT;
18031                 spin_unlock_irqrestore(&phba->hbalock, iflags);
18032                 lpfc_worker_wake_up(phba);
18033                 return;
18034         }
18035
18036         /* Allocate buffer for command payload */
18037         pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
18038         if (pcmd)
18039                 pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
18040                                             &pcmd->phys);
18041         if (!pcmd || !pcmd->virt)
18042                 goto exit;
18043
18044         INIT_LIST_HEAD(&pcmd->list);
18045
18046         /* copyin the payload */
18047         memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
18048
18049         /* fill in BDE's for command */
18050         iocbq->iocb.un.xseq64.bdl.addrHigh = putPaddrHigh(pcmd->phys);
18051         iocbq->iocb.un.xseq64.bdl.addrLow = putPaddrLow(pcmd->phys);
18052         iocbq->iocb.un.xseq64.bdl.bdeFlags = BUFF_TYPE_BDE_64;
18053         iocbq->iocb.un.xseq64.bdl.bdeSize = frame_len;
18054
18055         iocbq->context2 = pcmd;
18056         iocbq->vport = vport;
18057         iocbq->iocb_flag &= ~LPFC_FIP_ELS_ID_MASK;
18058         iocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
18059
18060         /*
18061          * Setup rest of the iocb as though it were a WQE
18062          * Build the SEND_FRAME WQE
18063          */
18064         wqe = (union lpfc_wqe *)&iocbq->iocb;
18065
18066         wqe->send_frame.frame_len = frame_len;
18067         wqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((uint32_t *)fc_hdr));
18068         wqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((uint32_t *)fc_hdr + 1));
18069         wqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((uint32_t *)fc_hdr + 2));
18070         wqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((uint32_t *)fc_hdr + 3));
18071         wqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((uint32_t *)fc_hdr + 4));
18072         wqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((uint32_t *)fc_hdr + 5));
18073
18074         iocbq->iocb.ulpCommand = CMD_SEND_FRAME;
18075         iocbq->iocb.ulpLe = 1;
18076         iocbq->iocb_cmpl = lpfc_sli4_mds_loopback_cmpl;
18077         rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
18078         if (rc == IOCB_ERROR)
18079                 goto exit;
18080
18081         lpfc_in_buf_free(phba, &dmabuf->dbuf);
18082         return;
18083
18084 exit:
18085         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18086                         "2023 Unable to process MDS loopback frame\n");
18087         if (pcmd && pcmd->virt)
18088                 dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
18089         kfree(pcmd);
18090         if (iocbq)
18091                 lpfc_sli_release_iocbq(phba, iocbq);
18092         lpfc_in_buf_free(phba, &dmabuf->dbuf);
18093 }
18094
18095 /**
18096  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
18097  * @phba: Pointer to HBA context object.
18098  *
18099  * This function is called with no lock held. This function processes all
18100  * the received buffers and gives it to upper layers when a received buffer
18101  * indicates that it is the final frame in the sequence. The interrupt
18102  * service routine processes received buffers at interrupt contexts.
18103  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
18104  * appropriate receive function when the final frame in a sequence is received.
18105  **/
18106 void
18107 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
18108                                  struct hbq_dmabuf *dmabuf)
18109 {
18110         struct hbq_dmabuf *seq_dmabuf;
18111         struct fc_frame_header *fc_hdr;
18112         struct lpfc_vport *vport;
18113         uint32_t fcfi;
18114         uint32_t did;
18115
18116         /* Process each received buffer */
18117         fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18118
18119         if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
18120             fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
18121                 vport = phba->pport;
18122                 /* Handle MDS Loopback frames */
18123                 lpfc_sli4_handle_mds_loopback(vport, dmabuf);
18124                 return;
18125         }
18126
18127         /* check to see if this a valid type of frame */
18128         if (lpfc_fc_frame_check(phba, fc_hdr)) {
18129                 lpfc_in_buf_free(phba, &dmabuf->dbuf);
18130                 return;
18131         }
18132
18133         if ((bf_get(lpfc_cqe_code,
18134                     &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
18135                 fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
18136                               &dmabuf->cq_event.cqe.rcqe_cmpl);
18137         else
18138                 fcfi = bf_get(lpfc_rcqe_fcf_id,
18139                               &dmabuf->cq_event.cqe.rcqe_cmpl);
18140
18141         if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
18142                 vport = phba->pport;
18143                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
18144                                 "2023 MDS Loopback %d bytes\n",
18145                                 bf_get(lpfc_rcqe_length,
18146                                        &dmabuf->cq_event.cqe.rcqe_cmpl));
18147                 /* Handle MDS Loopback frames */
18148                 lpfc_sli4_handle_mds_loopback(vport, dmabuf);
18149                 return;
18150         }
18151
18152         /* d_id this frame is directed to */
18153         did = sli4_did_from_fc_hdr(fc_hdr);
18154
18155         vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
18156         if (!vport) {
18157                 /* throw out the frame */
18158                 lpfc_in_buf_free(phba, &dmabuf->dbuf);
18159                 return;
18160         }
18161
18162         /* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
18163         if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
18164                 (did != Fabric_DID)) {
18165                 /*
18166                  * Throw out the frame if we are not pt2pt.
18167                  * The pt2pt protocol allows for discovery frames
18168                  * to be received without a registered VPI.
18169                  */
18170                 if (!(vport->fc_flag & FC_PT2PT) ||
18171                         (phba->link_state == LPFC_HBA_READY)) {
18172                         lpfc_in_buf_free(phba, &dmabuf->dbuf);
18173                         return;
18174                 }
18175         }
18176
18177         /* Handle the basic abort sequence (BA_ABTS) event */
18178         if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
18179                 lpfc_sli4_handle_unsol_abort(vport, dmabuf);
18180                 return;
18181         }
18182
18183         /* Link this frame */
18184         seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
18185         if (!seq_dmabuf) {
18186                 /* unable to add frame to vport - throw it out */
18187                 lpfc_in_buf_free(phba, &dmabuf->dbuf);
18188                 return;
18189         }
18190         /* If not last frame in sequence continue processing frames. */
18191         if (!lpfc_seq_complete(seq_dmabuf))
18192                 return;
18193
18194         /* Send the complete sequence to the upper layer protocol */
18195         lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
18196 }
18197
18198 /**
18199  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
18200  * @phba: pointer to lpfc hba data structure.
18201  *
18202  * This routine is invoked to post rpi header templates to the
18203  * HBA consistent with the SLI-4 interface spec.  This routine
18204  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18205  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18206  *
18207  * This routine does not require any locks.  It's usage is expected
18208  * to be driver load or reset recovery when the driver is
18209  * sequential.
18210  *
18211  * Return codes
18212  *      0 - successful
18213  *      -EIO - The mailbox failed to complete successfully.
18214  *      When this error occurs, the driver is not guaranteed
18215  *      to have any rpi regions posted to the device and
18216  *      must either attempt to repost the regions or take a
18217  *      fatal error.
18218  **/
18219 int
18220 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
18221 {
18222         struct lpfc_rpi_hdr *rpi_page;
18223         uint32_t rc = 0;
18224         uint16_t lrpi = 0;
18225
18226         /* SLI4 ports that support extents do not require RPI headers. */
18227         if (!phba->sli4_hba.rpi_hdrs_in_use)
18228                 goto exit;
18229         if (phba->sli4_hba.extents_in_use)
18230                 return -EIO;
18231
18232         list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
18233                 /*
18234                  * Assign the rpi headers a physical rpi only if the driver
18235                  * has not initialized those resources.  A port reset only
18236                  * needs the headers posted.
18237                  */
18238                 if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
18239                     LPFC_RPI_RSRC_RDY)
18240                         rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18241
18242                 rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
18243                 if (rc != MBX_SUCCESS) {
18244                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18245                                         "2008 Error %d posting all rpi "
18246                                         "headers\n", rc);
18247                         rc = -EIO;
18248                         break;
18249                 }
18250         }
18251
18252  exit:
18253         bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
18254                LPFC_RPI_RSRC_RDY);
18255         return rc;
18256 }
18257
18258 /**
18259  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
18260  * @phba: pointer to lpfc hba data structure.
18261  * @rpi_page:  pointer to the rpi memory region.
18262  *
18263  * This routine is invoked to post a single rpi header to the
18264  * HBA consistent with the SLI-4 interface spec.  This memory region
18265  * maps up to 64 rpi context regions.
18266  *
18267  * Return codes
18268  *      0 - successful
18269  *      -ENOMEM - No available memory
18270  *      -EIO - The mailbox failed to complete successfully.
18271  **/
18272 int
18273 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
18274 {
18275         LPFC_MBOXQ_t *mboxq;
18276         struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
18277         uint32_t rc = 0;
18278         uint32_t shdr_status, shdr_add_status;
18279         union lpfc_sli4_cfg_shdr *shdr;
18280
18281         /* SLI4 ports that support extents do not require RPI headers. */
18282         if (!phba->sli4_hba.rpi_hdrs_in_use)
18283                 return rc;
18284         if (phba->sli4_hba.extents_in_use)
18285                 return -EIO;
18286
18287         /* The port is notified of the header region via a mailbox command. */
18288         mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18289         if (!mboxq) {
18290                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18291                                 "2001 Unable to allocate memory for issuing "
18292                                 "SLI_CONFIG_SPECIAL mailbox command\n");
18293                 return -ENOMEM;
18294         }
18295
18296         /* Post all rpi memory regions to the port. */
18297         hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
18298         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
18299                          LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
18300                          sizeof(struct lpfc_mbx_post_hdr_tmpl) -
18301                          sizeof(struct lpfc_sli4_cfg_mhdr),
18302                          LPFC_SLI4_MBX_EMBED);
18303
18304
18305         /* Post the physical rpi to the port for this rpi header. */
18306         bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
18307                rpi_page->start_rpi);
18308         bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
18309                hdr_tmpl, rpi_page->page_count);
18310
18311         hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
18312         hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
18313         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
18314         shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
18315         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18316         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18317         if (rc != MBX_TIMEOUT)
18318                 mempool_free(mboxq, phba->mbox_mem_pool);
18319         if (shdr_status || shdr_add_status || rc) {
18320                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18321                                 "2514 POST_RPI_HDR mailbox failed with "
18322                                 "status x%x add_status x%x, mbx status x%x\n",
18323                                 shdr_status, shdr_add_status, rc);
18324                 rc = -ENXIO;
18325         } else {
18326                 /*
18327                  * The next_rpi stores the next logical module-64 rpi value used
18328                  * to post physical rpis in subsequent rpi postings.
18329                  */
18330                 spin_lock_irq(&phba->hbalock);
18331                 phba->sli4_hba.next_rpi = rpi_page->next_rpi;
18332                 spin_unlock_irq(&phba->hbalock);
18333         }
18334         return rc;
18335 }
18336
18337 /**
18338  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
18339  * @phba: pointer to lpfc hba data structure.
18340  *
18341  * This routine is invoked to post rpi header templates to the
18342  * HBA consistent with the SLI-4 interface spec.  This routine
18343  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18344  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18345  *
18346  * Returns
18347  *      A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
18348  *      LPFC_RPI_ALLOC_ERROR if no rpis are available.
18349  **/
18350 int
18351 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
18352 {
18353         unsigned long rpi;
18354         uint16_t max_rpi, rpi_limit;
18355         uint16_t rpi_remaining, lrpi = 0;
18356         struct lpfc_rpi_hdr *rpi_hdr;
18357         unsigned long iflag;
18358
18359         /*
18360          * Fetch the next logical rpi.  Because this index is logical,
18361          * the  driver starts at 0 each time.
18362          */
18363         spin_lock_irqsave(&phba->hbalock, iflag);
18364         max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
18365         rpi_limit = phba->sli4_hba.next_rpi;
18366
18367         rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
18368         if (rpi >= rpi_limit)
18369                 rpi = LPFC_RPI_ALLOC_ERROR;
18370         else {
18371                 set_bit(rpi, phba->sli4_hba.rpi_bmask);
18372                 phba->sli4_hba.max_cfg_param.rpi_used++;
18373                 phba->sli4_hba.rpi_count++;
18374         }
18375         lpfc_printf_log(phba, KERN_INFO,
18376                         LOG_NODE | LOG_DISCOVERY,
18377                         "0001 Allocated rpi:x%x max:x%x lim:x%x\n",
18378                         (int) rpi, max_rpi, rpi_limit);
18379
18380         /*
18381          * Don't try to allocate more rpi header regions if the device limit
18382          * has been exhausted.
18383          */
18384         if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
18385             (phba->sli4_hba.rpi_count >= max_rpi)) {
18386                 spin_unlock_irqrestore(&phba->hbalock, iflag);
18387                 return rpi;
18388         }
18389
18390         /*
18391          * RPI header postings are not required for SLI4 ports capable of
18392          * extents.
18393          */
18394         if (!phba->sli4_hba.rpi_hdrs_in_use) {
18395                 spin_unlock_irqrestore(&phba->hbalock, iflag);
18396                 return rpi;
18397         }
18398
18399         /*
18400          * If the driver is running low on rpi resources, allocate another
18401          * page now.  Note that the next_rpi value is used because
18402          * it represents how many are actually in use whereas max_rpi notes
18403          * how many are supported max by the device.
18404          */
18405         rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
18406         spin_unlock_irqrestore(&phba->hbalock, iflag);
18407         if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
18408                 rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
18409                 if (!rpi_hdr) {
18410                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18411                                         "2002 Error Could not grow rpi "
18412                                         "count\n");
18413                 } else {
18414                         lrpi = rpi_hdr->start_rpi;
18415                         rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
18416                         lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
18417                 }
18418         }
18419
18420         return rpi;
18421 }
18422
18423 /**
18424  * lpfc_sli4_free_rpi - Release an rpi for reuse.
18425  * @phba: pointer to lpfc hba data structure.
18426  *
18427  * This routine is invoked to release an rpi to the pool of
18428  * available rpis maintained by the driver.
18429  **/
18430 static void
18431 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
18432 {
18433         /*
18434          * if the rpi value indicates a prior unreg has already
18435          * been done, skip the unreg.
18436          */
18437         if (rpi == LPFC_RPI_ALLOC_ERROR)
18438                 return;
18439
18440         if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
18441                 phba->sli4_hba.rpi_count--;
18442                 phba->sli4_hba.max_cfg_param.rpi_used--;
18443         } else {
18444                 lpfc_printf_log(phba, KERN_INFO,
18445                                 LOG_NODE | LOG_DISCOVERY,
18446                                 "2016 rpi %x not inuse\n",
18447                                 rpi);
18448         }
18449 }
18450
18451 /**
18452  * lpfc_sli4_free_rpi - Release an rpi for reuse.
18453  * @phba: pointer to lpfc hba data structure.
18454  *
18455  * This routine is invoked to release an rpi to the pool of
18456  * available rpis maintained by the driver.
18457  **/
18458 void
18459 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
18460 {
18461         spin_lock_irq(&phba->hbalock);
18462         __lpfc_sli4_free_rpi(phba, rpi);
18463         spin_unlock_irq(&phba->hbalock);
18464 }
18465
18466 /**
18467  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
18468  * @phba: pointer to lpfc hba data structure.
18469  *
18470  * This routine is invoked to remove the memory region that
18471  * provided rpi via a bitmask.
18472  **/
18473 void
18474 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
18475 {
18476         kfree(phba->sli4_hba.rpi_bmask);
18477         kfree(phba->sli4_hba.rpi_ids);
18478         bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
18479 }
18480
18481 /**
18482  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
18483  * @phba: pointer to lpfc hba data structure.
18484  *
18485  * This routine is invoked to remove the memory region that
18486  * provided rpi via a bitmask.
18487  **/
18488 int
18489 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
18490         void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
18491 {
18492         LPFC_MBOXQ_t *mboxq;
18493         struct lpfc_hba *phba = ndlp->phba;
18494         int rc;
18495
18496         /* The port is notified of the header region via a mailbox command. */
18497         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18498         if (!mboxq)
18499                 return -ENOMEM;
18500
18501         /* Post all rpi memory regions to the port. */
18502         lpfc_resume_rpi(mboxq, ndlp);
18503         if (cmpl) {
18504                 mboxq->mbox_cmpl = cmpl;
18505                 mboxq->ctx_buf = arg;
18506                 mboxq->ctx_ndlp = ndlp;
18507         } else
18508                 mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
18509         mboxq->vport = ndlp->vport;
18510         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18511         if (rc == MBX_NOT_FINISHED) {
18512                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
18513                                 "2010 Resume RPI Mailbox failed "
18514                                 "status %d, mbxStatus x%x\n", rc,
18515                                 bf_get(lpfc_mqe_status, &mboxq->u.mqe));
18516                 mempool_free(mboxq, phba->mbox_mem_pool);
18517                 return -EIO;
18518         }
18519         return 0;
18520 }
18521
18522 /**
18523  * lpfc_sli4_init_vpi - Initialize a vpi with the port
18524  * @vport: Pointer to the vport for which the vpi is being initialized
18525  *
18526  * This routine is invoked to activate a vpi with the port.
18527  *
18528  * Returns:
18529  *    0 success
18530  *    -Evalue otherwise
18531  **/
18532 int
18533 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
18534 {
18535         LPFC_MBOXQ_t *mboxq;
18536         int rc = 0;
18537         int retval = MBX_SUCCESS;
18538         uint32_t mbox_tmo;
18539         struct lpfc_hba *phba = vport->phba;
18540         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18541         if (!mboxq)
18542                 return -ENOMEM;
18543         lpfc_init_vpi(phba, mboxq, vport->vpi);
18544         mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
18545         rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
18546         if (rc != MBX_SUCCESS) {
18547                 lpfc_printf_vlog(vport, KERN_ERR, LOG_SLI,
18548                                 "2022 INIT VPI Mailbox failed "
18549                                 "status %d, mbxStatus x%x\n", rc,
18550                                 bf_get(lpfc_mqe_status, &mboxq->u.mqe));
18551                 retval = -EIO;
18552         }
18553         if (rc != MBX_TIMEOUT)
18554                 mempool_free(mboxq, vport->phba->mbox_mem_pool);
18555
18556         return retval;
18557 }
18558
18559 /**
18560  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
18561  * @phba: pointer to lpfc hba data structure.
18562  * @mboxq: Pointer to mailbox object.
18563  *
18564  * This routine is invoked to manually add a single FCF record. The caller
18565  * must pass a completely initialized FCF_Record.  This routine takes
18566  * care of the nonembedded mailbox operations.
18567  **/
18568 static void
18569 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
18570 {
18571         void *virt_addr;
18572         union lpfc_sli4_cfg_shdr *shdr;
18573         uint32_t shdr_status, shdr_add_status;
18574
18575         virt_addr = mboxq->sge_array->addr[0];
18576         /* The IOCTL status is embedded in the mailbox subheader. */
18577         shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
18578         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18579         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18580
18581         if ((shdr_status || shdr_add_status) &&
18582                 (shdr_status != STATUS_FCF_IN_USE))
18583                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18584                         "2558 ADD_FCF_RECORD mailbox failed with "
18585                         "status x%x add_status x%x\n",
18586                         shdr_status, shdr_add_status);
18587
18588         lpfc_sli4_mbox_cmd_free(phba, mboxq);
18589 }
18590
18591 /**
18592  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
18593  * @phba: pointer to lpfc hba data structure.
18594  * @fcf_record:  pointer to the initialized fcf record to add.
18595  *
18596  * This routine is invoked to manually add a single FCF record. The caller
18597  * must pass a completely initialized FCF_Record.  This routine takes
18598  * care of the nonembedded mailbox operations.
18599  **/
18600 int
18601 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
18602 {
18603         int rc = 0;
18604         LPFC_MBOXQ_t *mboxq;
18605         uint8_t *bytep;
18606         void *virt_addr;
18607         struct lpfc_mbx_sge sge;
18608         uint32_t alloc_len, req_len;
18609         uint32_t fcfindex;
18610
18611         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18612         if (!mboxq) {
18613                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18614                         "2009 Failed to allocate mbox for ADD_FCF cmd\n");
18615                 return -ENOMEM;
18616         }
18617
18618         req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
18619                   sizeof(uint32_t);
18620
18621         /* Allocate DMA memory and set up the non-embedded mailbox command */
18622         alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
18623                                      LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
18624                                      req_len, LPFC_SLI4_MBX_NEMBED);
18625         if (alloc_len < req_len) {
18626                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18627                         "2523 Allocated DMA memory size (x%x) is "
18628                         "less than the requested DMA memory "
18629                         "size (x%x)\n", alloc_len, req_len);
18630                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
18631                 return -ENOMEM;
18632         }
18633
18634         /*
18635          * Get the first SGE entry from the non-embedded DMA memory.  This
18636          * routine only uses a single SGE.
18637          */
18638         lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
18639         virt_addr = mboxq->sge_array->addr[0];
18640         /*
18641          * Configure the FCF record for FCFI 0.  This is the driver's
18642          * hardcoded default and gets used in nonFIP mode.
18643          */
18644         fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
18645         bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
18646         lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
18647
18648         /*
18649          * Copy the fcf_index and the FCF Record Data. The data starts after
18650          * the FCoE header plus word10. The data copy needs to be endian
18651          * correct.
18652          */
18653         bytep += sizeof(uint32_t);
18654         lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
18655         mboxq->vport = phba->pport;
18656         mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
18657         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18658         if (rc == MBX_NOT_FINISHED) {
18659                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18660                         "2515 ADD_FCF_RECORD mailbox failed with "
18661                         "status 0x%x\n", rc);
18662                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
18663                 rc = -EIO;
18664         } else
18665                 rc = 0;
18666
18667         return rc;
18668 }
18669
18670 /**
18671  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
18672  * @phba: pointer to lpfc hba data structure.
18673  * @fcf_record:  pointer to the fcf record to write the default data.
18674  * @fcf_index: FCF table entry index.
18675  *
18676  * This routine is invoked to build the driver's default FCF record.  The
18677  * values used are hardcoded.  This routine handles memory initialization.
18678  *
18679  **/
18680 void
18681 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
18682                                 struct fcf_record *fcf_record,
18683                                 uint16_t fcf_index)
18684 {
18685         memset(fcf_record, 0, sizeof(struct fcf_record));
18686         fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
18687         fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
18688         fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
18689         bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
18690         bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
18691         bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
18692         bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
18693         bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
18694         bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
18695         bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
18696         bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
18697         bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
18698         bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
18699         bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
18700         bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
18701         bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
18702                 LPFC_FCF_FPMA | LPFC_FCF_SPMA);
18703         /* Set the VLAN bit map */
18704         if (phba->valid_vlan) {
18705                 fcf_record->vlan_bitmap[phba->vlan_id / 8]
18706                         = 1 << (phba->vlan_id % 8);
18707         }
18708 }
18709
18710 /**
18711  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
18712  * @phba: pointer to lpfc hba data structure.
18713  * @fcf_index: FCF table entry offset.
18714  *
18715  * This routine is invoked to scan the entire FCF table by reading FCF
18716  * record and processing it one at a time starting from the @fcf_index
18717  * for initial FCF discovery or fast FCF failover rediscovery.
18718  *
18719  * Return 0 if the mailbox command is submitted successfully, none 0
18720  * otherwise.
18721  **/
18722 int
18723 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
18724 {
18725         int rc = 0, error;
18726         LPFC_MBOXQ_t *mboxq;
18727
18728         phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
18729         phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
18730         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18731         if (!mboxq) {
18732                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
18733                                 "2000 Failed to allocate mbox for "
18734                                 "READ_FCF cmd\n");
18735                 error = -ENOMEM;
18736                 goto fail_fcf_scan;
18737         }
18738         /* Construct the read FCF record mailbox command */
18739         rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
18740         if (rc) {
18741                 error = -EINVAL;
18742                 goto fail_fcf_scan;
18743         }
18744         /* Issue the mailbox command asynchronously */
18745         mboxq->vport = phba->pport;
18746         mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
18747
18748         spin_lock_irq(&phba->hbalock);
18749         phba->hba_flag |= FCF_TS_INPROG;
18750         spin_unlock_irq(&phba->hbalock);
18751
18752         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18753         if (rc == MBX_NOT_FINISHED)
18754                 error = -EIO;
18755         else {
18756                 /* Reset eligible FCF count for new scan */
18757                 if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
18758                         phba->fcf.eligible_fcf_cnt = 0;
18759                 error = 0;
18760         }
18761 fail_fcf_scan:
18762         if (error) {
18763                 if (mboxq)
18764                         lpfc_sli4_mbox_cmd_free(phba, mboxq);
18765                 /* FCF scan failed, clear FCF_TS_INPROG flag */
18766                 spin_lock_irq(&phba->hbalock);
18767                 phba->hba_flag &= ~FCF_TS_INPROG;
18768                 spin_unlock_irq(&phba->hbalock);
18769         }
18770         return error;
18771 }
18772
18773 /**
18774  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
18775  * @phba: pointer to lpfc hba data structure.
18776  * @fcf_index: FCF table entry offset.
18777  *
18778  * This routine is invoked to read an FCF record indicated by @fcf_index
18779  * and to use it for FLOGI roundrobin FCF failover.
18780  *
18781  * Return 0 if the mailbox command is submitted successfully, none 0
18782  * otherwise.
18783  **/
18784 int
18785 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
18786 {
18787         int rc = 0, error;
18788         LPFC_MBOXQ_t *mboxq;
18789
18790         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18791         if (!mboxq) {
18792                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
18793                                 "2763 Failed to allocate mbox for "
18794                                 "READ_FCF cmd\n");
18795                 error = -ENOMEM;
18796                 goto fail_fcf_read;
18797         }
18798         /* Construct the read FCF record mailbox command */
18799         rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
18800         if (rc) {
18801                 error = -EINVAL;
18802                 goto fail_fcf_read;
18803         }
18804         /* Issue the mailbox command asynchronously */
18805         mboxq->vport = phba->pport;
18806         mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
18807         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18808         if (rc == MBX_NOT_FINISHED)
18809                 error = -EIO;
18810         else
18811                 error = 0;
18812
18813 fail_fcf_read:
18814         if (error && mboxq)
18815                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
18816         return error;
18817 }
18818
18819 /**
18820  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
18821  * @phba: pointer to lpfc hba data structure.
18822  * @fcf_index: FCF table entry offset.
18823  *
18824  * This routine is invoked to read an FCF record indicated by @fcf_index to
18825  * determine whether it's eligible for FLOGI roundrobin failover list.
18826  *
18827  * Return 0 if the mailbox command is submitted successfully, none 0
18828  * otherwise.
18829  **/
18830 int
18831 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
18832 {
18833         int rc = 0, error;
18834         LPFC_MBOXQ_t *mboxq;
18835
18836         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18837         if (!mboxq) {
18838                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
18839                                 "2758 Failed to allocate mbox for "
18840                                 "READ_FCF cmd\n");
18841                                 error = -ENOMEM;
18842                                 goto fail_fcf_read;
18843         }
18844         /* Construct the read FCF record mailbox command */
18845         rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
18846         if (rc) {
18847                 error = -EINVAL;
18848                 goto fail_fcf_read;
18849         }
18850         /* Issue the mailbox command asynchronously */
18851         mboxq->vport = phba->pport;
18852         mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
18853         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
18854         if (rc == MBX_NOT_FINISHED)
18855                 error = -EIO;
18856         else
18857                 error = 0;
18858
18859 fail_fcf_read:
18860         if (error && mboxq)
18861                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
18862         return error;
18863 }
18864
18865 /**
18866  * lpfc_check_next_fcf_pri_level
18867  * phba pointer to the lpfc_hba struct for this port.
18868  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
18869  * routine when the rr_bmask is empty. The FCF indecies are put into the
18870  * rr_bmask based on their priority level. Starting from the highest priority
18871  * to the lowest. The most likely FCF candidate will be in the highest
18872  * priority group. When this routine is called it searches the fcf_pri list for
18873  * next lowest priority group and repopulates the rr_bmask with only those
18874  * fcf_indexes.
18875  * returns:
18876  * 1=success 0=failure
18877  **/
18878 static int
18879 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
18880 {
18881         uint16_t next_fcf_pri;
18882         uint16_t last_index;
18883         struct lpfc_fcf_pri *fcf_pri;
18884         int rc;
18885         int ret = 0;
18886
18887         last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
18888                         LPFC_SLI4_FCF_TBL_INDX_MAX);
18889         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
18890                         "3060 Last IDX %d\n", last_index);
18891
18892         /* Verify the priority list has 2 or more entries */
18893         spin_lock_irq(&phba->hbalock);
18894         if (list_empty(&phba->fcf.fcf_pri_list) ||
18895             list_is_singular(&phba->fcf.fcf_pri_list)) {
18896                 spin_unlock_irq(&phba->hbalock);
18897                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
18898                         "3061 Last IDX %d\n", last_index);
18899                 return 0; /* Empty rr list */
18900         }
18901         spin_unlock_irq(&phba->hbalock);
18902
18903         next_fcf_pri = 0;
18904         /*
18905          * Clear the rr_bmask and set all of the bits that are at this
18906          * priority.
18907          */
18908         memset(phba->fcf.fcf_rr_bmask, 0,
18909                         sizeof(*phba->fcf.fcf_rr_bmask));
18910         spin_lock_irq(&phba->hbalock);
18911         list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
18912                 if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
18913                         continue;
18914                 /*
18915                  * the 1st priority that has not FLOGI failed
18916                  * will be the highest.
18917                  */
18918                 if (!next_fcf_pri)
18919                         next_fcf_pri = fcf_pri->fcf_rec.priority;
18920                 spin_unlock_irq(&phba->hbalock);
18921                 if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
18922                         rc = lpfc_sli4_fcf_rr_index_set(phba,
18923                                                 fcf_pri->fcf_rec.fcf_index);
18924                         if (rc)
18925                                 return 0;
18926                 }
18927                 spin_lock_irq(&phba->hbalock);
18928         }
18929         /*
18930          * if next_fcf_pri was not set above and the list is not empty then
18931          * we have failed flogis on all of them. So reset flogi failed
18932          * and start at the beginning.
18933          */
18934         if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
18935                 list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
18936                         fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
18937                         /*
18938                          * the 1st priority that has not FLOGI failed
18939                          * will be the highest.
18940                          */
18941                         if (!next_fcf_pri)
18942                                 next_fcf_pri = fcf_pri->fcf_rec.priority;
18943                         spin_unlock_irq(&phba->hbalock);
18944                         if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
18945                                 rc = lpfc_sli4_fcf_rr_index_set(phba,
18946                                                 fcf_pri->fcf_rec.fcf_index);
18947                                 if (rc)
18948                                         return 0;
18949                         }
18950                         spin_lock_irq(&phba->hbalock);
18951                 }
18952         } else
18953                 ret = 1;
18954         spin_unlock_irq(&phba->hbalock);
18955
18956         return ret;
18957 }
18958 /**
18959  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
18960  * @phba: pointer to lpfc hba data structure.
18961  *
18962  * This routine is to get the next eligible FCF record index in a round
18963  * robin fashion. If the next eligible FCF record index equals to the
18964  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
18965  * shall be returned, otherwise, the next eligible FCF record's index
18966  * shall be returned.
18967  **/
18968 uint16_t
18969 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
18970 {
18971         uint16_t next_fcf_index;
18972
18973 initial_priority:
18974         /* Search start from next bit of currently registered FCF index */
18975         next_fcf_index = phba->fcf.current_rec.fcf_indx;
18976
18977 next_priority:
18978         /* Determine the next fcf index to check */
18979         next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
18980         next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
18981                                        LPFC_SLI4_FCF_TBL_INDX_MAX,
18982                                        next_fcf_index);
18983
18984         /* Wrap around condition on phba->fcf.fcf_rr_bmask */
18985         if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
18986                 /*
18987                  * If we have wrapped then we need to clear the bits that
18988                  * have been tested so that we can detect when we should
18989                  * change the priority level.
18990                  */
18991                 next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
18992                                                LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
18993         }
18994
18995
18996         /* Check roundrobin failover list empty condition */
18997         if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
18998                 next_fcf_index == phba->fcf.current_rec.fcf_indx) {
18999                 /*
19000                  * If next fcf index is not found check if there are lower
19001                  * Priority level fcf's in the fcf_priority list.
19002                  * Set up the rr_bmask with all of the avaiable fcf bits
19003                  * at that level and continue the selection process.
19004                  */
19005                 if (lpfc_check_next_fcf_pri_level(phba))
19006                         goto initial_priority;
19007                 lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
19008                                 "2844 No roundrobin failover FCF available\n");
19009
19010                 return LPFC_FCOE_FCF_NEXT_NONE;
19011         }
19012
19013         if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
19014                 phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
19015                 LPFC_FCF_FLOGI_FAILED) {
19016                 if (list_is_singular(&phba->fcf.fcf_pri_list))
19017                         return LPFC_FCOE_FCF_NEXT_NONE;
19018
19019                 goto next_priority;
19020         }
19021
19022         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19023                         "2845 Get next roundrobin failover FCF (x%x)\n",
19024                         next_fcf_index);
19025
19026         return next_fcf_index;
19027 }
19028
19029 /**
19030  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
19031  * @phba: pointer to lpfc hba data structure.
19032  *
19033  * This routine sets the FCF record index in to the eligible bmask for
19034  * roundrobin failover search. It checks to make sure that the index
19035  * does not go beyond the range of the driver allocated bmask dimension
19036  * before setting the bit.
19037  *
19038  * Returns 0 if the index bit successfully set, otherwise, it returns
19039  * -EINVAL.
19040  **/
19041 int
19042 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
19043 {
19044         if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19045                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19046                                 "2610 FCF (x%x) reached driver's book "
19047                                 "keeping dimension:x%x\n",
19048                                 fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
19049                 return -EINVAL;
19050         }
19051         /* Set the eligible FCF record index bmask */
19052         set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
19053
19054         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19055                         "2790 Set FCF (x%x) to roundrobin FCF failover "
19056                         "bmask\n", fcf_index);
19057
19058         return 0;
19059 }
19060
19061 /**
19062  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
19063  * @phba: pointer to lpfc hba data structure.
19064  *
19065  * This routine clears the FCF record index from the eligible bmask for
19066  * roundrobin failover search. It checks to make sure that the index
19067  * does not go beyond the range of the driver allocated bmask dimension
19068  * before clearing the bit.
19069  **/
19070 void
19071 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
19072 {
19073         struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
19074         if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
19075                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19076                                 "2762 FCF (x%x) reached driver's book "
19077                                 "keeping dimension:x%x\n",
19078                                 fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
19079                 return;
19080         }
19081         /* Clear the eligible FCF record index bmask */
19082         spin_lock_irq(&phba->hbalock);
19083         list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
19084                                  list) {
19085                 if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
19086                         list_del_init(&fcf_pri->list);
19087                         break;
19088                 }
19089         }
19090         spin_unlock_irq(&phba->hbalock);
19091         clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
19092
19093         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19094                         "2791 Clear FCF (x%x) from roundrobin failover "
19095                         "bmask\n", fcf_index);
19096 }
19097
19098 /**
19099  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
19100  * @phba: pointer to lpfc hba data structure.
19101  *
19102  * This routine is the completion routine for the rediscover FCF table mailbox
19103  * command. If the mailbox command returned failure, it will try to stop the
19104  * FCF rediscover wait timer.
19105  **/
19106 static void
19107 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
19108 {
19109         struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
19110         uint32_t shdr_status, shdr_add_status;
19111
19112         redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
19113
19114         shdr_status = bf_get(lpfc_mbox_hdr_status,
19115                              &redisc_fcf->header.cfg_shdr.response);
19116         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
19117                              &redisc_fcf->header.cfg_shdr.response);
19118         if (shdr_status || shdr_add_status) {
19119                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
19120                                 "2746 Requesting for FCF rediscovery failed "
19121                                 "status x%x add_status x%x\n",
19122                                 shdr_status, shdr_add_status);
19123                 if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
19124                         spin_lock_irq(&phba->hbalock);
19125                         phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
19126                         spin_unlock_irq(&phba->hbalock);
19127                         /*
19128                          * CVL event triggered FCF rediscover request failed,
19129                          * last resort to re-try current registered FCF entry.
19130                          */
19131                         lpfc_retry_pport_discovery(phba);
19132                 } else {
19133                         spin_lock_irq(&phba->hbalock);
19134                         phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
19135                         spin_unlock_irq(&phba->hbalock);
19136                         /*
19137                          * DEAD FCF event triggered FCF rediscover request
19138                          * failed, last resort to fail over as a link down
19139                          * to FCF registration.
19140                          */
19141                         lpfc_sli4_fcf_dead_failthrough(phba);
19142                 }
19143         } else {
19144                 lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
19145                                 "2775 Start FCF rediscover quiescent timer\n");
19146                 /*
19147                  * Start FCF rediscovery wait timer for pending FCF
19148                  * before rescan FCF record table.
19149                  */
19150                 lpfc_fcf_redisc_wait_start_timer(phba);
19151         }
19152
19153         mempool_free(mbox, phba->mbox_mem_pool);
19154 }
19155
19156 /**
19157  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
19158  * @phba: pointer to lpfc hba data structure.
19159  *
19160  * This routine is invoked to request for rediscovery of the entire FCF table
19161  * by the port.
19162  **/
19163 int
19164 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
19165 {
19166         LPFC_MBOXQ_t *mbox;
19167         struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
19168         int rc, length;
19169
19170         /* Cancel retry delay timers to all vports before FCF rediscover */
19171         lpfc_cancel_all_vport_retry_delay_timer(phba);
19172
19173         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19174         if (!mbox) {
19175                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
19176                                 "2745 Failed to allocate mbox for "
19177                                 "requesting FCF rediscover.\n");
19178                 return -ENOMEM;
19179         }
19180
19181         length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
19182                   sizeof(struct lpfc_sli4_cfg_mhdr));
19183         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
19184                          LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
19185                          length, LPFC_SLI4_MBX_EMBED);
19186
19187         redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
19188         /* Set count to 0 for invalidating the entire FCF database */
19189         bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
19190
19191         /* Issue the mailbox command asynchronously */
19192         mbox->vport = phba->pport;
19193         mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
19194         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
19195
19196         if (rc == MBX_NOT_FINISHED) {
19197                 mempool_free(mbox, phba->mbox_mem_pool);
19198                 return -EIO;
19199         }
19200         return 0;
19201 }
19202
19203 /**
19204  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
19205  * @phba: pointer to lpfc hba data structure.
19206  *
19207  * This function is the failover routine as a last resort to the FCF DEAD
19208  * event when driver failed to perform fast FCF failover.
19209  **/
19210 void
19211 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
19212 {
19213         uint32_t link_state;
19214
19215         /*
19216          * Last resort as FCF DEAD event failover will treat this as
19217          * a link down, but save the link state because we don't want
19218          * it to be changed to Link Down unless it is already down.
19219          */
19220         link_state = phba->link_state;
19221         lpfc_linkdown(phba);
19222         phba->link_state = link_state;
19223
19224         /* Unregister FCF if no devices connected to it */
19225         lpfc_unregister_unused_fcf(phba);
19226 }
19227
19228 /**
19229  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
19230  * @phba: pointer to lpfc hba data structure.
19231  * @rgn23_data: pointer to configure region 23 data.
19232  *
19233  * This function gets SLI3 port configure region 23 data through memory dump
19234  * mailbox command. When it successfully retrieves data, the size of the data
19235  * will be returned, otherwise, 0 will be returned.
19236  **/
19237 static uint32_t
19238 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19239 {
19240         LPFC_MBOXQ_t *pmb = NULL;
19241         MAILBOX_t *mb;
19242         uint32_t offset = 0;
19243         int rc;
19244
19245         if (!rgn23_data)
19246                 return 0;
19247
19248         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19249         if (!pmb) {
19250                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19251                                 "2600 failed to allocate mailbox memory\n");
19252                 return 0;
19253         }
19254         mb = &pmb->u.mb;
19255
19256         do {
19257                 lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
19258                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
19259
19260                 if (rc != MBX_SUCCESS) {
19261                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19262                                         "2601 failed to read config "
19263                                         "region 23, rc 0x%x Status 0x%x\n",
19264                                         rc, mb->mbxStatus);
19265                         mb->un.varDmp.word_cnt = 0;
19266                 }
19267                 /*
19268                  * dump mem may return a zero when finished or we got a
19269                  * mailbox error, either way we are done.
19270                  */
19271                 if (mb->un.varDmp.word_cnt == 0)
19272                         break;
19273                 if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
19274                         mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
19275
19276                 lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
19277                                        rgn23_data + offset,
19278                                        mb->un.varDmp.word_cnt);
19279                 offset += mb->un.varDmp.word_cnt;
19280         } while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
19281
19282         mempool_free(pmb, phba->mbox_mem_pool);
19283         return offset;
19284 }
19285
19286 /**
19287  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
19288  * @phba: pointer to lpfc hba data structure.
19289  * @rgn23_data: pointer to configure region 23 data.
19290  *
19291  * This function gets SLI4 port configure region 23 data through memory dump
19292  * mailbox command. When it successfully retrieves data, the size of the data
19293  * will be returned, otherwise, 0 will be returned.
19294  **/
19295 static uint32_t
19296 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
19297 {
19298         LPFC_MBOXQ_t *mboxq = NULL;
19299         struct lpfc_dmabuf *mp = NULL;
19300         struct lpfc_mqe *mqe;
19301         uint32_t data_length = 0;
19302         int rc;
19303
19304         if (!rgn23_data)
19305                 return 0;
19306
19307         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19308         if (!mboxq) {
19309                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19310                                 "3105 failed to allocate mailbox memory\n");
19311                 return 0;
19312         }
19313
19314         if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
19315                 goto out;
19316         mqe = &mboxq->u.mqe;
19317         mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
19318         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19319         if (rc)
19320                 goto out;
19321         data_length = mqe->un.mb_words[5];
19322         if (data_length == 0)
19323                 goto out;
19324         if (data_length > DMP_RGN23_SIZE) {
19325                 data_length = 0;
19326                 goto out;
19327         }
19328         lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
19329 out:
19330         mempool_free(mboxq, phba->mbox_mem_pool);
19331         if (mp) {
19332                 lpfc_mbuf_free(phba, mp->virt, mp->phys);
19333                 kfree(mp);
19334         }
19335         return data_length;
19336 }
19337
19338 /**
19339  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
19340  * @phba: pointer to lpfc hba data structure.
19341  *
19342  * This function read region 23 and parse TLV for port status to
19343  * decide if the user disaled the port. If the TLV indicates the
19344  * port is disabled, the hba_flag is set accordingly.
19345  **/
19346 void
19347 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
19348 {
19349         uint8_t *rgn23_data = NULL;
19350         uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
19351         uint32_t offset = 0;
19352
19353         /* Get adapter Region 23 data */
19354         rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
19355         if (!rgn23_data)
19356                 goto out;
19357
19358         if (phba->sli_rev < LPFC_SLI_REV4)
19359                 data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
19360         else {
19361                 if_type = bf_get(lpfc_sli_intf_if_type,
19362                                  &phba->sli4_hba.sli_intf);
19363                 if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
19364                         goto out;
19365                 data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
19366         }
19367
19368         if (!data_size)
19369                 goto out;
19370
19371         /* Check the region signature first */
19372         if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
19373                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19374                         "2619 Config region 23 has bad signature\n");
19375                         goto out;
19376         }
19377         offset += 4;
19378
19379         /* Check the data structure version */
19380         if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
19381                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19382                         "2620 Config region 23 has bad version\n");
19383                 goto out;
19384         }
19385         offset += 4;
19386
19387         /* Parse TLV entries in the region */
19388         while (offset < data_size) {
19389                 if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
19390                         break;
19391                 /*
19392                  * If the TLV is not driver specific TLV or driver id is
19393                  * not linux driver id, skip the record.
19394                  */
19395                 if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
19396                     (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
19397                     (rgn23_data[offset + 3] != 0)) {
19398                         offset += rgn23_data[offset + 1] * 4 + 4;
19399                         continue;
19400                 }
19401
19402                 /* Driver found a driver specific TLV in the config region */
19403                 sub_tlv_len = rgn23_data[offset + 1] * 4;
19404                 offset += 4;
19405                 tlv_offset = 0;
19406
19407                 /*
19408                  * Search for configured port state sub-TLV.
19409                  */
19410                 while ((offset < data_size) &&
19411                         (tlv_offset < sub_tlv_len)) {
19412                         if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
19413                                 offset += 4;
19414                                 tlv_offset += 4;
19415                                 break;
19416                         }
19417                         if (rgn23_data[offset] != PORT_STE_TYPE) {
19418                                 offset += rgn23_data[offset + 1] * 4 + 4;
19419                                 tlv_offset += rgn23_data[offset + 1] * 4 + 4;
19420                                 continue;
19421                         }
19422
19423                         /* This HBA contains PORT_STE configured */
19424                         if (!rgn23_data[offset + 2])
19425                                 phba->hba_flag |= LINK_DISABLED;
19426
19427                         goto out;
19428                 }
19429         }
19430
19431 out:
19432         kfree(rgn23_data);
19433         return;
19434 }
19435
19436 /**
19437  * lpfc_wr_object - write an object to the firmware
19438  * @phba: HBA structure that indicates port to create a queue on.
19439  * @dmabuf_list: list of dmabufs to write to the port.
19440  * @size: the total byte value of the objects to write to the port.
19441  * @offset: the current offset to be used to start the transfer.
19442  *
19443  * This routine will create a wr_object mailbox command to send to the port.
19444  * the mailbox command will be constructed using the dma buffers described in
19445  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
19446  * BDEs that the imbedded mailbox can support. The @offset variable will be
19447  * used to indicate the starting offset of the transfer and will also return
19448  * the offset after the write object mailbox has completed. @size is used to
19449  * determine the end of the object and whether the eof bit should be set.
19450  *
19451  * Return 0 is successful and offset will contain the the new offset to use
19452  * for the next write.
19453  * Return negative value for error cases.
19454  **/
19455 int
19456 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
19457                uint32_t size, uint32_t *offset)
19458 {
19459         struct lpfc_mbx_wr_object *wr_object;
19460         LPFC_MBOXQ_t *mbox;
19461         int rc = 0, i = 0;
19462         uint32_t shdr_status, shdr_add_status, shdr_change_status, shdr_csf;
19463         uint32_t mbox_tmo;
19464         struct lpfc_dmabuf *dmabuf;
19465         uint32_t written = 0;
19466         bool check_change_status = false;
19467
19468         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19469         if (!mbox)
19470                 return -ENOMEM;
19471
19472         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
19473                         LPFC_MBOX_OPCODE_WRITE_OBJECT,
19474                         sizeof(struct lpfc_mbx_wr_object) -
19475                         sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
19476
19477         wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
19478         wr_object->u.request.write_offset = *offset;
19479         sprintf((uint8_t *)wr_object->u.request.object_name, "/");
19480         wr_object->u.request.object_name[0] =
19481                 cpu_to_le32(wr_object->u.request.object_name[0]);
19482         bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
19483         list_for_each_entry(dmabuf, dmabuf_list, list) {
19484                 if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
19485                         break;
19486                 wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
19487                 wr_object->u.request.bde[i].addrHigh =
19488                         putPaddrHigh(dmabuf->phys);
19489                 if (written + SLI4_PAGE_SIZE >= size) {
19490                         wr_object->u.request.bde[i].tus.f.bdeSize =
19491                                 (size - written);
19492                         written += (size - written);
19493                         bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
19494                         bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
19495                         check_change_status = true;
19496                 } else {
19497                         wr_object->u.request.bde[i].tus.f.bdeSize =
19498                                 SLI4_PAGE_SIZE;
19499                         written += SLI4_PAGE_SIZE;
19500                 }
19501                 i++;
19502         }
19503         wr_object->u.request.bde_count = i;
19504         bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
19505         if (!phba->sli4_hba.intr_enable)
19506                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
19507         else {
19508                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
19509                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
19510         }
19511         /* The IOCTL status is embedded in the mailbox subheader. */
19512         shdr_status = bf_get(lpfc_mbox_hdr_status,
19513                              &wr_object->header.cfg_shdr.response);
19514         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
19515                                  &wr_object->header.cfg_shdr.response);
19516         if (check_change_status) {
19517                 shdr_change_status = bf_get(lpfc_wr_object_change_status,
19518                                             &wr_object->u.response);
19519
19520                 if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
19521                     shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
19522                         shdr_csf = bf_get(lpfc_wr_object_csf,
19523                                           &wr_object->u.response);
19524                         if (shdr_csf)
19525                                 shdr_change_status =
19526                                                    LPFC_CHANGE_STATUS_PCI_RESET;
19527                 }
19528
19529                 switch (shdr_change_status) {
19530                 case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
19531                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19532                                         "3198 Firmware write complete: System "
19533                                         "reboot required to instantiate\n");
19534                         break;
19535                 case (LPFC_CHANGE_STATUS_FW_RESET):
19536                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19537                                         "3199 Firmware write complete: Firmware"
19538                                         " reset required to instantiate\n");
19539                         break;
19540                 case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
19541                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19542                                         "3200 Firmware write complete: Port "
19543                                         "Migration or PCI Reset required to "
19544                                         "instantiate\n");
19545                         break;
19546                 case (LPFC_CHANGE_STATUS_PCI_RESET):
19547                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
19548                                         "3201 Firmware write complete: PCI "
19549                                         "Reset required to instantiate\n");
19550                         break;
19551                 default:
19552                         break;
19553                 }
19554         }
19555         if (rc != MBX_TIMEOUT)
19556                 mempool_free(mbox, phba->mbox_mem_pool);
19557         if (shdr_status || shdr_add_status || rc) {
19558                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
19559                                 "3025 Write Object mailbox failed with "
19560                                 "status x%x add_status x%x, mbx status x%x\n",
19561                                 shdr_status, shdr_add_status, rc);
19562                 rc = -ENXIO;
19563                 *offset = shdr_add_status;
19564         } else
19565                 *offset += wr_object->u.response.actual_write_length;
19566         return rc;
19567 }
19568
19569 /**
19570  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
19571  * @vport: pointer to vport data structure.
19572  *
19573  * This function iterate through the mailboxq and clean up all REG_LOGIN
19574  * and REG_VPI mailbox commands associated with the vport. This function
19575  * is called when driver want to restart discovery of the vport due to
19576  * a Clear Virtual Link event.
19577  **/
19578 void
19579 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
19580 {
19581         struct lpfc_hba *phba = vport->phba;
19582         LPFC_MBOXQ_t *mb, *nextmb;
19583         struct lpfc_dmabuf *mp;
19584         struct lpfc_nodelist *ndlp;
19585         struct lpfc_nodelist *act_mbx_ndlp = NULL;
19586         struct Scsi_Host  *shost = lpfc_shost_from_vport(vport);
19587         LIST_HEAD(mbox_cmd_list);
19588         uint8_t restart_loop;
19589
19590         /* Clean up internally queued mailbox commands with the vport */
19591         spin_lock_irq(&phba->hbalock);
19592         list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
19593                 if (mb->vport != vport)
19594                         continue;
19595
19596                 if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
19597                         (mb->u.mb.mbxCommand != MBX_REG_VPI))
19598                         continue;
19599
19600                 list_del(&mb->list);
19601                 list_add_tail(&mb->list, &mbox_cmd_list);
19602         }
19603         /* Clean up active mailbox command with the vport */
19604         mb = phba->sli.mbox_active;
19605         if (mb && (mb->vport == vport)) {
19606                 if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
19607                         (mb->u.mb.mbxCommand == MBX_REG_VPI))
19608                         mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19609                 if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19610                         act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19611                         /* Put reference count for delayed processing */
19612                         act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
19613                         /* Unregister the RPI when mailbox complete */
19614                         mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
19615                 }
19616         }
19617         /* Cleanup any mailbox completions which are not yet processed */
19618         do {
19619                 restart_loop = 0;
19620                 list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
19621                         /*
19622                          * If this mailox is already processed or it is
19623                          * for another vport ignore it.
19624                          */
19625                         if ((mb->vport != vport) ||
19626                                 (mb->mbox_flag & LPFC_MBX_IMED_UNREG))
19627                                 continue;
19628
19629                         if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
19630                                 (mb->u.mb.mbxCommand != MBX_REG_VPI))
19631                                 continue;
19632
19633                         mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19634                         if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19635                                 ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19636                                 /* Unregister the RPI when mailbox complete */
19637                                 mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
19638                                 restart_loop = 1;
19639                                 spin_unlock_irq(&phba->hbalock);
19640                                 spin_lock(shost->host_lock);
19641                                 ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19642                                 spin_unlock(shost->host_lock);
19643                                 spin_lock_irq(&phba->hbalock);
19644                                 break;
19645                         }
19646                 }
19647         } while (restart_loop);
19648
19649         spin_unlock_irq(&phba->hbalock);
19650
19651         /* Release the cleaned-up mailbox commands */
19652         while (!list_empty(&mbox_cmd_list)) {
19653                 list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
19654                 if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
19655                         mp = (struct lpfc_dmabuf *)(mb->ctx_buf);
19656                         if (mp) {
19657                                 __lpfc_mbuf_free(phba, mp->virt, mp->phys);
19658                                 kfree(mp);
19659                         }
19660                         mb->ctx_buf = NULL;
19661                         ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
19662                         mb->ctx_ndlp = NULL;
19663                         if (ndlp) {
19664                                 spin_lock(shost->host_lock);
19665                                 ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19666                                 spin_unlock(shost->host_lock);
19667                                 lpfc_nlp_put(ndlp);
19668                         }
19669                 }
19670                 mempool_free(mb, phba->mbox_mem_pool);
19671         }
19672
19673         /* Release the ndlp with the cleaned-up active mailbox command */
19674         if (act_mbx_ndlp) {
19675                 spin_lock(shost->host_lock);
19676                 act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
19677                 spin_unlock(shost->host_lock);
19678                 lpfc_nlp_put(act_mbx_ndlp);
19679         }
19680 }
19681
19682 /**
19683  * lpfc_drain_txq - Drain the txq
19684  * @phba: Pointer to HBA context object.
19685  *
19686  * This function attempt to submit IOCBs on the txq
19687  * to the adapter.  For SLI4 adapters, the txq contains
19688  * ELS IOCBs that have been deferred because the there
19689  * are no SGLs.  This congestion can occur with large
19690  * vport counts during node discovery.
19691  **/
19692
19693 uint32_t
19694 lpfc_drain_txq(struct lpfc_hba *phba)
19695 {
19696         LIST_HEAD(completions);
19697         struct lpfc_sli_ring *pring;
19698         struct lpfc_iocbq *piocbq = NULL;
19699         unsigned long iflags = 0;
19700         char *fail_msg = NULL;
19701         struct lpfc_sglq *sglq;
19702         union lpfc_wqe128 wqe;
19703         uint32_t txq_cnt = 0;
19704         struct lpfc_queue *wq;
19705
19706         if (phba->link_flag & LS_MDS_LOOPBACK) {
19707                 /* MDS WQE are posted only to first WQ*/
19708                 wq = phba->sli4_hba.hdwq[0].io_wq;
19709                 if (unlikely(!wq))
19710                         return 0;
19711                 pring = wq->pring;
19712         } else {
19713                 wq = phba->sli4_hba.els_wq;
19714                 if (unlikely(!wq))
19715                         return 0;
19716                 pring = lpfc_phba_elsring(phba);
19717         }
19718
19719         if (unlikely(!pring) || list_empty(&pring->txq))
19720                 return 0;
19721
19722         spin_lock_irqsave(&pring->ring_lock, iflags);
19723         list_for_each_entry(piocbq, &pring->txq, list) {
19724                 txq_cnt++;
19725         }
19726
19727         if (txq_cnt > pring->txq_max)
19728                 pring->txq_max = txq_cnt;
19729
19730         spin_unlock_irqrestore(&pring->ring_lock, iflags);
19731
19732         while (!list_empty(&pring->txq)) {
19733                 spin_lock_irqsave(&pring->ring_lock, iflags);
19734
19735                 piocbq = lpfc_sli_ringtx_get(phba, pring);
19736                 if (!piocbq) {
19737                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
19738                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
19739                                 "2823 txq empty and txq_cnt is %d\n ",
19740                                 txq_cnt);
19741                         break;
19742                 }
19743                 sglq = __lpfc_sli_get_els_sglq(phba, piocbq);
19744                 if (!sglq) {
19745                         __lpfc_sli_ringtx_put(phba, pring, piocbq);
19746                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
19747                         break;
19748                 }
19749                 txq_cnt--;
19750
19751                 /* The xri and iocb resources secured,
19752                  * attempt to issue request
19753                  */
19754                 piocbq->sli4_lxritag = sglq->sli4_lxritag;
19755                 piocbq->sli4_xritag = sglq->sli4_xritag;
19756                 if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
19757                         fail_msg = "to convert bpl to sgl";
19758                 else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
19759                         fail_msg = "to convert iocb to wqe";
19760                 else if (lpfc_sli4_wq_put(wq, &wqe))
19761                         fail_msg = " - Wq is full";
19762                 else
19763                         lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
19764
19765                 if (fail_msg) {
19766                         /* Failed means we can't issue and need to cancel */
19767                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
19768                                         "2822 IOCB failed %s iotag 0x%x "
19769                                         "xri 0x%x\n",
19770                                         fail_msg,
19771                                         piocbq->iotag, piocbq->sli4_xritag);
19772                         list_add_tail(&piocbq->list, &completions);
19773                 }
19774                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
19775         }
19776
19777         /* Cancel all the IOCBs that cannot be issued */
19778         lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
19779                                 IOERR_SLI_ABORTED);
19780
19781         return txq_cnt;
19782 }
19783
19784 /**
19785  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
19786  * @phba: Pointer to HBA context object.
19787  * @pwqe: Pointer to command WQE.
19788  * @sglq: Pointer to the scatter gather queue object.
19789  *
19790  * This routine converts the bpl or bde that is in the WQE
19791  * to a sgl list for the sli4 hardware. The physical address
19792  * of the bpl/bde is converted back to a virtual address.
19793  * If the WQE contains a BPL then the list of BDE's is
19794  * converted to sli4_sge's. If the WQE contains a single
19795  * BDE then it is converted to a single sli_sge.
19796  * The WQE is still in cpu endianness so the contents of
19797  * the bpl can be used without byte swapping.
19798  *
19799  * Returns valid XRI = Success, NO_XRI = Failure.
19800  */
19801 static uint16_t
19802 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
19803                  struct lpfc_sglq *sglq)
19804 {
19805         uint16_t xritag = NO_XRI;
19806         struct ulp_bde64 *bpl = NULL;
19807         struct ulp_bde64 bde;
19808         struct sli4_sge *sgl  = NULL;
19809         struct lpfc_dmabuf *dmabuf;
19810         union lpfc_wqe128 *wqe;
19811         int numBdes = 0;
19812         int i = 0;
19813         uint32_t offset = 0; /* accumulated offset in the sg request list */
19814         int inbound = 0; /* number of sg reply entries inbound from firmware */
19815         uint32_t cmd;
19816
19817         if (!pwqeq || !sglq)
19818                 return xritag;
19819
19820         sgl  = (struct sli4_sge *)sglq->sgl;
19821         wqe = &pwqeq->wqe;
19822         pwqeq->iocb.ulpIoTag = pwqeq->iotag;
19823
19824         cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
19825         if (cmd == CMD_XMIT_BLS_RSP64_WQE)
19826                 return sglq->sli4_xritag;
19827         numBdes = pwqeq->rsvd2;
19828         if (numBdes) {
19829                 /* The addrHigh and addrLow fields within the WQE
19830                  * have not been byteswapped yet so there is no
19831                  * need to swap them back.
19832                  */
19833                 if (pwqeq->context3)
19834                         dmabuf = (struct lpfc_dmabuf *)pwqeq->context3;
19835                 else
19836                         return xritag;
19837
19838                 bpl  = (struct ulp_bde64 *)dmabuf->virt;
19839                 if (!bpl)
19840                         return xritag;
19841
19842                 for (i = 0; i < numBdes; i++) {
19843                         /* Should already be byte swapped. */
19844                         sgl->addr_hi = bpl->addrHigh;
19845                         sgl->addr_lo = bpl->addrLow;
19846
19847                         sgl->word2 = le32_to_cpu(sgl->word2);
19848                         if ((i+1) == numBdes)
19849                                 bf_set(lpfc_sli4_sge_last, sgl, 1);
19850                         else
19851                                 bf_set(lpfc_sli4_sge_last, sgl, 0);
19852                         /* swap the size field back to the cpu so we
19853                          * can assign it to the sgl.
19854                          */
19855                         bde.tus.w = le32_to_cpu(bpl->tus.w);
19856                         sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
19857                         /* The offsets in the sgl need to be accumulated
19858                          * separately for the request and reply lists.
19859                          * The request is always first, the reply follows.
19860                          */
19861                         switch (cmd) {
19862                         case CMD_GEN_REQUEST64_WQE:
19863                                 /* add up the reply sg entries */
19864                                 if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
19865                                         inbound++;
19866                                 /* first inbound? reset the offset */
19867                                 if (inbound == 1)
19868                                         offset = 0;
19869                                 bf_set(lpfc_sli4_sge_offset, sgl, offset);
19870                                 bf_set(lpfc_sli4_sge_type, sgl,
19871                                         LPFC_SGE_TYPE_DATA);
19872                                 offset += bde.tus.f.bdeSize;
19873                                 break;
19874                         case CMD_FCP_TRSP64_WQE:
19875                                 bf_set(lpfc_sli4_sge_offset, sgl, 0);
19876                                 bf_set(lpfc_sli4_sge_type, sgl,
19877                                         LPFC_SGE_TYPE_DATA);
19878                                 break;
19879                         case CMD_FCP_TSEND64_WQE:
19880                         case CMD_FCP_TRECEIVE64_WQE:
19881                                 bf_set(lpfc_sli4_sge_type, sgl,
19882                                         bpl->tus.f.bdeFlags);
19883                                 if (i < 3)
19884                                         offset = 0;
19885                                 else
19886                                         offset += bde.tus.f.bdeSize;
19887                                 bf_set(lpfc_sli4_sge_offset, sgl, offset);
19888                                 break;
19889                         }
19890                         sgl->word2 = cpu_to_le32(sgl->word2);
19891                         bpl++;
19892                         sgl++;
19893                 }
19894         } else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
19895                 /* The addrHigh and addrLow fields of the BDE have not
19896                  * been byteswapped yet so they need to be swapped
19897                  * before putting them in the sgl.
19898                  */
19899                 sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
19900                 sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
19901                 sgl->word2 = le32_to_cpu(sgl->word2);
19902                 bf_set(lpfc_sli4_sge_last, sgl, 1);
19903                 sgl->word2 = cpu_to_le32(sgl->word2);
19904                 sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
19905         }
19906         return sglq->sli4_xritag;
19907 }
19908
19909 /**
19910  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
19911  * @phba: Pointer to HBA context object.
19912  * @ring_number: Base sli ring number
19913  * @pwqe: Pointer to command WQE.
19914  **/
19915 int
19916 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
19917                     struct lpfc_iocbq *pwqe)
19918 {
19919         union lpfc_wqe128 *wqe = &pwqe->wqe;
19920         struct lpfc_nvmet_rcv_ctx *ctxp;
19921         struct lpfc_queue *wq;
19922         struct lpfc_sglq *sglq;
19923         struct lpfc_sli_ring *pring;
19924         unsigned long iflags;
19925         uint32_t ret = 0;
19926
19927         /* NVME_LS and NVME_LS ABTS requests. */
19928         if (pwqe->iocb_flag & LPFC_IO_NVME_LS) {
19929                 pring =  phba->sli4_hba.nvmels_wq->pring;
19930                 lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
19931                                           qp, wq_access);
19932                 sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
19933                 if (!sglq) {
19934                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
19935                         return WQE_BUSY;
19936                 }
19937                 pwqe->sli4_lxritag = sglq->sli4_lxritag;
19938                 pwqe->sli4_xritag = sglq->sli4_xritag;
19939                 if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
19940                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
19941                         return WQE_ERROR;
19942                 }
19943                 bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
19944                        pwqe->sli4_xritag);
19945                 ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
19946                 if (ret) {
19947                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
19948                         return ret;
19949                 }
19950
19951                 lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
19952                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
19953
19954                 lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
19955                 return 0;
19956         }
19957
19958         /* NVME_FCREQ and NVME_ABTS requests */
19959         if (pwqe->iocb_flag & LPFC_IO_NVME) {
19960                 /* Get the IO distribution (hba_wqidx) for WQ assignment. */
19961                 wq = qp->io_wq;
19962                 pring = wq->pring;
19963
19964                 bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
19965
19966                 lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
19967                                           qp, wq_access);
19968                 ret = lpfc_sli4_wq_put(wq, wqe);
19969                 if (ret) {
19970                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
19971                         return ret;
19972                 }
19973                 lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
19974                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
19975
19976                 lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
19977                 return 0;
19978         }
19979
19980         /* NVMET requests */
19981         if (pwqe->iocb_flag & LPFC_IO_NVMET) {
19982                 /* Get the IO distribution (hba_wqidx) for WQ assignment. */
19983                 wq = qp->io_wq;
19984                 pring = wq->pring;
19985
19986                 ctxp = pwqe->context2;
19987                 sglq = ctxp->ctxbuf->sglq;
19988                 if (pwqe->sli4_xritag ==  NO_XRI) {
19989                         pwqe->sli4_lxritag = sglq->sli4_lxritag;
19990                         pwqe->sli4_xritag = sglq->sli4_xritag;
19991                 }
19992                 bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
19993                        pwqe->sli4_xritag);
19994                 bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
19995
19996                 lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
19997                                           qp, wq_access);
19998                 ret = lpfc_sli4_wq_put(wq, wqe);
19999                 if (ret) {
20000                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
20001                         return ret;
20002                 }
20003                 lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
20004                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
20005
20006                 lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
20007                 return 0;
20008         }
20009         return WQE_ERROR;
20010 }
20011
20012 #ifdef LPFC_MXP_STAT
20013 /**
20014  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
20015  * @phba: pointer to lpfc hba data structure.
20016  * @hwqid: belong to which HWQ.
20017  *
20018  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
20019  * 15 seconds after a test case is running.
20020  *
20021  * The user should call lpfc_debugfs_multixripools_write before running a test
20022  * case to clear stat_snapshot_taken. Then the user starts a test case. During
20023  * test case is running, stat_snapshot_taken is incremented by 1 every time when
20024  * this routine is called from heartbeat timer. When stat_snapshot_taken is
20025  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
20026  **/
20027 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
20028 {
20029         struct lpfc_sli4_hdw_queue *qp;
20030         struct lpfc_multixri_pool *multixri_pool;
20031         struct lpfc_pvt_pool *pvt_pool;
20032         struct lpfc_pbl_pool *pbl_pool;
20033         u32 txcmplq_cnt;
20034
20035         qp = &phba->sli4_hba.hdwq[hwqid];
20036         multixri_pool = qp->p_multixri_pool;
20037         if (!multixri_pool)
20038                 return;
20039
20040         if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
20041                 pvt_pool = &qp->p_multixri_pool->pvt_pool;
20042                 pbl_pool = &qp->p_multixri_pool->pbl_pool;
20043                 txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20044
20045                 multixri_pool->stat_pbl_count = pbl_pool->count;
20046                 multixri_pool->stat_pvt_count = pvt_pool->count;
20047                 multixri_pool->stat_busy_count = txcmplq_cnt;
20048         }
20049
20050         multixri_pool->stat_snapshot_taken++;
20051 }
20052 #endif
20053
20054 /**
20055  * lpfc_adjust_pvt_pool_count - Adjust private pool count
20056  * @phba: pointer to lpfc hba data structure.
20057  * @hwqid: belong to which HWQ.
20058  *
20059  * This routine moves some XRIs from private to public pool when private pool
20060  * is not busy.
20061  **/
20062 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
20063 {
20064         struct lpfc_multixri_pool *multixri_pool;
20065         u32 io_req_count;
20066         u32 prev_io_req_count;
20067
20068         multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
20069         if (!multixri_pool)
20070                 return;
20071         io_req_count = multixri_pool->io_req_count;
20072         prev_io_req_count = multixri_pool->prev_io_req_count;
20073
20074         if (prev_io_req_count != io_req_count) {
20075                 /* Private pool is busy */
20076                 multixri_pool->prev_io_req_count = io_req_count;
20077         } else {
20078                 /* Private pool is not busy.
20079                  * Move XRIs from private to public pool.
20080                  */
20081                 lpfc_move_xri_pvt_to_pbl(phba, hwqid);
20082         }
20083 }
20084
20085 /**
20086  * lpfc_adjust_high_watermark - Adjust high watermark
20087  * @phba: pointer to lpfc hba data structure.
20088  * @hwqid: belong to which HWQ.
20089  *
20090  * This routine sets high watermark as number of outstanding XRIs,
20091  * but make sure the new value is between xri_limit/2 and xri_limit.
20092  **/
20093 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
20094 {
20095         u32 new_watermark;
20096         u32 watermark_max;
20097         u32 watermark_min;
20098         u32 xri_limit;
20099         u32 txcmplq_cnt;
20100         u32 abts_io_bufs;
20101         struct lpfc_multixri_pool *multixri_pool;
20102         struct lpfc_sli4_hdw_queue *qp;
20103
20104         qp = &phba->sli4_hba.hdwq[hwqid];
20105         multixri_pool = qp->p_multixri_pool;
20106         if (!multixri_pool)
20107                 return;
20108         xri_limit = multixri_pool->xri_limit;
20109
20110         watermark_max = xri_limit;
20111         watermark_min = xri_limit / 2;
20112
20113         txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20114         abts_io_bufs = qp->abts_scsi_io_bufs;
20115         abts_io_bufs += qp->abts_nvme_io_bufs;
20116
20117         new_watermark = txcmplq_cnt + abts_io_bufs;
20118         new_watermark = min(watermark_max, new_watermark);
20119         new_watermark = max(watermark_min, new_watermark);
20120         multixri_pool->pvt_pool.high_watermark = new_watermark;
20121
20122 #ifdef LPFC_MXP_STAT
20123         multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
20124                                           new_watermark);
20125 #endif
20126 }
20127
20128 /**
20129  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
20130  * @phba: pointer to lpfc hba data structure.
20131  * @hwqid: belong to which HWQ.
20132  *
20133  * This routine is called from hearbeat timer when pvt_pool is idle.
20134  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
20135  * The first step moves (all - low_watermark) amount of XRIs.
20136  * The second step moves the rest of XRIs.
20137  **/
20138 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
20139 {
20140         struct lpfc_pbl_pool *pbl_pool;
20141         struct lpfc_pvt_pool *pvt_pool;
20142         struct lpfc_sli4_hdw_queue *qp;
20143         struct lpfc_io_buf *lpfc_ncmd;
20144         struct lpfc_io_buf *lpfc_ncmd_next;
20145         unsigned long iflag;
20146         struct list_head tmp_list;
20147         u32 tmp_count;
20148
20149         qp = &phba->sli4_hba.hdwq[hwqid];
20150         pbl_pool = &qp->p_multixri_pool->pbl_pool;
20151         pvt_pool = &qp->p_multixri_pool->pvt_pool;
20152         tmp_count = 0;
20153
20154         lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
20155         lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
20156
20157         if (pvt_pool->count > pvt_pool->low_watermark) {
20158                 /* Step 1: move (all - low_watermark) from pvt_pool
20159                  * to pbl_pool
20160                  */
20161
20162                 /* Move low watermark of bufs from pvt_pool to tmp_list */
20163                 INIT_LIST_HEAD(&tmp_list);
20164                 list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20165                                          &pvt_pool->list, list) {
20166                         list_move_tail(&lpfc_ncmd->list, &tmp_list);
20167                         tmp_count++;
20168                         if (tmp_count >= pvt_pool->low_watermark)
20169                                 break;
20170                 }
20171
20172                 /* Move all bufs from pvt_pool to pbl_pool */
20173                 list_splice_init(&pvt_pool->list, &pbl_pool->list);
20174
20175                 /* Move all bufs from tmp_list to pvt_pool */
20176                 list_splice(&tmp_list, &pvt_pool->list);
20177
20178                 pbl_pool->count += (pvt_pool->count - tmp_count);
20179                 pvt_pool->count = tmp_count;
20180         } else {
20181                 /* Step 2: move the rest from pvt_pool to pbl_pool */
20182                 list_splice_init(&pvt_pool->list, &pbl_pool->list);
20183                 pbl_pool->count += pvt_pool->count;
20184                 pvt_pool->count = 0;
20185         }
20186
20187         spin_unlock(&pvt_pool->lock);
20188         spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20189 }
20190
20191 /**
20192  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
20193  * @phba: pointer to lpfc hba data structure
20194  * @pbl_pool: specified public free XRI pool
20195  * @pvt_pool: specified private free XRI pool
20196  * @count: number of XRIs to move
20197  *
20198  * This routine tries to move some free common bufs from the specified pbl_pool
20199  * to the specified pvt_pool. It might move less than count XRIs if there's not
20200  * enough in public pool.
20201  *
20202  * Return:
20203  *   true - if XRIs are successfully moved from the specified pbl_pool to the
20204  *          specified pvt_pool
20205  *   false - if the specified pbl_pool is empty or locked by someone else
20206  **/
20207 static bool
20208 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
20209                           struct lpfc_pbl_pool *pbl_pool,
20210                           struct lpfc_pvt_pool *pvt_pool, u32 count)
20211 {
20212         struct lpfc_io_buf *lpfc_ncmd;
20213         struct lpfc_io_buf *lpfc_ncmd_next;
20214         unsigned long iflag;
20215         int ret;
20216
20217         ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
20218         if (ret) {
20219                 if (pbl_pool->count) {
20220                         /* Move a batch of XRIs from public to private pool */
20221                         lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
20222                         list_for_each_entry_safe(lpfc_ncmd,
20223                                                  lpfc_ncmd_next,
20224                                                  &pbl_pool->list,
20225                                                  list) {
20226                                 list_move_tail(&lpfc_ncmd->list,
20227                                                &pvt_pool->list);
20228                                 pvt_pool->count++;
20229                                 pbl_pool->count--;
20230                                 count--;
20231                                 if (count == 0)
20232                                         break;
20233                         }
20234
20235                         spin_unlock(&pvt_pool->lock);
20236                         spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20237                         return true;
20238                 }
20239                 spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20240         }
20241
20242         return false;
20243 }
20244
20245 /**
20246  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
20247  * @phba: pointer to lpfc hba data structure.
20248  * @hwqid: belong to which HWQ.
20249  * @count: number of XRIs to move
20250  *
20251  * This routine tries to find some free common bufs in one of public pools with
20252  * Round Robin method. The search always starts from local hwqid, then the next
20253  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
20254  * a batch of free common bufs are moved to private pool on hwqid.
20255  * It might move less than count XRIs if there's not enough in public pool.
20256  **/
20257 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
20258 {
20259         struct lpfc_multixri_pool *multixri_pool;
20260         struct lpfc_multixri_pool *next_multixri_pool;
20261         struct lpfc_pvt_pool *pvt_pool;
20262         struct lpfc_pbl_pool *pbl_pool;
20263         struct lpfc_sli4_hdw_queue *qp;
20264         u32 next_hwqid;
20265         u32 hwq_count;
20266         int ret;
20267
20268         qp = &phba->sli4_hba.hdwq[hwqid];
20269         multixri_pool = qp->p_multixri_pool;
20270         pvt_pool = &multixri_pool->pvt_pool;
20271         pbl_pool = &multixri_pool->pbl_pool;
20272
20273         /* Check if local pbl_pool is available */
20274         ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
20275         if (ret) {
20276 #ifdef LPFC_MXP_STAT
20277                 multixri_pool->local_pbl_hit_count++;
20278 #endif
20279                 return;
20280         }
20281
20282         hwq_count = phba->cfg_hdw_queue;
20283
20284         /* Get the next hwqid which was found last time */
20285         next_hwqid = multixri_pool->rrb_next_hwqid;
20286
20287         do {
20288                 /* Go to next hwq */
20289                 next_hwqid = (next_hwqid + 1) % hwq_count;
20290
20291                 next_multixri_pool =
20292                         phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
20293                 pbl_pool = &next_multixri_pool->pbl_pool;
20294
20295                 /* Check if the public free xri pool is available */
20296                 ret = _lpfc_move_xri_pbl_to_pvt(
20297                         phba, qp, pbl_pool, pvt_pool, count);
20298
20299                 /* Exit while-loop if success or all hwqid are checked */
20300         } while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
20301
20302         /* Starting point for the next time */
20303         multixri_pool->rrb_next_hwqid = next_hwqid;
20304
20305         if (!ret) {
20306                 /* stats: all public pools are empty*/
20307                 multixri_pool->pbl_empty_count++;
20308         }
20309
20310 #ifdef LPFC_MXP_STAT
20311         if (ret) {
20312                 if (next_hwqid == hwqid)
20313                         multixri_pool->local_pbl_hit_count++;
20314                 else
20315                         multixri_pool->other_pbl_hit_count++;
20316         }
20317 #endif
20318 }
20319
20320 /**
20321  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
20322  * @phba: pointer to lpfc hba data structure.
20323  * @qp: belong to which HWQ.
20324  *
20325  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
20326  * low watermark.
20327  **/
20328 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
20329 {
20330         struct lpfc_multixri_pool *multixri_pool;
20331         struct lpfc_pvt_pool *pvt_pool;
20332
20333         multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
20334         pvt_pool = &multixri_pool->pvt_pool;
20335
20336         if (pvt_pool->count < pvt_pool->low_watermark)
20337                 lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
20338 }
20339
20340 /**
20341  * lpfc_release_io_buf - Return one IO buf back to free pool
20342  * @phba: pointer to lpfc hba data structure.
20343  * @lpfc_ncmd: IO buf to be returned.
20344  * @qp: belong to which HWQ.
20345  *
20346  * This routine returns one IO buf back to free pool. If this is an urgent IO,
20347  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
20348  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
20349  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
20350  * lpfc_io_buf_list_put.
20351  **/
20352 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
20353                          struct lpfc_sli4_hdw_queue *qp)
20354 {
20355         unsigned long iflag;
20356         struct lpfc_pbl_pool *pbl_pool;
20357         struct lpfc_pvt_pool *pvt_pool;
20358         struct lpfc_epd_pool *epd_pool;
20359         u32 txcmplq_cnt;
20360         u32 xri_owned;
20361         u32 xri_limit;
20362         u32 abts_io_bufs;
20363
20364         /* MUST zero fields if buffer is reused by another protocol */
20365         lpfc_ncmd->nvmeCmd = NULL;
20366         lpfc_ncmd->cur_iocbq.wqe_cmpl = NULL;
20367         lpfc_ncmd->cur_iocbq.iocb_cmpl = NULL;
20368
20369         if (phba->cfg_xpsgl && !phba->nvmet_support &&
20370             !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
20371                 lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
20372
20373         if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
20374                 lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
20375
20376         if (phba->cfg_xri_rebalancing) {
20377                 if (lpfc_ncmd->expedite) {
20378                         /* Return to expedite pool */
20379                         epd_pool = &phba->epd_pool;
20380                         spin_lock_irqsave(&epd_pool->lock, iflag);
20381                         list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
20382                         epd_pool->count++;
20383                         spin_unlock_irqrestore(&epd_pool->lock, iflag);
20384                         return;
20385                 }
20386
20387                 /* Avoid invalid access if an IO sneaks in and is being rejected
20388                  * just _after_ xri pools are destroyed in lpfc_offline.
20389                  * Nothing much can be done at this point.
20390                  */
20391                 if (!qp->p_multixri_pool)
20392                         return;
20393
20394                 pbl_pool = &qp->p_multixri_pool->pbl_pool;
20395                 pvt_pool = &qp->p_multixri_pool->pvt_pool;
20396
20397                 txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
20398                 abts_io_bufs = qp->abts_scsi_io_bufs;
20399                 abts_io_bufs += qp->abts_nvme_io_bufs;
20400
20401                 xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
20402                 xri_limit = qp->p_multixri_pool->xri_limit;
20403
20404 #ifdef LPFC_MXP_STAT
20405                 if (xri_owned <= xri_limit)
20406                         qp->p_multixri_pool->below_limit_count++;
20407                 else
20408                         qp->p_multixri_pool->above_limit_count++;
20409 #endif
20410
20411                 /* XRI goes to either public or private free xri pool
20412                  *     based on watermark and xri_limit
20413                  */
20414                 if ((pvt_pool->count < pvt_pool->low_watermark) ||
20415                     (xri_owned < xri_limit &&
20416                      pvt_pool->count < pvt_pool->high_watermark)) {
20417                         lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
20418                                                   qp, free_pvt_pool);
20419                         list_add_tail(&lpfc_ncmd->list,
20420                                       &pvt_pool->list);
20421                         pvt_pool->count++;
20422                         spin_unlock_irqrestore(&pvt_pool->lock, iflag);
20423                 } else {
20424                         lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
20425                                                   qp, free_pub_pool);
20426                         list_add_tail(&lpfc_ncmd->list,
20427                                       &pbl_pool->list);
20428                         pbl_pool->count++;
20429                         spin_unlock_irqrestore(&pbl_pool->lock, iflag);
20430                 }
20431         } else {
20432                 lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
20433                                           qp, free_xri);
20434                 list_add_tail(&lpfc_ncmd->list,
20435                               &qp->lpfc_io_buf_list_put);
20436                 qp->put_io_bufs++;
20437                 spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
20438                                        iflag);
20439         }
20440 }
20441
20442 /**
20443  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
20444  * @phba: pointer to lpfc hba data structure.
20445  * @pvt_pool: pointer to private pool data structure.
20446  * @ndlp: pointer to lpfc nodelist data structure.
20447  *
20448  * This routine tries to get one free IO buf from private pool.
20449  *
20450  * Return:
20451  *   pointer to one free IO buf - if private pool is not empty
20452  *   NULL - if private pool is empty
20453  **/
20454 static struct lpfc_io_buf *
20455 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
20456                                   struct lpfc_sli4_hdw_queue *qp,
20457                                   struct lpfc_pvt_pool *pvt_pool,
20458                                   struct lpfc_nodelist *ndlp)
20459 {
20460         struct lpfc_io_buf *lpfc_ncmd;
20461         struct lpfc_io_buf *lpfc_ncmd_next;
20462         unsigned long iflag;
20463
20464         lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
20465         list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20466                                  &pvt_pool->list, list) {
20467                 if (lpfc_test_rrq_active(
20468                         phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
20469                         continue;
20470                 list_del(&lpfc_ncmd->list);
20471                 pvt_pool->count--;
20472                 spin_unlock_irqrestore(&pvt_pool->lock, iflag);
20473                 return lpfc_ncmd;
20474         }
20475         spin_unlock_irqrestore(&pvt_pool->lock, iflag);
20476
20477         return NULL;
20478 }
20479
20480 /**
20481  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
20482  * @phba: pointer to lpfc hba data structure.
20483  *
20484  * This routine tries to get one free IO buf from expedite pool.
20485  *
20486  * Return:
20487  *   pointer to one free IO buf - if expedite pool is not empty
20488  *   NULL - if expedite pool is empty
20489  **/
20490 static struct lpfc_io_buf *
20491 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
20492 {
20493         struct lpfc_io_buf *lpfc_ncmd;
20494         struct lpfc_io_buf *lpfc_ncmd_next;
20495         unsigned long iflag;
20496         struct lpfc_epd_pool *epd_pool;
20497
20498         epd_pool = &phba->epd_pool;
20499         lpfc_ncmd = NULL;
20500
20501         spin_lock_irqsave(&epd_pool->lock, iflag);
20502         if (epd_pool->count > 0) {
20503                 list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
20504                                          &epd_pool->list, list) {
20505                         list_del(&lpfc_ncmd->list);
20506                         epd_pool->count--;
20507                         break;
20508                 }
20509         }
20510         spin_unlock_irqrestore(&epd_pool->lock, iflag);
20511
20512         return lpfc_ncmd;
20513 }
20514
20515 /**
20516  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
20517  * @phba: pointer to lpfc hba data structure.
20518  * @ndlp: pointer to lpfc nodelist data structure.
20519  * @hwqid: belong to which HWQ
20520  * @expedite: 1 means this request is urgent.
20521  *
20522  * This routine will do the following actions and then return a pointer to
20523  * one free IO buf.
20524  *
20525  * 1. If private free xri count is empty, move some XRIs from public to
20526  *    private pool.
20527  * 2. Get one XRI from private free xri pool.
20528  * 3. If we fail to get one from pvt_pool and this is an expedite request,
20529  *    get one free xri from expedite pool.
20530  *
20531  * Note: ndlp is only used on SCSI side for RRQ testing.
20532  *       The caller should pass NULL for ndlp on NVME side.
20533  *
20534  * Return:
20535  *   pointer to one free IO buf - if private pool is not empty
20536  *   NULL - if private pool is empty
20537  **/
20538 static struct lpfc_io_buf *
20539 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
20540                                     struct lpfc_nodelist *ndlp,
20541                                     int hwqid, int expedite)
20542 {
20543         struct lpfc_sli4_hdw_queue *qp;
20544         struct lpfc_multixri_pool *multixri_pool;
20545         struct lpfc_pvt_pool *pvt_pool;
20546         struct lpfc_io_buf *lpfc_ncmd;
20547
20548         qp = &phba->sli4_hba.hdwq[hwqid];
20549         lpfc_ncmd = NULL;
20550         multixri_pool = qp->p_multixri_pool;
20551         pvt_pool = &multixri_pool->pvt_pool;
20552         multixri_pool->io_req_count++;
20553
20554         /* If pvt_pool is empty, move some XRIs from public to private pool */
20555         if (pvt_pool->count == 0)
20556                 lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
20557
20558         /* Get one XRI from private free xri pool */
20559         lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
20560
20561         if (lpfc_ncmd) {
20562                 lpfc_ncmd->hdwq = qp;
20563                 lpfc_ncmd->hdwq_no = hwqid;
20564         } else if (expedite) {
20565                 /* If we fail to get one from pvt_pool and this is an expedite
20566                  * request, get one free xri from expedite pool.
20567                  */
20568                 lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
20569         }
20570
20571         return lpfc_ncmd;
20572 }
20573
20574 static inline struct lpfc_io_buf *
20575 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
20576 {
20577         struct lpfc_sli4_hdw_queue *qp;
20578         struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
20579
20580         qp = &phba->sli4_hba.hdwq[idx];
20581         list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
20582                                  &qp->lpfc_io_buf_list_get, list) {
20583                 if (lpfc_test_rrq_active(phba, ndlp,
20584                                          lpfc_cmd->cur_iocbq.sli4_lxritag))
20585                         continue;
20586
20587                 if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
20588                         continue;
20589
20590                 list_del_init(&lpfc_cmd->list);
20591                 qp->get_io_bufs--;
20592                 lpfc_cmd->hdwq = qp;
20593                 lpfc_cmd->hdwq_no = idx;
20594                 return lpfc_cmd;
20595         }
20596         return NULL;
20597 }
20598
20599 /**
20600  * lpfc_get_io_buf - Get one IO buffer from free pool
20601  * @phba: The HBA for which this call is being executed.
20602  * @ndlp: pointer to lpfc nodelist data structure.
20603  * @hwqid: belong to which HWQ
20604  * @expedite: 1 means this request is urgent.
20605  *
20606  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
20607  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
20608  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
20609  *
20610  * Note: ndlp is only used on SCSI side for RRQ testing.
20611  *       The caller should pass NULL for ndlp on NVME side.
20612  *
20613  * Return codes:
20614  *   NULL - Error
20615  *   Pointer to lpfc_io_buf - Success
20616  **/
20617 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
20618                                     struct lpfc_nodelist *ndlp,
20619                                     u32 hwqid, int expedite)
20620 {
20621         struct lpfc_sli4_hdw_queue *qp;
20622         unsigned long iflag;
20623         struct lpfc_io_buf *lpfc_cmd;
20624
20625         qp = &phba->sli4_hba.hdwq[hwqid];
20626         lpfc_cmd = NULL;
20627
20628         if (phba->cfg_xri_rebalancing)
20629                 lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
20630                         phba, ndlp, hwqid, expedite);
20631         else {
20632                 lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
20633                                           qp, alloc_xri_get);
20634                 if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
20635                         lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
20636                 if (!lpfc_cmd) {
20637                         lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
20638                                           qp, alloc_xri_put);
20639                         list_splice(&qp->lpfc_io_buf_list_put,
20640                                     &qp->lpfc_io_buf_list_get);
20641                         qp->get_io_bufs += qp->put_io_bufs;
20642                         INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
20643                         qp->put_io_bufs = 0;
20644                         spin_unlock(&qp->io_buf_list_put_lock);
20645                         if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
20646                             expedite)
20647                                 lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
20648                 }
20649                 spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
20650         }
20651
20652         return lpfc_cmd;
20653 }
20654
20655 /**
20656  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
20657  * @phba: The HBA for which this call is being executed.
20658  * @lpfc_buf: IO buf structure to append the SGL chunk
20659  *
20660  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
20661  * and will allocate an SGL chunk if the pool is empty.
20662  *
20663  * Return codes:
20664  *   NULL - Error
20665  *   Pointer to sli4_hybrid_sgl - Success
20666  **/
20667 struct sli4_hybrid_sgl *
20668 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
20669 {
20670         struct sli4_hybrid_sgl *list_entry = NULL;
20671         struct sli4_hybrid_sgl *tmp = NULL;
20672         struct sli4_hybrid_sgl *allocated_sgl = NULL;
20673         struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
20674         struct list_head *buf_list = &hdwq->sgl_list;
20675         unsigned long iflags;
20676
20677         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20678
20679         if (likely(!list_empty(buf_list))) {
20680                 /* break off 1 chunk from the sgl_list */
20681                 list_for_each_entry_safe(list_entry, tmp,
20682                                          buf_list, list_node) {
20683                         list_move_tail(&list_entry->list_node,
20684                                        &lpfc_buf->dma_sgl_xtra_list);
20685                         break;
20686                 }
20687         } else {
20688                 /* allocate more */
20689                 spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20690                 tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
20691                                    cpu_to_node(hdwq->io_wq->chann));
20692                 if (!tmp) {
20693                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
20694                                         "8353 error kmalloc memory for HDWQ "
20695                                         "%d %s\n",
20696                                         lpfc_buf->hdwq_no, __func__);
20697                         return NULL;
20698                 }
20699
20700                 tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
20701                                               GFP_ATOMIC, &tmp->dma_phys_sgl);
20702                 if (!tmp->dma_sgl) {
20703                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
20704                                         "8354 error pool_alloc memory for HDWQ "
20705                                         "%d %s\n",
20706                                         lpfc_buf->hdwq_no, __func__);
20707                         kfree(tmp);
20708                         return NULL;
20709                 }
20710
20711                 spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20712                 list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
20713         }
20714
20715         allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
20716                                         struct sli4_hybrid_sgl,
20717                                         list_node);
20718
20719         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20720
20721         return allocated_sgl;
20722 }
20723
20724 /**
20725  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
20726  * @phba: The HBA for which this call is being executed.
20727  * @lpfc_buf: IO buf structure with the SGL chunk
20728  *
20729  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
20730  *
20731  * Return codes:
20732  *   0 - Success
20733  *   -EINVAL - Error
20734  **/
20735 int
20736 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
20737 {
20738         int rc = 0;
20739         struct sli4_hybrid_sgl *list_entry = NULL;
20740         struct sli4_hybrid_sgl *tmp = NULL;
20741         struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
20742         struct list_head *buf_list = &hdwq->sgl_list;
20743         unsigned long iflags;
20744
20745         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20746
20747         if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
20748                 list_for_each_entry_safe(list_entry, tmp,
20749                                          &lpfc_buf->dma_sgl_xtra_list,
20750                                          list_node) {
20751                         list_move_tail(&list_entry->list_node,
20752                                        buf_list);
20753                 }
20754         } else {
20755                 rc = -EINVAL;
20756         }
20757
20758         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20759         return rc;
20760 }
20761
20762 /**
20763  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
20764  * @phba: phba object
20765  * @hdwq: hdwq to cleanup sgl buff resources on
20766  *
20767  * This routine frees all SGL chunks of hdwq SGL chunk pool.
20768  *
20769  * Return codes:
20770  *   None
20771  **/
20772 void
20773 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
20774                        struct lpfc_sli4_hdw_queue *hdwq)
20775 {
20776         struct list_head *buf_list = &hdwq->sgl_list;
20777         struct sli4_hybrid_sgl *list_entry = NULL;
20778         struct sli4_hybrid_sgl *tmp = NULL;
20779         unsigned long iflags;
20780
20781         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20782
20783         /* Free sgl pool */
20784         list_for_each_entry_safe(list_entry, tmp,
20785                                  buf_list, list_node) {
20786                 dma_pool_free(phba->lpfc_sg_dma_buf_pool,
20787                               list_entry->dma_sgl,
20788                               list_entry->dma_phys_sgl);
20789                 list_del(&list_entry->list_node);
20790                 kfree(list_entry);
20791         }
20792
20793         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20794 }
20795
20796 /**
20797  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
20798  * @phba: The HBA for which this call is being executed.
20799  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
20800  *
20801  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
20802  * and will allocate an CMD/RSP buffer if the pool is empty.
20803  *
20804  * Return codes:
20805  *   NULL - Error
20806  *   Pointer to fcp_cmd_rsp_buf - Success
20807  **/
20808 struct fcp_cmd_rsp_buf *
20809 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
20810                               struct lpfc_io_buf *lpfc_buf)
20811 {
20812         struct fcp_cmd_rsp_buf *list_entry = NULL;
20813         struct fcp_cmd_rsp_buf *tmp = NULL;
20814         struct fcp_cmd_rsp_buf *allocated_buf = NULL;
20815         struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
20816         struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
20817         unsigned long iflags;
20818
20819         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20820
20821         if (likely(!list_empty(buf_list))) {
20822                 /* break off 1 chunk from the list */
20823                 list_for_each_entry_safe(list_entry, tmp,
20824                                          buf_list,
20825                                          list_node) {
20826                         list_move_tail(&list_entry->list_node,
20827                                        &lpfc_buf->dma_cmd_rsp_list);
20828                         break;
20829                 }
20830         } else {
20831                 /* allocate more */
20832                 spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20833                 tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
20834                                    cpu_to_node(hdwq->io_wq->chann));
20835                 if (!tmp) {
20836                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
20837                                         "8355 error kmalloc memory for HDWQ "
20838                                         "%d %s\n",
20839                                         lpfc_buf->hdwq_no, __func__);
20840                         return NULL;
20841                 }
20842
20843                 tmp->fcp_cmnd = dma_pool_alloc(phba->lpfc_cmd_rsp_buf_pool,
20844                                                 GFP_ATOMIC,
20845                                                 &tmp->fcp_cmd_rsp_dma_handle);
20846
20847                 if (!tmp->fcp_cmnd) {
20848                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
20849                                         "8356 error pool_alloc memory for HDWQ "
20850                                         "%d %s\n",
20851                                         lpfc_buf->hdwq_no, __func__);
20852                         kfree(tmp);
20853                         return NULL;
20854                 }
20855
20856                 tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
20857                                 sizeof(struct fcp_cmnd));
20858
20859                 spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20860                 list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
20861         }
20862
20863         allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
20864                                         struct fcp_cmd_rsp_buf,
20865                                         list_node);
20866
20867         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20868
20869         return allocated_buf;
20870 }
20871
20872 /**
20873  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
20874  * @phba: The HBA for which this call is being executed.
20875  * @lpfc_buf: IO buf structure with the CMD/RSP buf
20876  *
20877  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
20878  *
20879  * Return codes:
20880  *   0 - Success
20881  *   -EINVAL - Error
20882  **/
20883 int
20884 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
20885                               struct lpfc_io_buf *lpfc_buf)
20886 {
20887         int rc = 0;
20888         struct fcp_cmd_rsp_buf *list_entry = NULL;
20889         struct fcp_cmd_rsp_buf *tmp = NULL;
20890         struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
20891         struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
20892         unsigned long iflags;
20893
20894         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20895
20896         if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
20897                 list_for_each_entry_safe(list_entry, tmp,
20898                                          &lpfc_buf->dma_cmd_rsp_list,
20899                                          list_node) {
20900                         list_move_tail(&list_entry->list_node,
20901                                        buf_list);
20902                 }
20903         } else {
20904                 rc = -EINVAL;
20905         }
20906
20907         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20908         return rc;
20909 }
20910
20911 /**
20912  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
20913  * @phba: phba object
20914  * @hdwq: hdwq to cleanup cmd rsp buff resources on
20915  *
20916  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
20917  *
20918  * Return codes:
20919  *   None
20920  **/
20921 void
20922 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
20923                                struct lpfc_sli4_hdw_queue *hdwq)
20924 {
20925         struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
20926         struct fcp_cmd_rsp_buf *list_entry = NULL;
20927         struct fcp_cmd_rsp_buf *tmp = NULL;
20928         unsigned long iflags;
20929
20930         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
20931
20932         /* Free cmd_rsp buf pool */
20933         list_for_each_entry_safe(list_entry, tmp,
20934                                  buf_list,
20935                                  list_node) {
20936                 dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
20937                               list_entry->fcp_cmnd,
20938                               list_entry->fcp_cmd_rsp_dma_handle);
20939                 list_del(&list_entry->list_node);
20940                 kfree(list_entry);
20941         }
20942
20943         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
20944 }