Merge tag 'ovl-update-5.16' of git://git.kernel.org/pub/scm/linux/kernel/git/mszeredi/vfs
[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-2021 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 #include <linux/crash_dump.h>
39 #ifdef CONFIG_X86
40 #include <asm/set_memory.h>
41 #endif
42
43 #include "lpfc_hw4.h"
44 #include "lpfc_hw.h"
45 #include "lpfc_sli.h"
46 #include "lpfc_sli4.h"
47 #include "lpfc_nl.h"
48 #include "lpfc_disc.h"
49 #include "lpfc.h"
50 #include "lpfc_scsi.h"
51 #include "lpfc_nvme.h"
52 #include "lpfc_crtn.h"
53 #include "lpfc_logmsg.h"
54 #include "lpfc_compat.h"
55 #include "lpfc_debugfs.h"
56 #include "lpfc_vport.h"
57 #include "lpfc_version.h"
58
59 /* There are only four IOCB completion types. */
60 typedef enum _lpfc_iocb_type {
61         LPFC_UNKNOWN_IOCB,
62         LPFC_UNSOL_IOCB,
63         LPFC_SOL_IOCB,
64         LPFC_ABORT_IOCB
65 } lpfc_iocb_type;
66
67
68 /* Provide function prototypes local to this module. */
69 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
70                                   uint32_t);
71 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
72                               uint8_t *, uint32_t *);
73 static struct lpfc_iocbq *lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *,
74                                                          struct lpfc_iocbq *);
75 static void lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *,
76                                       struct hbq_dmabuf *);
77 static void lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
78                                           struct hbq_dmabuf *dmabuf);
79 static bool lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba,
80                                    struct lpfc_queue *cq, struct lpfc_cqe *cqe);
81 static int lpfc_sli4_post_sgl_list(struct lpfc_hba *, struct list_head *,
82                                        int);
83 static void lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba,
84                                      struct lpfc_queue *eq,
85                                      struct lpfc_eqe *eqe);
86 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
87 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
88 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
89 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
90                                     struct lpfc_queue *cq,
91                                     struct lpfc_cqe *cqe);
92
93 union lpfc_wqe128 lpfc_iread_cmd_template;
94 union lpfc_wqe128 lpfc_iwrite_cmd_template;
95 union lpfc_wqe128 lpfc_icmnd_cmd_template;
96
97 static IOCB_t *
98 lpfc_get_iocb_from_iocbq(struct lpfc_iocbq *iocbq)
99 {
100         return &iocbq->iocb;
101 }
102
103 /* Setup WQE templates for IOs */
104 void lpfc_wqe_cmd_template(void)
105 {
106         union lpfc_wqe128 *wqe;
107
108         /* IREAD template */
109         wqe = &lpfc_iread_cmd_template;
110         memset(wqe, 0, sizeof(union lpfc_wqe128));
111
112         /* Word 0, 1, 2 - BDE is variable */
113
114         /* Word 3 - cmd_buff_len, payload_offset_len is zero */
115
116         /* Word 4 - total_xfer_len is variable */
117
118         /* Word 5 - is zero */
119
120         /* Word 6 - ctxt_tag, xri_tag is variable */
121
122         /* Word 7 */
123         bf_set(wqe_cmnd, &wqe->fcp_iread.wqe_com, CMD_FCP_IREAD64_WQE);
124         bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, PARM_READ_CHECK);
125         bf_set(wqe_class, &wqe->fcp_iread.wqe_com, CLASS3);
126         bf_set(wqe_ct, &wqe->fcp_iread.wqe_com, SLI4_CT_RPI);
127
128         /* Word 8 - abort_tag is variable */
129
130         /* Word 9  - reqtag is variable */
131
132         /* Word 10 - dbde, wqes is variable */
133         bf_set(wqe_qosd, &wqe->fcp_iread.wqe_com, 0);
134         bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
135         bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com, LPFC_WQE_LENLOC_WORD4);
136         bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
137         bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
138
139         /* Word 11 - pbde is variable */
140         bf_set(wqe_cmd_type, &wqe->fcp_iread.wqe_com, COMMAND_DATA_IN);
141         bf_set(wqe_cqid, &wqe->fcp_iread.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
142         bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
143
144         /* Word 12 - is zero */
145
146         /* Word 13, 14, 15 - PBDE is variable */
147
148         /* IWRITE template */
149         wqe = &lpfc_iwrite_cmd_template;
150         memset(wqe, 0, sizeof(union lpfc_wqe128));
151
152         /* Word 0, 1, 2 - BDE is variable */
153
154         /* Word 3 - cmd_buff_len, payload_offset_len is zero */
155
156         /* Word 4 - total_xfer_len is variable */
157
158         /* Word 5 - initial_xfer_len is variable */
159
160         /* Word 6 - ctxt_tag, xri_tag is variable */
161
162         /* Word 7 */
163         bf_set(wqe_cmnd, &wqe->fcp_iwrite.wqe_com, CMD_FCP_IWRITE64_WQE);
164         bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, PARM_READ_CHECK);
165         bf_set(wqe_class, &wqe->fcp_iwrite.wqe_com, CLASS3);
166         bf_set(wqe_ct, &wqe->fcp_iwrite.wqe_com, SLI4_CT_RPI);
167
168         /* Word 8 - abort_tag is variable */
169
170         /* Word 9  - reqtag is variable */
171
172         /* Word 10 - dbde, wqes is variable */
173         bf_set(wqe_qosd, &wqe->fcp_iwrite.wqe_com, 0);
174         bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
175         bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_LENLOC_WORD4);
176         bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
177         bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
178
179         /* Word 11 - pbde is variable */
180         bf_set(wqe_cmd_type, &wqe->fcp_iwrite.wqe_com, COMMAND_DATA_OUT);
181         bf_set(wqe_cqid, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
182         bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
183
184         /* Word 12 - is zero */
185
186         /* Word 13, 14, 15 - PBDE is variable */
187
188         /* ICMND template */
189         wqe = &lpfc_icmnd_cmd_template;
190         memset(wqe, 0, sizeof(union lpfc_wqe128));
191
192         /* Word 0, 1, 2 - BDE is variable */
193
194         /* Word 3 - payload_offset_len is variable */
195
196         /* Word 4, 5 - is zero */
197
198         /* Word 6 - ctxt_tag, xri_tag is variable */
199
200         /* Word 7 */
201         bf_set(wqe_cmnd, &wqe->fcp_icmd.wqe_com, CMD_FCP_ICMND64_WQE);
202         bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
203         bf_set(wqe_class, &wqe->fcp_icmd.wqe_com, CLASS3);
204         bf_set(wqe_ct, &wqe->fcp_icmd.wqe_com, SLI4_CT_RPI);
205
206         /* Word 8 - abort_tag is variable */
207
208         /* Word 9  - reqtag is variable */
209
210         /* Word 10 - dbde, wqes is variable */
211         bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
212         bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_NONE);
213         bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com, LPFC_WQE_LENLOC_NONE);
214         bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
215         bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
216
217         /* Word 11 */
218         bf_set(wqe_cmd_type, &wqe->fcp_icmd.wqe_com, COMMAND_DATA_IN);
219         bf_set(wqe_cqid, &wqe->fcp_icmd.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
220         bf_set(wqe_pbde, &wqe->fcp_icmd.wqe_com, 0);
221
222         /* Word 12, 13, 14, 15 - is zero */
223 }
224
225 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
226 /**
227  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
228  * @srcp: Source memory pointer.
229  * @destp: Destination memory pointer.
230  * @cnt: Number of words required to be copied.
231  *       Must be a multiple of sizeof(uint64_t)
232  *
233  * This function is used for copying data between driver memory
234  * and the SLI WQ. This function also changes the endianness
235  * of each word if native endianness is different from SLI
236  * endianness. This function can be called with or without
237  * lock.
238  **/
239 static void
240 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
241 {
242         uint64_t *src = srcp;
243         uint64_t *dest = destp;
244         int i;
245
246         for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
247                 *dest++ = *src++;
248 }
249 #else
250 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
251 #endif
252
253 /**
254  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
255  * @q: The Work Queue to operate on.
256  * @wqe: The work Queue Entry to put on the Work queue.
257  *
258  * This routine will copy the contents of @wqe to the next available entry on
259  * the @q. This function will then ring the Work Queue Doorbell to signal the
260  * HBA to start processing the Work Queue Entry. This function returns 0 if
261  * successful. If no entries are available on @q then this function will return
262  * -ENOMEM.
263  * The caller is expected to hold the hbalock when calling this routine.
264  **/
265 static int
266 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
267 {
268         union lpfc_wqe *temp_wqe;
269         struct lpfc_register doorbell;
270         uint32_t host_index;
271         uint32_t idx;
272         uint32_t i = 0;
273         uint8_t *tmp;
274         u32 if_type;
275
276         /* sanity check on queue memory */
277         if (unlikely(!q))
278                 return -ENOMEM;
279
280         temp_wqe = lpfc_sli4_qe(q, q->host_index);
281
282         /* If the host has not yet processed the next entry then we are done */
283         idx = ((q->host_index + 1) % q->entry_count);
284         if (idx == q->hba_index) {
285                 q->WQ_overflow++;
286                 return -EBUSY;
287         }
288         q->WQ_posted++;
289         /* set consumption flag every once in a while */
290         if (!((q->host_index + 1) % q->notify_interval))
291                 bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
292         else
293                 bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
294         if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
295                 bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
296         lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
297         if (q->dpp_enable && q->phba->cfg_enable_dpp) {
298                 /* write to DPP aperture taking advatage of Combined Writes */
299                 tmp = (uint8_t *)temp_wqe;
300 #ifdef __raw_writeq
301                 for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
302                         __raw_writeq(*((uint64_t *)(tmp + i)),
303                                         q->dpp_regaddr + i);
304 #else
305                 for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
306                         __raw_writel(*((uint32_t *)(tmp + i)),
307                                         q->dpp_regaddr + i);
308 #endif
309         }
310         /* ensure WQE bcopy and DPP flushed before doorbell write */
311         wmb();
312
313         /* Update the host index before invoking device */
314         host_index = q->host_index;
315
316         q->host_index = idx;
317
318         /* Ring Doorbell */
319         doorbell.word0 = 0;
320         if (q->db_format == LPFC_DB_LIST_FORMAT) {
321                 if (q->dpp_enable && q->phba->cfg_enable_dpp) {
322                         bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
323                         bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
324                         bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
325                             q->dpp_id);
326                         bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
327                             q->queue_id);
328                 } else {
329                         bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
330                         bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
331
332                         /* Leave bits <23:16> clear for if_type 6 dpp */
333                         if_type = bf_get(lpfc_sli_intf_if_type,
334                                          &q->phba->sli4_hba.sli_intf);
335                         if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
336                                 bf_set(lpfc_wq_db_list_fm_index, &doorbell,
337                                        host_index);
338                 }
339         } else if (q->db_format == LPFC_DB_RING_FORMAT) {
340                 bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
341                 bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
342         } else {
343                 return -EINVAL;
344         }
345         writel(doorbell.word0, q->db_regaddr);
346
347         return 0;
348 }
349
350 /**
351  * lpfc_sli4_wq_release - Updates internal hba index for WQ
352  * @q: The Work Queue to operate on.
353  * @index: The index to advance the hba index to.
354  *
355  * This routine will update the HBA index of a queue to reflect consumption of
356  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
357  * an entry the host calls this function to update the queue's internal
358  * pointers.
359  **/
360 static void
361 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
362 {
363         /* sanity check on queue memory */
364         if (unlikely(!q))
365                 return;
366
367         q->hba_index = index;
368 }
369
370 /**
371  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
372  * @q: The Mailbox Queue to operate on.
373  * @mqe: The Mailbox Queue Entry to put on the Work queue.
374  *
375  * This routine will copy the contents of @mqe to the next available entry on
376  * the @q. This function will then ring the Work Queue Doorbell to signal the
377  * HBA to start processing the Work Queue Entry. This function returns 0 if
378  * successful. If no entries are available on @q then this function will return
379  * -ENOMEM.
380  * The caller is expected to hold the hbalock when calling this routine.
381  **/
382 static uint32_t
383 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
384 {
385         struct lpfc_mqe *temp_mqe;
386         struct lpfc_register doorbell;
387
388         /* sanity check on queue memory */
389         if (unlikely(!q))
390                 return -ENOMEM;
391         temp_mqe = lpfc_sli4_qe(q, q->host_index);
392
393         /* If the host has not yet processed the next entry then we are done */
394         if (((q->host_index + 1) % q->entry_count) == q->hba_index)
395                 return -ENOMEM;
396         lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
397         /* Save off the mailbox pointer for completion */
398         q->phba->mbox = (MAILBOX_t *)temp_mqe;
399
400         /* Update the host index before invoking device */
401         q->host_index = ((q->host_index + 1) % q->entry_count);
402
403         /* Ring Doorbell */
404         doorbell.word0 = 0;
405         bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
406         bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
407         writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
408         return 0;
409 }
410
411 /**
412  * lpfc_sli4_mq_release - Updates internal hba index for MQ
413  * @q: The Mailbox Queue to operate on.
414  *
415  * This routine will update the HBA index of a queue to reflect consumption of
416  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
417  * an entry the host calls this function to update the queue's internal
418  * pointers. This routine returns the number of entries that were consumed by
419  * the HBA.
420  **/
421 static uint32_t
422 lpfc_sli4_mq_release(struct lpfc_queue *q)
423 {
424         /* sanity check on queue memory */
425         if (unlikely(!q))
426                 return 0;
427
428         /* Clear the mailbox pointer for completion */
429         q->phba->mbox = NULL;
430         q->hba_index = ((q->hba_index + 1) % q->entry_count);
431         return 1;
432 }
433
434 /**
435  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
436  * @q: The Event Queue to get the first valid EQE from
437  *
438  * This routine will get the first valid Event Queue Entry from @q, update
439  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
440  * the Queue (no more work to do), or the Queue is full of EQEs that have been
441  * processed, but not popped back to the HBA then this routine will return NULL.
442  **/
443 static struct lpfc_eqe *
444 lpfc_sli4_eq_get(struct lpfc_queue *q)
445 {
446         struct lpfc_eqe *eqe;
447
448         /* sanity check on queue memory */
449         if (unlikely(!q))
450                 return NULL;
451         eqe = lpfc_sli4_qe(q, q->host_index);
452
453         /* If the next EQE is not valid then we are done */
454         if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
455                 return NULL;
456
457         /*
458          * insert barrier for instruction interlock : data from the hardware
459          * must have the valid bit checked before it can be copied and acted
460          * upon. Speculative instructions were allowing a bcopy at the start
461          * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
462          * after our return, to copy data before the valid bit check above
463          * was done. As such, some of the copied data was stale. The barrier
464          * ensures the check is before any data is copied.
465          */
466         mb();
467         return eqe;
468 }
469
470 /**
471  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
472  * @q: The Event Queue to disable interrupts
473  *
474  **/
475 void
476 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
477 {
478         struct lpfc_register doorbell;
479
480         doorbell.word0 = 0;
481         bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
482         bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
483         bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
484                 (q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
485         bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
486         writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
487 }
488
489 /**
490  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
491  * @q: The Event Queue to disable interrupts
492  *
493  **/
494 void
495 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
496 {
497         struct lpfc_register doorbell;
498
499         doorbell.word0 = 0;
500         bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
501         writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
502 }
503
504 /**
505  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
506  * @phba: adapter with EQ
507  * @q: The Event Queue that the host has completed processing for.
508  * @count: Number of elements that have been consumed
509  * @arm: Indicates whether the host wants to arms this CQ.
510  *
511  * This routine will notify the HBA, by ringing the doorbell, that count
512  * number of EQEs have been processed. The @arm parameter indicates whether
513  * the queue should be rearmed when ringing the doorbell.
514  **/
515 void
516 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
517                      uint32_t count, bool arm)
518 {
519         struct lpfc_register doorbell;
520
521         /* sanity check on queue memory */
522         if (unlikely(!q || (count == 0 && !arm)))
523                 return;
524
525         /* ring doorbell for number popped */
526         doorbell.word0 = 0;
527         if (arm) {
528                 bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
529                 bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
530         }
531         bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
532         bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
533         bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
534                         (q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
535         bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
536         writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
537         /* PCI read to flush PCI pipeline on re-arming for INTx mode */
538         if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
539                 readl(q->phba->sli4_hba.EQDBregaddr);
540 }
541
542 /**
543  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
544  * @phba: adapter with EQ
545  * @q: The Event Queue that the host has completed processing for.
546  * @count: Number of elements that have been consumed
547  * @arm: Indicates whether the host wants to arms this CQ.
548  *
549  * This routine will notify the HBA, by ringing the doorbell, that count
550  * number of EQEs have been processed. The @arm parameter indicates whether
551  * the queue should be rearmed when ringing the doorbell.
552  **/
553 void
554 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
555                           uint32_t count, bool arm)
556 {
557         struct lpfc_register doorbell;
558
559         /* sanity check on queue memory */
560         if (unlikely(!q || (count == 0 && !arm)))
561                 return;
562
563         /* ring doorbell for number popped */
564         doorbell.word0 = 0;
565         if (arm)
566                 bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
567         bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
568         bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
569         writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
570         /* PCI read to flush PCI pipeline on re-arming for INTx mode */
571         if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
572                 readl(q->phba->sli4_hba.EQDBregaddr);
573 }
574
575 static void
576 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
577                         struct lpfc_eqe *eqe)
578 {
579         if (!phba->sli4_hba.pc_sli4_params.eqav)
580                 bf_set_le32(lpfc_eqe_valid, eqe, 0);
581
582         eq->host_index = ((eq->host_index + 1) % eq->entry_count);
583
584         /* if the index wrapped around, toggle the valid bit */
585         if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
586                 eq->qe_valid = (eq->qe_valid) ? 0 : 1;
587 }
588
589 static void
590 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
591 {
592         struct lpfc_eqe *eqe = NULL;
593         u32 eq_count = 0, cq_count = 0;
594         struct lpfc_cqe *cqe = NULL;
595         struct lpfc_queue *cq = NULL, *childq = NULL;
596         int cqid = 0;
597
598         /* walk all the EQ entries and drop on the floor */
599         eqe = lpfc_sli4_eq_get(eq);
600         while (eqe) {
601                 /* Get the reference to the corresponding CQ */
602                 cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
603                 cq = NULL;
604
605                 list_for_each_entry(childq, &eq->child_list, list) {
606                         if (childq->queue_id == cqid) {
607                                 cq = childq;
608                                 break;
609                         }
610                 }
611                 /* If CQ is valid, iterate through it and drop all the CQEs */
612                 if (cq) {
613                         cqe = lpfc_sli4_cq_get(cq);
614                         while (cqe) {
615                                 __lpfc_sli4_consume_cqe(phba, cq, cqe);
616                                 cq_count++;
617                                 cqe = lpfc_sli4_cq_get(cq);
618                         }
619                         /* Clear and re-arm the CQ */
620                         phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
621                             LPFC_QUEUE_REARM);
622                         cq_count = 0;
623                 }
624                 __lpfc_sli4_consume_eqe(phba, eq, eqe);
625                 eq_count++;
626                 eqe = lpfc_sli4_eq_get(eq);
627         }
628
629         /* Clear and re-arm the EQ */
630         phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
631 }
632
633 static int
634 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
635                      uint8_t rearm)
636 {
637         struct lpfc_eqe *eqe;
638         int count = 0, consumed = 0;
639
640         if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
641                 goto rearm_and_exit;
642
643         eqe = lpfc_sli4_eq_get(eq);
644         while (eqe) {
645                 lpfc_sli4_hba_handle_eqe(phba, eq, eqe);
646                 __lpfc_sli4_consume_eqe(phba, eq, eqe);
647
648                 consumed++;
649                 if (!(++count % eq->max_proc_limit))
650                         break;
651
652                 if (!(count % eq->notify_interval)) {
653                         phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
654                                                         LPFC_QUEUE_NOARM);
655                         consumed = 0;
656                 }
657
658                 eqe = lpfc_sli4_eq_get(eq);
659         }
660         eq->EQ_processed += count;
661
662         /* Track the max number of EQEs processed in 1 intr */
663         if (count > eq->EQ_max_eqe)
664                 eq->EQ_max_eqe = count;
665
666         xchg(&eq->queue_claimed, 0);
667
668 rearm_and_exit:
669         /* Always clear the EQ. */
670         phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
671
672         return count;
673 }
674
675 /**
676  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
677  * @q: The Completion Queue to get the first valid CQE from
678  *
679  * This routine will get the first valid Completion Queue Entry from @q, update
680  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
681  * the Queue (no more work to do), or the Queue is full of CQEs that have been
682  * processed, but not popped back to the HBA then this routine will return NULL.
683  **/
684 static struct lpfc_cqe *
685 lpfc_sli4_cq_get(struct lpfc_queue *q)
686 {
687         struct lpfc_cqe *cqe;
688
689         /* sanity check on queue memory */
690         if (unlikely(!q))
691                 return NULL;
692         cqe = lpfc_sli4_qe(q, q->host_index);
693
694         /* If the next CQE is not valid then we are done */
695         if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
696                 return NULL;
697
698         /*
699          * insert barrier for instruction interlock : data from the hardware
700          * must have the valid bit checked before it can be copied and acted
701          * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
702          * instructions allowing action on content before valid bit checked,
703          * add barrier here as well. May not be needed as "content" is a
704          * single 32-bit entity here (vs multi word structure for cq's).
705          */
706         mb();
707         return cqe;
708 }
709
710 static void
711 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
712                         struct lpfc_cqe *cqe)
713 {
714         if (!phba->sli4_hba.pc_sli4_params.cqav)
715                 bf_set_le32(lpfc_cqe_valid, cqe, 0);
716
717         cq->host_index = ((cq->host_index + 1) % cq->entry_count);
718
719         /* if the index wrapped around, toggle the valid bit */
720         if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
721                 cq->qe_valid = (cq->qe_valid) ? 0 : 1;
722 }
723
724 /**
725  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
726  * @phba: the adapter with the CQ
727  * @q: The Completion Queue that the host has completed processing for.
728  * @count: the number of elements that were consumed
729  * @arm: Indicates whether the host wants to arms this CQ.
730  *
731  * This routine will notify the HBA, by ringing the doorbell, that the
732  * CQEs have been processed. The @arm parameter specifies whether the
733  * queue should be rearmed when ringing the doorbell.
734  **/
735 void
736 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
737                      uint32_t count, bool arm)
738 {
739         struct lpfc_register doorbell;
740
741         /* sanity check on queue memory */
742         if (unlikely(!q || (count == 0 && !arm)))
743                 return;
744
745         /* ring doorbell for number popped */
746         doorbell.word0 = 0;
747         if (arm)
748                 bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
749         bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
750         bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
751         bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
752                         (q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
753         bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
754         writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
755 }
756
757 /**
758  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
759  * @phba: the adapter with the CQ
760  * @q: The Completion Queue that the host has completed processing for.
761  * @count: the number of elements that were consumed
762  * @arm: Indicates whether the host wants to arms this CQ.
763  *
764  * This routine will notify the HBA, by ringing the doorbell, that the
765  * CQEs have been processed. The @arm parameter specifies whether the
766  * queue should be rearmed when ringing the doorbell.
767  **/
768 void
769 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
770                          uint32_t count, bool arm)
771 {
772         struct lpfc_register doorbell;
773
774         /* sanity check on queue memory */
775         if (unlikely(!q || (count == 0 && !arm)))
776                 return;
777
778         /* ring doorbell for number popped */
779         doorbell.word0 = 0;
780         if (arm)
781                 bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
782         bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
783         bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
784         writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
785 }
786
787 /*
788  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
789  *
790  * This routine will copy the contents of @wqe to the next available entry on
791  * the @q. This function will then ring the Receive Queue Doorbell to signal the
792  * HBA to start processing the Receive Queue Entry. This function returns the
793  * index that the rqe was copied to if successful. If no entries are available
794  * on @q then this function will return -ENOMEM.
795  * The caller is expected to hold the hbalock when calling this routine.
796  **/
797 int
798 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
799                  struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
800 {
801         struct lpfc_rqe *temp_hrqe;
802         struct lpfc_rqe *temp_drqe;
803         struct lpfc_register doorbell;
804         int hq_put_index;
805         int dq_put_index;
806
807         /* sanity check on queue memory */
808         if (unlikely(!hq) || unlikely(!dq))
809                 return -ENOMEM;
810         hq_put_index = hq->host_index;
811         dq_put_index = dq->host_index;
812         temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
813         temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
814
815         if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
816                 return -EINVAL;
817         if (hq_put_index != dq_put_index)
818                 return -EINVAL;
819         /* If the host has not yet processed the next entry then we are done */
820         if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
821                 return -EBUSY;
822         lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
823         lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
824
825         /* Update the host index to point to the next slot */
826         hq->host_index = ((hq_put_index + 1) % hq->entry_count);
827         dq->host_index = ((dq_put_index + 1) % dq->entry_count);
828         hq->RQ_buf_posted++;
829
830         /* Ring The Header Receive Queue Doorbell */
831         if (!(hq->host_index % hq->notify_interval)) {
832                 doorbell.word0 = 0;
833                 if (hq->db_format == LPFC_DB_RING_FORMAT) {
834                         bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
835                                hq->notify_interval);
836                         bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
837                 } else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
838                         bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
839                                hq->notify_interval);
840                         bf_set(lpfc_rq_db_list_fm_index, &doorbell,
841                                hq->host_index);
842                         bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
843                 } else {
844                         return -EINVAL;
845                 }
846                 writel(doorbell.word0, hq->db_regaddr);
847         }
848         return hq_put_index;
849 }
850
851 /*
852  * lpfc_sli4_rq_release - Updates internal hba index for RQ
853  *
854  * This routine will update the HBA index of a queue to reflect consumption of
855  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
856  * consumed an entry the host calls this function to update the queue's
857  * internal pointers. This routine returns the number of entries that were
858  * consumed by the HBA.
859  **/
860 static uint32_t
861 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
862 {
863         /* sanity check on queue memory */
864         if (unlikely(!hq) || unlikely(!dq))
865                 return 0;
866
867         if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
868                 return 0;
869         hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
870         dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
871         return 1;
872 }
873
874 /**
875  * lpfc_cmd_iocb - Get next command iocb entry in the ring
876  * @phba: Pointer to HBA context object.
877  * @pring: Pointer to driver SLI ring object.
878  *
879  * This function returns pointer to next command iocb entry
880  * in the command ring. The caller must hold hbalock to prevent
881  * other threads consume the next command iocb.
882  * SLI-2/SLI-3 provide different sized iocbs.
883  **/
884 static inline IOCB_t *
885 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
886 {
887         return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
888                            pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
889 }
890
891 /**
892  * lpfc_resp_iocb - Get next response iocb entry in the ring
893  * @phba: Pointer to HBA context object.
894  * @pring: Pointer to driver SLI ring object.
895  *
896  * This function returns pointer to next response iocb entry
897  * in the response ring. The caller must hold hbalock to make sure
898  * that no other thread consume the next response iocb.
899  * SLI-2/SLI-3 provide different sized iocbs.
900  **/
901 static inline IOCB_t *
902 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
903 {
904         return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
905                            pring->sli.sli3.rspidx * phba->iocb_rsp_size);
906 }
907
908 /**
909  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
910  * @phba: Pointer to HBA context object.
911  *
912  * This function is called with hbalock held. This function
913  * allocates a new driver iocb object from the iocb pool. If the
914  * allocation is successful, it returns pointer to the newly
915  * allocated iocb object else it returns NULL.
916  **/
917 struct lpfc_iocbq *
918 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
919 {
920         struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
921         struct lpfc_iocbq * iocbq = NULL;
922
923         lockdep_assert_held(&phba->hbalock);
924
925         list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
926         if (iocbq)
927                 phba->iocb_cnt++;
928         if (phba->iocb_cnt > phba->iocb_max)
929                 phba->iocb_max = phba->iocb_cnt;
930         return iocbq;
931 }
932
933 /**
934  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
935  * @phba: Pointer to HBA context object.
936  * @xritag: XRI value.
937  *
938  * This function clears the sglq pointer from the array of active
939  * sglq's. The xritag that is passed in is used to index into the
940  * array. Before the xritag can be used it needs to be adjusted
941  * by subtracting the xribase.
942  *
943  * Returns sglq ponter = success, NULL = Failure.
944  **/
945 struct lpfc_sglq *
946 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
947 {
948         struct lpfc_sglq *sglq;
949
950         sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
951         phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
952         return sglq;
953 }
954
955 /**
956  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
957  * @phba: Pointer to HBA context object.
958  * @xritag: XRI value.
959  *
960  * This function returns the sglq pointer from the array of active
961  * sglq's. The xritag that is passed in is used to index into the
962  * array. Before the xritag can be used it needs to be adjusted
963  * by subtracting the xribase.
964  *
965  * Returns sglq ponter = success, NULL = Failure.
966  **/
967 struct lpfc_sglq *
968 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
969 {
970         struct lpfc_sglq *sglq;
971
972         sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
973         return sglq;
974 }
975
976 /**
977  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
978  * @phba: Pointer to HBA context object.
979  * @xritag: xri used in this exchange.
980  * @rrq: The RRQ to be cleared.
981  *
982  **/
983 void
984 lpfc_clr_rrq_active(struct lpfc_hba *phba,
985                     uint16_t xritag,
986                     struct lpfc_node_rrq *rrq)
987 {
988         struct lpfc_nodelist *ndlp = NULL;
989
990         /* Lookup did to verify if did is still active on this vport */
991         if (rrq->vport)
992                 ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
993
994         if (!ndlp)
995                 goto out;
996
997         if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
998                 rrq->send_rrq = 0;
999                 rrq->xritag = 0;
1000                 rrq->rrq_stop_time = 0;
1001         }
1002 out:
1003         mempool_free(rrq, phba->rrq_pool);
1004 }
1005
1006 /**
1007  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
1008  * @phba: Pointer to HBA context object.
1009  *
1010  * This function is called with hbalock held. This function
1011  * Checks if stop_time (ratov from setting rrq active) has
1012  * been reached, if it has and the send_rrq flag is set then
1013  * it will call lpfc_send_rrq. If the send_rrq flag is not set
1014  * then it will just call the routine to clear the rrq and
1015  * free the rrq resource.
1016  * The timer is set to the next rrq that is going to expire before
1017  * leaving the routine.
1018  *
1019  **/
1020 void
1021 lpfc_handle_rrq_active(struct lpfc_hba *phba)
1022 {
1023         struct lpfc_node_rrq *rrq;
1024         struct lpfc_node_rrq *nextrrq;
1025         unsigned long next_time;
1026         unsigned long iflags;
1027         LIST_HEAD(send_rrq);
1028
1029         spin_lock_irqsave(&phba->hbalock, iflags);
1030         phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1031         next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1032         list_for_each_entry_safe(rrq, nextrrq,
1033                                  &phba->active_rrq_list, list) {
1034                 if (time_after(jiffies, rrq->rrq_stop_time))
1035                         list_move(&rrq->list, &send_rrq);
1036                 else if (time_before(rrq->rrq_stop_time, next_time))
1037                         next_time = rrq->rrq_stop_time;
1038         }
1039         spin_unlock_irqrestore(&phba->hbalock, iflags);
1040         if ((!list_empty(&phba->active_rrq_list)) &&
1041             (!(phba->pport->load_flag & FC_UNLOADING)))
1042                 mod_timer(&phba->rrq_tmr, next_time);
1043         list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
1044                 list_del(&rrq->list);
1045                 if (!rrq->send_rrq) {
1046                         /* this call will free the rrq */
1047                         lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1048                 } else if (lpfc_send_rrq(phba, rrq)) {
1049                         /* if we send the rrq then the completion handler
1050                         *  will clear the bit in the xribitmap.
1051                         */
1052                         lpfc_clr_rrq_active(phba, rrq->xritag,
1053                                             rrq);
1054                 }
1055         }
1056 }
1057
1058 /**
1059  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
1060  * @vport: Pointer to vport context object.
1061  * @xri: The xri used in the exchange.
1062  * @did: The targets DID for this exchange.
1063  *
1064  * returns NULL = rrq not found in the phba->active_rrq_list.
1065  *         rrq = rrq for this xri and target.
1066  **/
1067 struct lpfc_node_rrq *
1068 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
1069 {
1070         struct lpfc_hba *phba = vport->phba;
1071         struct lpfc_node_rrq *rrq;
1072         struct lpfc_node_rrq *nextrrq;
1073         unsigned long iflags;
1074
1075         if (phba->sli_rev != LPFC_SLI_REV4)
1076                 return NULL;
1077         spin_lock_irqsave(&phba->hbalock, iflags);
1078         list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1079                 if (rrq->vport == vport && rrq->xritag == xri &&
1080                                 rrq->nlp_DID == did){
1081                         list_del(&rrq->list);
1082                         spin_unlock_irqrestore(&phba->hbalock, iflags);
1083                         return rrq;
1084                 }
1085         }
1086         spin_unlock_irqrestore(&phba->hbalock, iflags);
1087         return NULL;
1088 }
1089
1090 /**
1091  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
1092  * @vport: Pointer to vport context object.
1093  * @ndlp: Pointer to the lpfc_node_list structure.
1094  * If ndlp is NULL Remove all active RRQs for this vport from the
1095  * phba->active_rrq_list and clear the rrq.
1096  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
1097  **/
1098 void
1099 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
1100
1101 {
1102         struct lpfc_hba *phba = vport->phba;
1103         struct lpfc_node_rrq *rrq;
1104         struct lpfc_node_rrq *nextrrq;
1105         unsigned long iflags;
1106         LIST_HEAD(rrq_list);
1107
1108         if (phba->sli_rev != LPFC_SLI_REV4)
1109                 return;
1110         if (!ndlp) {
1111                 lpfc_sli4_vport_delete_els_xri_aborted(vport);
1112                 lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
1113         }
1114         spin_lock_irqsave(&phba->hbalock, iflags);
1115         list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1116                 if (rrq->vport != vport)
1117                         continue;
1118
1119                 if (!ndlp || ndlp == lpfc_findnode_did(vport, rrq->nlp_DID))
1120                         list_move(&rrq->list, &rrq_list);
1121
1122         }
1123         spin_unlock_irqrestore(&phba->hbalock, iflags);
1124
1125         list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1126                 list_del(&rrq->list);
1127                 lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1128         }
1129 }
1130
1131 /**
1132  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1133  * @phba: Pointer to HBA context object.
1134  * @ndlp: Targets nodelist pointer for this exchange.
1135  * @xritag: the xri in the bitmap to test.
1136  *
1137  * This function returns:
1138  * 0 = rrq not active for this xri
1139  * 1 = rrq is valid for this xri.
1140  **/
1141 int
1142 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1143                         uint16_t  xritag)
1144 {
1145         if (!ndlp)
1146                 return 0;
1147         if (!ndlp->active_rrqs_xri_bitmap)
1148                 return 0;
1149         if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1150                 return 1;
1151         else
1152                 return 0;
1153 }
1154
1155 /**
1156  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1157  * @phba: Pointer to HBA context object.
1158  * @ndlp: nodelist pointer for this target.
1159  * @xritag: xri used in this exchange.
1160  * @rxid: Remote Exchange ID.
1161  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1162  *
1163  * This function takes the hbalock.
1164  * The active bit is always set in the active rrq xri_bitmap even
1165  * if there is no slot avaiable for the other rrq information.
1166  *
1167  * returns 0 rrq actived for this xri
1168  *         < 0 No memory or invalid ndlp.
1169  **/
1170 int
1171 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1172                     uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1173 {
1174         unsigned long iflags;
1175         struct lpfc_node_rrq *rrq;
1176         int empty;
1177
1178         if (!ndlp)
1179                 return -EINVAL;
1180
1181         if (!phba->cfg_enable_rrq)
1182                 return -EINVAL;
1183
1184         spin_lock_irqsave(&phba->hbalock, iflags);
1185         if (phba->pport->load_flag & FC_UNLOADING) {
1186                 phba->hba_flag &= ~HBA_RRQ_ACTIVE;
1187                 goto out;
1188         }
1189
1190         if (ndlp->vport && (ndlp->vport->load_flag & FC_UNLOADING))
1191                 goto out;
1192
1193         if (!ndlp->active_rrqs_xri_bitmap)
1194                 goto out;
1195
1196         if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1197                 goto out;
1198
1199         spin_unlock_irqrestore(&phba->hbalock, iflags);
1200         rrq = mempool_alloc(phba->rrq_pool, GFP_ATOMIC);
1201         if (!rrq) {
1202                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1203                                 "3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1204                                 " DID:0x%x Send:%d\n",
1205                                 xritag, rxid, ndlp->nlp_DID, send_rrq);
1206                 return -EINVAL;
1207         }
1208         if (phba->cfg_enable_rrq == 1)
1209                 rrq->send_rrq = send_rrq;
1210         else
1211                 rrq->send_rrq = 0;
1212         rrq->xritag = xritag;
1213         rrq->rrq_stop_time = jiffies +
1214                                 msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1215         rrq->nlp_DID = ndlp->nlp_DID;
1216         rrq->vport = ndlp->vport;
1217         rrq->rxid = rxid;
1218         spin_lock_irqsave(&phba->hbalock, iflags);
1219         empty = list_empty(&phba->active_rrq_list);
1220         list_add_tail(&rrq->list, &phba->active_rrq_list);
1221         phba->hba_flag |= HBA_RRQ_ACTIVE;
1222         if (empty)
1223                 lpfc_worker_wake_up(phba);
1224         spin_unlock_irqrestore(&phba->hbalock, iflags);
1225         return 0;
1226 out:
1227         spin_unlock_irqrestore(&phba->hbalock, iflags);
1228         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1229                         "2921 Can't set rrq active xri:0x%x rxid:0x%x"
1230                         " DID:0x%x Send:%d\n",
1231                         xritag, rxid, ndlp->nlp_DID, send_rrq);
1232         return -EINVAL;
1233 }
1234
1235 /**
1236  * __lpfc_sli_get_els_sglq - Allocates an iocb object from sgl pool
1237  * @phba: Pointer to HBA context object.
1238  * @piocbq: Pointer to the iocbq.
1239  *
1240  * The driver calls this function with either the nvme ls ring lock
1241  * or the fc els ring lock held depending on the iocb usage.  This function
1242  * gets a new driver sglq object from the sglq list. If the list is not empty
1243  * then it is successful, it returns pointer to the newly allocated sglq
1244  * object else it returns NULL.
1245  **/
1246 static struct lpfc_sglq *
1247 __lpfc_sli_get_els_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1248 {
1249         struct list_head *lpfc_els_sgl_list = &phba->sli4_hba.lpfc_els_sgl_list;
1250         struct lpfc_sglq *sglq = NULL;
1251         struct lpfc_sglq *start_sglq = NULL;
1252         struct lpfc_io_buf *lpfc_cmd;
1253         struct lpfc_nodelist *ndlp;
1254         struct lpfc_sli_ring *pring = NULL;
1255         int found = 0;
1256
1257         if (piocbq->iocb_flag & LPFC_IO_NVME_LS)
1258                 pring =  phba->sli4_hba.nvmels_wq->pring;
1259         else
1260                 pring = lpfc_phba_elsring(phba);
1261
1262         lockdep_assert_held(&pring->ring_lock);
1263
1264         if (piocbq->iocb_flag &  LPFC_IO_FCP) {
1265                 lpfc_cmd = (struct lpfc_io_buf *) piocbq->context1;
1266                 ndlp = lpfc_cmd->rdata->pnode;
1267         } else  if ((piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) &&
1268                         !(piocbq->iocb_flag & LPFC_IO_LIBDFC)) {
1269                 ndlp = piocbq->context_un.ndlp;
1270         } else  if (piocbq->iocb_flag & LPFC_IO_LIBDFC) {
1271                 if (piocbq->iocb_flag & LPFC_IO_LOOPBACK)
1272                         ndlp = NULL;
1273                 else
1274                         ndlp = piocbq->context_un.ndlp;
1275         } else {
1276                 ndlp = piocbq->context1;
1277         }
1278
1279         spin_lock(&phba->sli4_hba.sgl_list_lock);
1280         list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
1281         start_sglq = sglq;
1282         while (!found) {
1283                 if (!sglq)
1284                         break;
1285                 if (ndlp && ndlp->active_rrqs_xri_bitmap &&
1286                     test_bit(sglq->sli4_lxritag,
1287                     ndlp->active_rrqs_xri_bitmap)) {
1288                         /* This xri has an rrq outstanding for this DID.
1289                          * put it back in the list and get another xri.
1290                          */
1291                         list_add_tail(&sglq->list, lpfc_els_sgl_list);
1292                         sglq = NULL;
1293                         list_remove_head(lpfc_els_sgl_list, sglq,
1294                                                 struct lpfc_sglq, list);
1295                         if (sglq == start_sglq) {
1296                                 list_add_tail(&sglq->list, lpfc_els_sgl_list);
1297                                 sglq = NULL;
1298                                 break;
1299                         } else
1300                                 continue;
1301                 }
1302                 sglq->ndlp = ndlp;
1303                 found = 1;
1304                 phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1305                 sglq->state = SGL_ALLOCATED;
1306         }
1307         spin_unlock(&phba->sli4_hba.sgl_list_lock);
1308         return sglq;
1309 }
1310
1311 /**
1312  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
1313  * @phba: Pointer to HBA context object.
1314  * @piocbq: Pointer to the iocbq.
1315  *
1316  * This function is called with the sgl_list lock held. This function
1317  * gets a new driver sglq object from the sglq list. If the
1318  * list is not empty then it is successful, it returns pointer to the newly
1319  * allocated sglq object else it returns NULL.
1320  **/
1321 struct lpfc_sglq *
1322 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1323 {
1324         struct list_head *lpfc_nvmet_sgl_list;
1325         struct lpfc_sglq *sglq = NULL;
1326
1327         lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
1328
1329         lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1330
1331         list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1332         if (!sglq)
1333                 return NULL;
1334         phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1335         sglq->state = SGL_ALLOCATED;
1336         return sglq;
1337 }
1338
1339 /**
1340  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1341  * @phba: Pointer to HBA context object.
1342  *
1343  * This function is called with no lock held. This function
1344  * allocates a new driver iocb object from the iocb pool. If the
1345  * allocation is successful, it returns pointer to the newly
1346  * allocated iocb object else it returns NULL.
1347  **/
1348 struct lpfc_iocbq *
1349 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1350 {
1351         struct lpfc_iocbq * iocbq = NULL;
1352         unsigned long iflags;
1353
1354         spin_lock_irqsave(&phba->hbalock, iflags);
1355         iocbq = __lpfc_sli_get_iocbq(phba);
1356         spin_unlock_irqrestore(&phba->hbalock, iflags);
1357         return iocbq;
1358 }
1359
1360 /**
1361  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1362  * @phba: Pointer to HBA context object.
1363  * @iocbq: Pointer to driver iocb object.
1364  *
1365  * This function is called to release the driver iocb object
1366  * to the iocb pool. The iotag in the iocb object
1367  * does not change for each use of the iocb object. This function
1368  * clears all other fields of the iocb object when it is freed.
1369  * The sqlq structure that holds the xritag and phys and virtual
1370  * mappings for the scatter gather list is retrieved from the
1371  * active array of sglq. The get of the sglq pointer also clears
1372  * the entry in the array. If the status of the IO indiactes that
1373  * this IO was aborted then the sglq entry it put on the
1374  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1375  * IO has good status or fails for any other reason then the sglq
1376  * entry is added to the free list (lpfc_els_sgl_list). The hbalock is
1377  *  asserted held in the code path calling this routine.
1378  **/
1379 static void
1380 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1381 {
1382         struct lpfc_sglq *sglq;
1383         size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1384         unsigned long iflag = 0;
1385         struct lpfc_sli_ring *pring;
1386
1387         if (iocbq->sli4_xritag == NO_XRI)
1388                 sglq = NULL;
1389         else
1390                 sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1391
1392
1393         if (sglq)  {
1394                 if (iocbq->iocb_flag & LPFC_IO_NVMET) {
1395                         spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1396                                           iflag);
1397                         sglq->state = SGL_FREED;
1398                         sglq->ndlp = NULL;
1399                         list_add_tail(&sglq->list,
1400                                       &phba->sli4_hba.lpfc_nvmet_sgl_list);
1401                         spin_unlock_irqrestore(
1402                                 &phba->sli4_hba.sgl_list_lock, iflag);
1403                         goto out;
1404                 }
1405
1406                 if ((iocbq->iocb_flag & LPFC_EXCHANGE_BUSY) &&
1407                     (!(unlikely(pci_channel_offline(phba->pcidev)))) &&
1408                     sglq->state != SGL_XRI_ABORTED) {
1409                         spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1410                                           iflag);
1411
1412                         /* Check if we can get a reference on ndlp */
1413                         if (sglq->ndlp && !lpfc_nlp_get(sglq->ndlp))
1414                                 sglq->ndlp = NULL;
1415
1416                         list_add(&sglq->list,
1417                                  &phba->sli4_hba.lpfc_abts_els_sgl_list);
1418                         spin_unlock_irqrestore(
1419                                 &phba->sli4_hba.sgl_list_lock, iflag);
1420                 } else {
1421                         spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1422                                           iflag);
1423                         sglq->state = SGL_FREED;
1424                         sglq->ndlp = NULL;
1425                         list_add_tail(&sglq->list,
1426                                       &phba->sli4_hba.lpfc_els_sgl_list);
1427                         spin_unlock_irqrestore(
1428                                 &phba->sli4_hba.sgl_list_lock, iflag);
1429                         pring = lpfc_phba_elsring(phba);
1430                         /* Check if TXQ queue needs to be serviced */
1431                         if (pring && (!list_empty(&pring->txq)))
1432                                 lpfc_worker_wake_up(phba);
1433                 }
1434         }
1435
1436 out:
1437         /*
1438          * Clean all volatile data fields, preserve iotag and node struct.
1439          */
1440         memset((char *)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1441         iocbq->sli4_lxritag = NO_XRI;
1442         iocbq->sli4_xritag = NO_XRI;
1443         iocbq->iocb_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET | LPFC_IO_CMF |
1444                               LPFC_IO_NVME_LS);
1445         list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1446 }
1447
1448
1449 /**
1450  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1451  * @phba: Pointer to HBA context object.
1452  * @iocbq: Pointer to driver iocb object.
1453  *
1454  * This function is called to release the driver iocb object to the
1455  * iocb pool. The iotag in the iocb object does not change for each
1456  * use of the iocb object. This function clears all other fields of
1457  * the iocb object when it is freed. The hbalock is asserted held in
1458  * the code path calling this routine.
1459  **/
1460 static void
1461 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1462 {
1463         size_t start_clean = offsetof(struct lpfc_iocbq, iocb);
1464
1465         /*
1466          * Clean all volatile data fields, preserve iotag and node struct.
1467          */
1468         memset((char*)iocbq + start_clean, 0, sizeof(*iocbq) - start_clean);
1469         iocbq->sli4_xritag = NO_XRI;
1470         list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1471 }
1472
1473 /**
1474  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1475  * @phba: Pointer to HBA context object.
1476  * @iocbq: Pointer to driver iocb object.
1477  *
1478  * This function is called with hbalock held to release driver
1479  * iocb object to the iocb pool. The iotag in the iocb object
1480  * does not change for each use of the iocb object. This function
1481  * clears all other fields of the iocb object when it is freed.
1482  **/
1483 static void
1484 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1485 {
1486         lockdep_assert_held(&phba->hbalock);
1487
1488         phba->__lpfc_sli_release_iocbq(phba, iocbq);
1489         phba->iocb_cnt--;
1490 }
1491
1492 /**
1493  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1494  * @phba: Pointer to HBA context object.
1495  * @iocbq: Pointer to driver iocb object.
1496  *
1497  * This function is called with no lock held to release the iocb to
1498  * iocb pool.
1499  **/
1500 void
1501 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1502 {
1503         unsigned long iflags;
1504
1505         /*
1506          * Clean all volatile data fields, preserve iotag and node struct.
1507          */
1508         spin_lock_irqsave(&phba->hbalock, iflags);
1509         __lpfc_sli_release_iocbq(phba, iocbq);
1510         spin_unlock_irqrestore(&phba->hbalock, iflags);
1511 }
1512
1513 /**
1514  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1515  * @phba: Pointer to HBA context object.
1516  * @iocblist: List of IOCBs.
1517  * @ulpstatus: ULP status in IOCB command field.
1518  * @ulpWord4: ULP word-4 in IOCB command field.
1519  *
1520  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1521  * on the list by invoking the complete callback function associated with the
1522  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1523  * fields.
1524  **/
1525 void
1526 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1527                       uint32_t ulpstatus, uint32_t ulpWord4)
1528 {
1529         struct lpfc_iocbq *piocb;
1530
1531         while (!list_empty(iocblist)) {
1532                 list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1533                 if (piocb->wqe_cmpl) {
1534                         if (piocb->iocb_flag & LPFC_IO_NVME)
1535                                 lpfc_nvme_cancel_iocb(phba, piocb,
1536                                                       ulpstatus, ulpWord4);
1537                         else
1538                                 lpfc_sli_release_iocbq(phba, piocb);
1539
1540                 } else if (piocb->iocb_cmpl) {
1541                         piocb->iocb.ulpStatus = ulpstatus;
1542                         piocb->iocb.un.ulpWord[4] = ulpWord4;
1543                         (piocb->iocb_cmpl) (phba, piocb, piocb);
1544                 } else {
1545                         lpfc_sli_release_iocbq(phba, piocb);
1546                 }
1547         }
1548         return;
1549 }
1550
1551 /**
1552  * lpfc_sli_iocb_cmd_type - Get the iocb type
1553  * @iocb_cmnd: iocb command code.
1554  *
1555  * This function is called by ring event handler function to get the iocb type.
1556  * This function translates the iocb command to an iocb command type used to
1557  * decide the final disposition of each completed IOCB.
1558  * The function returns
1559  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1560  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1561  * LPFC_ABORT_IOCB   if it is an abort iocb
1562  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1563  *
1564  * The caller is not required to hold any lock.
1565  **/
1566 static lpfc_iocb_type
1567 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1568 {
1569         lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1570
1571         if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1572                 return 0;
1573
1574         switch (iocb_cmnd) {
1575         case CMD_XMIT_SEQUENCE_CR:
1576         case CMD_XMIT_SEQUENCE_CX:
1577         case CMD_XMIT_BCAST_CN:
1578         case CMD_XMIT_BCAST_CX:
1579         case CMD_ELS_REQUEST_CR:
1580         case CMD_ELS_REQUEST_CX:
1581         case CMD_CREATE_XRI_CR:
1582         case CMD_CREATE_XRI_CX:
1583         case CMD_GET_RPI_CN:
1584         case CMD_XMIT_ELS_RSP_CX:
1585         case CMD_GET_RPI_CR:
1586         case CMD_FCP_IWRITE_CR:
1587         case CMD_FCP_IWRITE_CX:
1588         case CMD_FCP_IREAD_CR:
1589         case CMD_FCP_IREAD_CX:
1590         case CMD_FCP_ICMND_CR:
1591         case CMD_FCP_ICMND_CX:
1592         case CMD_FCP_TSEND_CX:
1593         case CMD_FCP_TRSP_CX:
1594         case CMD_FCP_TRECEIVE_CX:
1595         case CMD_FCP_AUTO_TRSP_CX:
1596         case CMD_ADAPTER_MSG:
1597         case CMD_ADAPTER_DUMP:
1598         case CMD_XMIT_SEQUENCE64_CR:
1599         case CMD_XMIT_SEQUENCE64_CX:
1600         case CMD_XMIT_BCAST64_CN:
1601         case CMD_XMIT_BCAST64_CX:
1602         case CMD_ELS_REQUEST64_CR:
1603         case CMD_ELS_REQUEST64_CX:
1604         case CMD_FCP_IWRITE64_CR:
1605         case CMD_FCP_IWRITE64_CX:
1606         case CMD_FCP_IREAD64_CR:
1607         case CMD_FCP_IREAD64_CX:
1608         case CMD_FCP_ICMND64_CR:
1609         case CMD_FCP_ICMND64_CX:
1610         case CMD_FCP_TSEND64_CX:
1611         case CMD_FCP_TRSP64_CX:
1612         case CMD_FCP_TRECEIVE64_CX:
1613         case CMD_GEN_REQUEST64_CR:
1614         case CMD_GEN_REQUEST64_CX:
1615         case CMD_XMIT_ELS_RSP64_CX:
1616         case DSSCMD_IWRITE64_CR:
1617         case DSSCMD_IWRITE64_CX:
1618         case DSSCMD_IREAD64_CR:
1619         case DSSCMD_IREAD64_CX:
1620         case CMD_SEND_FRAME:
1621                 type = LPFC_SOL_IOCB;
1622                 break;
1623         case CMD_ABORT_XRI_CN:
1624         case CMD_ABORT_XRI_CX:
1625         case CMD_CLOSE_XRI_CN:
1626         case CMD_CLOSE_XRI_CX:
1627         case CMD_XRI_ABORTED_CX:
1628         case CMD_ABORT_MXRI64_CN:
1629         case CMD_XMIT_BLS_RSP64_CX:
1630                 type = LPFC_ABORT_IOCB;
1631                 break;
1632         case CMD_RCV_SEQUENCE_CX:
1633         case CMD_RCV_ELS_REQ_CX:
1634         case CMD_RCV_SEQUENCE64_CX:
1635         case CMD_RCV_ELS_REQ64_CX:
1636         case CMD_ASYNC_STATUS:
1637         case CMD_IOCB_RCV_SEQ64_CX:
1638         case CMD_IOCB_RCV_ELS64_CX:
1639         case CMD_IOCB_RCV_CONT64_CX:
1640         case CMD_IOCB_RET_XRI64_CX:
1641                 type = LPFC_UNSOL_IOCB;
1642                 break;
1643         case CMD_IOCB_XMIT_MSEQ64_CR:
1644         case CMD_IOCB_XMIT_MSEQ64_CX:
1645         case CMD_IOCB_RCV_SEQ_LIST64_CX:
1646         case CMD_IOCB_RCV_ELS_LIST64_CX:
1647         case CMD_IOCB_CLOSE_EXTENDED_CN:
1648         case CMD_IOCB_ABORT_EXTENDED_CN:
1649         case CMD_IOCB_RET_HBQE64_CN:
1650         case CMD_IOCB_FCP_IBIDIR64_CR:
1651         case CMD_IOCB_FCP_IBIDIR64_CX:
1652         case CMD_IOCB_FCP_ITASKMGT64_CX:
1653         case CMD_IOCB_LOGENTRY_CN:
1654         case CMD_IOCB_LOGENTRY_ASYNC_CN:
1655                 printk("%s - Unhandled SLI-3 Command x%x\n",
1656                                 __func__, iocb_cmnd);
1657                 type = LPFC_UNKNOWN_IOCB;
1658                 break;
1659         default:
1660                 type = LPFC_UNKNOWN_IOCB;
1661                 break;
1662         }
1663
1664         return type;
1665 }
1666
1667 /**
1668  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1669  * @phba: Pointer to HBA context object.
1670  *
1671  * This function is called from SLI initialization code
1672  * to configure every ring of the HBA's SLI interface. The
1673  * caller is not required to hold any lock. This function issues
1674  * a config_ring mailbox command for each ring.
1675  * This function returns zero if successful else returns a negative
1676  * error code.
1677  **/
1678 static int
1679 lpfc_sli_ring_map(struct lpfc_hba *phba)
1680 {
1681         struct lpfc_sli *psli = &phba->sli;
1682         LPFC_MBOXQ_t *pmb;
1683         MAILBOX_t *pmbox;
1684         int i, rc, ret = 0;
1685
1686         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1687         if (!pmb)
1688                 return -ENOMEM;
1689         pmbox = &pmb->u.mb;
1690         phba->link_state = LPFC_INIT_MBX_CMDS;
1691         for (i = 0; i < psli->num_rings; i++) {
1692                 lpfc_config_ring(phba, i, pmb);
1693                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1694                 if (rc != MBX_SUCCESS) {
1695                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1696                                         "0446 Adapter failed to init (%d), "
1697                                         "mbxCmd x%x CFG_RING, mbxStatus x%x, "
1698                                         "ring %d\n",
1699                                         rc, pmbox->mbxCommand,
1700                                         pmbox->mbxStatus, i);
1701                         phba->link_state = LPFC_HBA_ERROR;
1702                         ret = -ENXIO;
1703                         break;
1704                 }
1705         }
1706         mempool_free(pmb, phba->mbox_mem_pool);
1707         return ret;
1708 }
1709
1710 /**
1711  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1712  * @phba: Pointer to HBA context object.
1713  * @pring: Pointer to driver SLI ring object.
1714  * @piocb: Pointer to the driver iocb object.
1715  *
1716  * The driver calls this function with the hbalock held for SLI3 ports or
1717  * the ring lock held for SLI4 ports. The function adds the
1718  * new iocb to txcmplq of the given ring. This function always returns
1719  * 0. If this function is called for ELS ring, this function checks if
1720  * there is a vport associated with the ELS command. This function also
1721  * starts els_tmofunc timer if this is an ELS command.
1722  **/
1723 static int
1724 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1725                         struct lpfc_iocbq *piocb)
1726 {
1727         if (phba->sli_rev == LPFC_SLI_REV4)
1728                 lockdep_assert_held(&pring->ring_lock);
1729         else
1730                 lockdep_assert_held(&phba->hbalock);
1731
1732         BUG_ON(!piocb);
1733
1734         list_add_tail(&piocb->list, &pring->txcmplq);
1735         piocb->iocb_flag |= LPFC_IO_ON_TXCMPLQ;
1736         pring->txcmplq_cnt++;
1737
1738         if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1739            (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
1740            (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
1741                 BUG_ON(!piocb->vport);
1742                 if (!(piocb->vport->load_flag & FC_UNLOADING))
1743                         mod_timer(&piocb->vport->els_tmofunc,
1744                                   jiffies +
1745                                   msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1746         }
1747
1748         return 0;
1749 }
1750
1751 /**
1752  * lpfc_sli_ringtx_get - Get first element of the txq
1753  * @phba: Pointer to HBA context object.
1754  * @pring: Pointer to driver SLI ring object.
1755  *
1756  * This function is called with hbalock held to get next
1757  * iocb in txq of the given ring. If there is any iocb in
1758  * the txq, the function returns first iocb in the list after
1759  * removing the iocb from the list, else it returns NULL.
1760  **/
1761 struct lpfc_iocbq *
1762 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1763 {
1764         struct lpfc_iocbq *cmd_iocb;
1765
1766         lockdep_assert_held(&phba->hbalock);
1767
1768         list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1769         return cmd_iocb;
1770 }
1771
1772 /**
1773  * lpfc_cmf_sync_cmpl - Process a CMF_SYNC_WQE cmpl
1774  * @phba: Pointer to HBA context object.
1775  * @cmdiocb: Pointer to driver command iocb object.
1776  * @cmf_cmpl: Pointer to completed WCQE.
1777  *
1778  * This routine will inform the driver of any BW adjustments we need
1779  * to make. These changes will be picked up during the next CMF
1780  * timer interrupt. In addition, any BW changes will be logged
1781  * with LOG_CGN_MGMT.
1782  **/
1783 static void
1784 lpfc_cmf_sync_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
1785                    struct lpfc_wcqe_complete *cmf_cmpl)
1786 {
1787         union lpfc_wqe128 *wqe;
1788         uint32_t status, info;
1789         uint64_t bw, bwdif, slop;
1790         uint64_t pcent, bwpcent;
1791         int asig, afpin, sigcnt, fpincnt;
1792         int wsigmax, wfpinmax, cg, tdp;
1793         char *s;
1794
1795         /* First check for error */
1796         status = bf_get(lpfc_wcqe_c_status, cmf_cmpl);
1797         if (status) {
1798                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1799                                 "6211 CMF_SYNC_WQE Error "
1800                                 "req_tag x%x status x%x hwstatus x%x "
1801                                 "tdatap x%x parm x%x\n",
1802                                 bf_get(lpfc_wcqe_c_request_tag, cmf_cmpl),
1803                                 bf_get(lpfc_wcqe_c_status, cmf_cmpl),
1804                                 bf_get(lpfc_wcqe_c_hw_status, cmf_cmpl),
1805                                 cmf_cmpl->total_data_placed,
1806                                 cmf_cmpl->parameter);
1807                 goto out;
1808         }
1809
1810         /* Gather congestion information on a successful cmpl */
1811         info = cmf_cmpl->parameter;
1812         phba->cmf_active_info = info;
1813
1814         /* See if firmware info count is valid or has changed */
1815         if (info > LPFC_MAX_CMF_INFO || phba->cmf_info_per_interval == info)
1816                 info = 0;
1817         else
1818                 phba->cmf_info_per_interval = info;
1819
1820         tdp = bf_get(lpfc_wcqe_c_cmf_bw, cmf_cmpl);
1821         cg = bf_get(lpfc_wcqe_c_cmf_cg, cmf_cmpl);
1822
1823         /* Get BW requirement from firmware */
1824         bw = (uint64_t)tdp * LPFC_CMF_BLK_SIZE;
1825         if (!bw) {
1826                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1827                                 "6212 CMF_SYNC_WQE x%x: NULL bw\n",
1828                                 bf_get(lpfc_wcqe_c_request_tag, cmf_cmpl));
1829                 goto out;
1830         }
1831
1832         /* Gather information needed for logging if a BW change is required */
1833         wqe = &cmdiocb->wqe;
1834         asig = bf_get(cmf_sync_asig, &wqe->cmf_sync);
1835         afpin = bf_get(cmf_sync_afpin, &wqe->cmf_sync);
1836         fpincnt = bf_get(cmf_sync_wfpincnt, &wqe->cmf_sync);
1837         sigcnt = bf_get(cmf_sync_wsigcnt, &wqe->cmf_sync);
1838         if (phba->cmf_max_bytes_per_interval != bw ||
1839             (asig || afpin || sigcnt || fpincnt)) {
1840                 /* Are we increasing or decreasing BW */
1841                 if (phba->cmf_max_bytes_per_interval <  bw) {
1842                         bwdif = bw - phba->cmf_max_bytes_per_interval;
1843                         s = "Increase";
1844                 } else {
1845                         bwdif = phba->cmf_max_bytes_per_interval - bw;
1846                         s = "Decrease";
1847                 }
1848
1849                 /* What is the change percentage */
1850                 slop = div_u64(phba->cmf_link_byte_count, 200); /*For rounding*/
1851                 pcent = div64_u64(bwdif * 100 + slop,
1852                                   phba->cmf_link_byte_count);
1853                 bwpcent = div64_u64(bw * 100 + slop,
1854                                     phba->cmf_link_byte_count);
1855                 if (asig) {
1856                         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1857                                         "6237 BW Threshold %lld%% (%lld): "
1858                                         "%lld%% %s: Signal Alarm: cg:%d "
1859                                         "Info:%u\n",
1860                                         bwpcent, bw, pcent, s, cg,
1861                                         phba->cmf_active_info);
1862                 } else if (afpin) {
1863                         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1864                                         "6238 BW Threshold %lld%% (%lld): "
1865                                         "%lld%% %s: FPIN Alarm: cg:%d "
1866                                         "Info:%u\n",
1867                                         bwpcent, bw, pcent, s, cg,
1868                                         phba->cmf_active_info);
1869                 } else if (sigcnt) {
1870                         wsigmax = bf_get(cmf_sync_wsigmax, &wqe->cmf_sync);
1871                         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1872                                         "6239 BW Threshold %lld%% (%lld): "
1873                                         "%lld%% %s: Signal Warning: "
1874                                         "Cnt %d Max %d: cg:%d Info:%u\n",
1875                                         bwpcent, bw, pcent, s, sigcnt,
1876                                         wsigmax, cg, phba->cmf_active_info);
1877                 } else if (fpincnt) {
1878                         wfpinmax = bf_get(cmf_sync_wfpinmax, &wqe->cmf_sync);
1879                         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1880                                         "6240 BW Threshold %lld%% (%lld): "
1881                                         "%lld%% %s: FPIN Warning: "
1882                                         "Cnt %d Max %d: cg:%d Info:%u\n",
1883                                         bwpcent, bw, pcent, s, fpincnt,
1884                                         wfpinmax, cg, phba->cmf_active_info);
1885                 } else {
1886                         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1887                                         "6241 BW Threshold %lld%% (%lld): "
1888                                         "CMF %lld%% %s: cg:%d Info:%u\n",
1889                                         bwpcent, bw, pcent, s, cg,
1890                                         phba->cmf_active_info);
1891                 }
1892         } else if (info) {
1893                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1894                                 "6246 Info Threshold %u\n", info);
1895         }
1896
1897         /* Save BW change to be picked up during next timer interrupt */
1898         phba->cmf_last_sync_bw = bw;
1899 out:
1900         lpfc_sli_release_iocbq(phba, cmdiocb);
1901 }
1902
1903 /**
1904  * lpfc_issue_cmf_sync_wqe - Issue a CMF_SYNC_WQE
1905  * @phba: Pointer to HBA context object.
1906  * @ms:   ms to set in WQE interval, 0 means use init op
1907  * @total: Total rcv bytes for this interval
1908  *
1909  * This routine is called every CMF timer interrupt. Its purpose is
1910  * to issue a CMF_SYNC_WQE to the firmware to inform it of any events
1911  * that may indicate we have congestion (FPINs or Signals). Upon
1912  * completion, the firmware will indicate any BW restrictions the
1913  * driver may need to take.
1914  **/
1915 int
1916 lpfc_issue_cmf_sync_wqe(struct lpfc_hba *phba, u32 ms, u64 total)
1917 {
1918         union lpfc_wqe128 *wqe;
1919         struct lpfc_iocbq *sync_buf;
1920         unsigned long iflags;
1921         u32 ret_val;
1922         u32 atot, wtot, max;
1923
1924         /* First address any alarm / warning activity */
1925         atot = atomic_xchg(&phba->cgn_sync_alarm_cnt, 0);
1926         wtot = atomic_xchg(&phba->cgn_sync_warn_cnt, 0);
1927
1928         /* ONLY Managed mode will send the CMF_SYNC_WQE to the HBA */
1929         if (phba->cmf_active_mode != LPFC_CFG_MANAGED ||
1930             phba->link_state == LPFC_LINK_DOWN)
1931                 return 0;
1932
1933         spin_lock_irqsave(&phba->hbalock, iflags);
1934         sync_buf = __lpfc_sli_get_iocbq(phba);
1935         if (!sync_buf) {
1936                 lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
1937                                 "6213 No available WQEs for CMF_SYNC_WQE\n");
1938                 ret_val = ENOMEM;
1939                 goto out_unlock;
1940         }
1941
1942         wqe = &sync_buf->wqe;
1943
1944         /* WQEs are reused.  Clear stale data and set key fields to zero */
1945         memset(wqe, 0, sizeof(*wqe));
1946
1947         /* If this is the very first CMF_SYNC_WQE, issue an init operation */
1948         if (!ms) {
1949                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1950                                 "6441 CMF Init %d - CMF_SYNC_WQE\n",
1951                                 phba->fc_eventTag);
1952                 bf_set(cmf_sync_op, &wqe->cmf_sync, 1); /* 1=init */
1953                 bf_set(cmf_sync_interval, &wqe->cmf_sync, LPFC_CMF_INTERVAL);
1954                 goto initpath;
1955         }
1956
1957         bf_set(cmf_sync_op, &wqe->cmf_sync, 0); /* 0=recalc */
1958         bf_set(cmf_sync_interval, &wqe->cmf_sync, ms);
1959
1960         /* Check for alarms / warnings */
1961         if (atot) {
1962                 if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1963                         /* We hit an Signal alarm condition */
1964                         bf_set(cmf_sync_asig, &wqe->cmf_sync, 1);
1965                 } else {
1966                         /* We hit a FPIN alarm condition */
1967                         bf_set(cmf_sync_afpin, &wqe->cmf_sync, 1);
1968                 }
1969         } else if (wtot) {
1970                 if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
1971                     phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1972                         /* We hit an Signal warning condition */
1973                         max = LPFC_SEC_TO_MSEC / lpfc_fabric_cgn_frequency *
1974                                 lpfc_acqe_cgn_frequency;
1975                         bf_set(cmf_sync_wsigmax, &wqe->cmf_sync, max);
1976                         bf_set(cmf_sync_wsigcnt, &wqe->cmf_sync, wtot);
1977                 } else {
1978                         /* We hit a FPIN warning condition */
1979                         bf_set(cmf_sync_wfpinmax, &wqe->cmf_sync, 1);
1980                         bf_set(cmf_sync_wfpincnt, &wqe->cmf_sync, 1);
1981                 }
1982         }
1983
1984         /* Update total read blocks during previous timer interval */
1985         wqe->cmf_sync.read_bytes = (u32)(total / LPFC_CMF_BLK_SIZE);
1986
1987 initpath:
1988         bf_set(cmf_sync_ver, &wqe->cmf_sync, LPFC_CMF_SYNC_VER);
1989         wqe->cmf_sync.event_tag = phba->fc_eventTag;
1990         bf_set(cmf_sync_cmnd, &wqe->cmf_sync, CMD_CMF_SYNC_WQE);
1991
1992         /* Setup reqtag to match the wqe completion. */
1993         bf_set(cmf_sync_reqtag, &wqe->cmf_sync, sync_buf->iotag);
1994
1995         bf_set(cmf_sync_qosd, &wqe->cmf_sync, 1);
1996
1997         bf_set(cmf_sync_cmd_type, &wqe->cmf_sync, CMF_SYNC_COMMAND);
1998         bf_set(cmf_sync_wqec, &wqe->cmf_sync, 1);
1999         bf_set(cmf_sync_cqid, &wqe->cmf_sync, LPFC_WQE_CQ_ID_DEFAULT);
2000
2001         sync_buf->vport = phba->pport;
2002         sync_buf->wqe_cmpl = lpfc_cmf_sync_cmpl;
2003         sync_buf->iocb_cmpl = NULL;
2004         sync_buf->context1 = NULL;
2005         sync_buf->context2 = NULL;
2006         sync_buf->context3 = NULL;
2007         sync_buf->sli4_xritag = NO_XRI;
2008
2009         sync_buf->iocb_flag |= LPFC_IO_CMF;
2010         ret_val = lpfc_sli4_issue_wqe(phba, &phba->sli4_hba.hdwq[0], sync_buf);
2011         if (ret_val)
2012                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
2013                                 "6214 Cannot issue CMF_SYNC_WQE: x%x\n",
2014                                 ret_val);
2015 out_unlock:
2016         spin_unlock_irqrestore(&phba->hbalock, iflags);
2017         return ret_val;
2018 }
2019
2020 /**
2021  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
2022  * @phba: Pointer to HBA context object.
2023  * @pring: Pointer to driver SLI ring object.
2024  *
2025  * This function is called with hbalock held and the caller must post the
2026  * iocb without releasing the lock. If the caller releases the lock,
2027  * iocb slot returned by the function is not guaranteed to be available.
2028  * The function returns pointer to the next available iocb slot if there
2029  * is available slot in the ring, else it returns NULL.
2030  * If the get index of the ring is ahead of the put index, the function
2031  * will post an error attention event to the worker thread to take the
2032  * HBA to offline state.
2033  **/
2034 static IOCB_t *
2035 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2036 {
2037         struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2038         uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
2039
2040         lockdep_assert_held(&phba->hbalock);
2041
2042         if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
2043            (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
2044                 pring->sli.sli3.next_cmdidx = 0;
2045
2046         if (unlikely(pring->sli.sli3.local_getidx ==
2047                 pring->sli.sli3.next_cmdidx)) {
2048
2049                 pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
2050
2051                 if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
2052                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2053                                         "0315 Ring %d issue: portCmdGet %d "
2054                                         "is bigger than cmd ring %d\n",
2055                                         pring->ringno,
2056                                         pring->sli.sli3.local_getidx,
2057                                         max_cmd_idx);
2058
2059                         phba->link_state = LPFC_HBA_ERROR;
2060                         /*
2061                          * All error attention handlers are posted to
2062                          * worker thread
2063                          */
2064                         phba->work_ha |= HA_ERATT;
2065                         phba->work_hs = HS_FFER3;
2066
2067                         lpfc_worker_wake_up(phba);
2068
2069                         return NULL;
2070                 }
2071
2072                 if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
2073                         return NULL;
2074         }
2075
2076         return lpfc_cmd_iocb(phba, pring);
2077 }
2078
2079 /**
2080  * lpfc_sli_next_iotag - Get an iotag for the iocb
2081  * @phba: Pointer to HBA context object.
2082  * @iocbq: Pointer to driver iocb object.
2083  *
2084  * This function gets an iotag for the iocb. If there is no unused iotag and
2085  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
2086  * array and assigns a new iotag.
2087  * The function returns the allocated iotag if successful, else returns zero.
2088  * Zero is not a valid iotag.
2089  * The caller is not required to hold any lock.
2090  **/
2091 uint16_t
2092 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
2093 {
2094         struct lpfc_iocbq **new_arr;
2095         struct lpfc_iocbq **old_arr;
2096         size_t new_len;
2097         struct lpfc_sli *psli = &phba->sli;
2098         uint16_t iotag;
2099
2100         spin_lock_irq(&phba->hbalock);
2101         iotag = psli->last_iotag;
2102         if(++iotag < psli->iocbq_lookup_len) {
2103                 psli->last_iotag = iotag;
2104                 psli->iocbq_lookup[iotag] = iocbq;
2105                 spin_unlock_irq(&phba->hbalock);
2106                 iocbq->iotag = iotag;
2107                 return iotag;
2108         } else if (psli->iocbq_lookup_len < (0xffff
2109                                            - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
2110                 new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
2111                 spin_unlock_irq(&phba->hbalock);
2112                 new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
2113                                   GFP_KERNEL);
2114                 if (new_arr) {
2115                         spin_lock_irq(&phba->hbalock);
2116                         old_arr = psli->iocbq_lookup;
2117                         if (new_len <= psli->iocbq_lookup_len) {
2118                                 /* highly unprobable case */
2119                                 kfree(new_arr);
2120                                 iotag = psli->last_iotag;
2121                                 if(++iotag < psli->iocbq_lookup_len) {
2122                                         psli->last_iotag = iotag;
2123                                         psli->iocbq_lookup[iotag] = iocbq;
2124                                         spin_unlock_irq(&phba->hbalock);
2125                                         iocbq->iotag = iotag;
2126                                         return iotag;
2127                                 }
2128                                 spin_unlock_irq(&phba->hbalock);
2129                                 return 0;
2130                         }
2131                         if (psli->iocbq_lookup)
2132                                 memcpy(new_arr, old_arr,
2133                                        ((psli->last_iotag  + 1) *
2134                                         sizeof (struct lpfc_iocbq *)));
2135                         psli->iocbq_lookup = new_arr;
2136                         psli->iocbq_lookup_len = new_len;
2137                         psli->last_iotag = iotag;
2138                         psli->iocbq_lookup[iotag] = iocbq;
2139                         spin_unlock_irq(&phba->hbalock);
2140                         iocbq->iotag = iotag;
2141                         kfree(old_arr);
2142                         return iotag;
2143                 }
2144         } else
2145                 spin_unlock_irq(&phba->hbalock);
2146
2147         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2148                         "0318 Failed to allocate IOTAG.last IOTAG is %d\n",
2149                         psli->last_iotag);
2150
2151         return 0;
2152 }
2153
2154 /**
2155  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
2156  * @phba: Pointer to HBA context object.
2157  * @pring: Pointer to driver SLI ring object.
2158  * @iocb: Pointer to iocb slot in the ring.
2159  * @nextiocb: Pointer to driver iocb object which need to be
2160  *            posted to firmware.
2161  *
2162  * This function is called to post a new iocb to the firmware. This
2163  * function copies the new iocb to ring iocb slot and updates the
2164  * ring pointers. It adds the new iocb to txcmplq if there is
2165  * a completion call back for this iocb else the function will free the
2166  * iocb object.  The hbalock is asserted held in the code path calling
2167  * this routine.
2168  **/
2169 static void
2170 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2171                 IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
2172 {
2173         /*
2174          * Set up an iotag
2175          */
2176         nextiocb->iocb.ulpIoTag = (nextiocb->iocb_cmpl) ? nextiocb->iotag : 0;
2177
2178
2179         if (pring->ringno == LPFC_ELS_RING) {
2180                 lpfc_debugfs_slow_ring_trc(phba,
2181                         "IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
2182                         *(((uint32_t *) &nextiocb->iocb) + 4),
2183                         *(((uint32_t *) &nextiocb->iocb) + 6),
2184                         *(((uint32_t *) &nextiocb->iocb) + 7));
2185         }
2186
2187         /*
2188          * Issue iocb command to adapter
2189          */
2190         lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
2191         wmb();
2192         pring->stats.iocb_cmd++;
2193
2194         /*
2195          * If there is no completion routine to call, we can release the
2196          * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
2197          * that have no rsp ring completion, iocb_cmpl MUST be NULL.
2198          */
2199         if (nextiocb->iocb_cmpl)
2200                 lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
2201         else
2202                 __lpfc_sli_release_iocbq(phba, nextiocb);
2203
2204         /*
2205          * Let the HBA know what IOCB slot will be the next one the
2206          * driver will put a command into.
2207          */
2208         pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
2209         writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
2210 }
2211
2212 /**
2213  * lpfc_sli_update_full_ring - Update the chip attention register
2214  * @phba: Pointer to HBA context object.
2215  * @pring: Pointer to driver SLI ring object.
2216  *
2217  * The caller is not required to hold any lock for calling this function.
2218  * This function updates the chip attention bits for the ring to inform firmware
2219  * that there are pending work to be done for this ring and requests an
2220  * interrupt when there is space available in the ring. This function is
2221  * called when the driver is unable to post more iocbs to the ring due
2222  * to unavailability of space in the ring.
2223  **/
2224 static void
2225 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2226 {
2227         int ringno = pring->ringno;
2228
2229         pring->flag |= LPFC_CALL_RING_AVAILABLE;
2230
2231         wmb();
2232
2233         /*
2234          * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
2235          * The HBA will tell us when an IOCB entry is available.
2236          */
2237         writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
2238         readl(phba->CAregaddr); /* flush */
2239
2240         pring->stats.iocb_cmd_full++;
2241 }
2242
2243 /**
2244  * lpfc_sli_update_ring - Update chip attention register
2245  * @phba: Pointer to HBA context object.
2246  * @pring: Pointer to driver SLI ring object.
2247  *
2248  * This function updates the chip attention register bit for the
2249  * given ring to inform HBA that there is more work to be done
2250  * in this ring. The caller is not required to hold any lock.
2251  **/
2252 static void
2253 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2254 {
2255         int ringno = pring->ringno;
2256
2257         /*
2258          * Tell the HBA that there is work to do in this ring.
2259          */
2260         if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
2261                 wmb();
2262                 writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
2263                 readl(phba->CAregaddr); /* flush */
2264         }
2265 }
2266
2267 /**
2268  * lpfc_sli_resume_iocb - Process iocbs in the txq
2269  * @phba: Pointer to HBA context object.
2270  * @pring: Pointer to driver SLI ring object.
2271  *
2272  * This function is called with hbalock held to post pending iocbs
2273  * in the txq to the firmware. This function is called when driver
2274  * detects space available in the ring.
2275  **/
2276 static void
2277 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2278 {
2279         IOCB_t *iocb;
2280         struct lpfc_iocbq *nextiocb;
2281
2282         lockdep_assert_held(&phba->hbalock);
2283
2284         /*
2285          * Check to see if:
2286          *  (a) there is anything on the txq to send
2287          *  (b) link is up
2288          *  (c) link attention events can be processed (fcp ring only)
2289          *  (d) IOCB processing is not blocked by the outstanding mbox command.
2290          */
2291
2292         if (lpfc_is_link_up(phba) &&
2293             (!list_empty(&pring->txq)) &&
2294             (pring->ringno != LPFC_FCP_RING ||
2295              phba->sli.sli_flag & LPFC_PROCESS_LA)) {
2296
2297                 while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
2298                        (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
2299                         lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
2300
2301                 if (iocb)
2302                         lpfc_sli_update_ring(phba, pring);
2303                 else
2304                         lpfc_sli_update_full_ring(phba, pring);
2305         }
2306
2307         return;
2308 }
2309
2310 /**
2311  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
2312  * @phba: Pointer to HBA context object.
2313  * @hbqno: HBQ number.
2314  *
2315  * This function is called with hbalock held to get the next
2316  * available slot for the given HBQ. If there is free slot
2317  * available for the HBQ it will return pointer to the next available
2318  * HBQ entry else it will return NULL.
2319  **/
2320 static struct lpfc_hbq_entry *
2321 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
2322 {
2323         struct hbq_s *hbqp = &phba->hbqs[hbqno];
2324
2325         lockdep_assert_held(&phba->hbalock);
2326
2327         if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
2328             ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
2329                 hbqp->next_hbqPutIdx = 0;
2330
2331         if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
2332                 uint32_t raw_index = phba->hbq_get[hbqno];
2333                 uint32_t getidx = le32_to_cpu(raw_index);
2334
2335                 hbqp->local_hbqGetIdx = getidx;
2336
2337                 if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
2338                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2339                                         "1802 HBQ %d: local_hbqGetIdx "
2340                                         "%u is > than hbqp->entry_count %u\n",
2341                                         hbqno, hbqp->local_hbqGetIdx,
2342                                         hbqp->entry_count);
2343
2344                         phba->link_state = LPFC_HBA_ERROR;
2345                         return NULL;
2346                 }
2347
2348                 if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
2349                         return NULL;
2350         }
2351
2352         return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
2353                         hbqp->hbqPutIdx;
2354 }
2355
2356 /**
2357  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
2358  * @phba: Pointer to HBA context object.
2359  *
2360  * This function is called with no lock held to free all the
2361  * hbq buffers while uninitializing the SLI interface. It also
2362  * frees the HBQ buffers returned by the firmware but not yet
2363  * processed by the upper layers.
2364  **/
2365 void
2366 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
2367 {
2368         struct lpfc_dmabuf *dmabuf, *next_dmabuf;
2369         struct hbq_dmabuf *hbq_buf;
2370         unsigned long flags;
2371         int i, hbq_count;
2372
2373         hbq_count = lpfc_sli_hbq_count();
2374         /* Return all memory used by all HBQs */
2375         spin_lock_irqsave(&phba->hbalock, flags);
2376         for (i = 0; i < hbq_count; ++i) {
2377                 list_for_each_entry_safe(dmabuf, next_dmabuf,
2378                                 &phba->hbqs[i].hbq_buffer_list, list) {
2379                         hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2380                         list_del(&hbq_buf->dbuf.list);
2381                         (phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2382                 }
2383                 phba->hbqs[i].buffer_count = 0;
2384         }
2385
2386         /* Mark the HBQs not in use */
2387         phba->hbq_in_use = 0;
2388         spin_unlock_irqrestore(&phba->hbalock, flags);
2389 }
2390
2391 /**
2392  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2393  * @phba: Pointer to HBA context object.
2394  * @hbqno: HBQ number.
2395  * @hbq_buf: Pointer to HBQ buffer.
2396  *
2397  * This function is called with the hbalock held to post a
2398  * hbq buffer to the firmware. If the function finds an empty
2399  * slot in the HBQ, it will post the buffer. The function will return
2400  * pointer to the hbq entry if it successfully post the buffer
2401  * else it will return NULL.
2402  **/
2403 static int
2404 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2405                          struct hbq_dmabuf *hbq_buf)
2406 {
2407         lockdep_assert_held(&phba->hbalock);
2408         return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2409 }
2410
2411 /**
2412  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2413  * @phba: Pointer to HBA context object.
2414  * @hbqno: HBQ number.
2415  * @hbq_buf: Pointer to HBQ buffer.
2416  *
2417  * This function is called with the hbalock held to post a hbq buffer to the
2418  * firmware. If the function finds an empty slot in the HBQ, it will post the
2419  * buffer and place it on the hbq_buffer_list. The function will return zero if
2420  * it successfully post the buffer else it will return an error.
2421  **/
2422 static int
2423 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2424                             struct hbq_dmabuf *hbq_buf)
2425 {
2426         struct lpfc_hbq_entry *hbqe;
2427         dma_addr_t physaddr = hbq_buf->dbuf.phys;
2428
2429         lockdep_assert_held(&phba->hbalock);
2430         /* Get next HBQ entry slot to use */
2431         hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2432         if (hbqe) {
2433                 struct hbq_s *hbqp = &phba->hbqs[hbqno];
2434
2435                 hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2436                 hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2437                 hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2438                 hbqe->bde.tus.f.bdeFlags = 0;
2439                 hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2440                 hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2441                                 /* Sync SLIM */
2442                 hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2443                 writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2444                                 /* flush */
2445                 readl(phba->hbq_put + hbqno);
2446                 list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2447                 return 0;
2448         } else
2449                 return -ENOMEM;
2450 }
2451
2452 /**
2453  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2454  * @phba: Pointer to HBA context object.
2455  * @hbqno: HBQ number.
2456  * @hbq_buf: Pointer to HBQ buffer.
2457  *
2458  * This function is called with the hbalock held to post an RQE to the SLI4
2459  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2460  * the hbq_buffer_list and return zero, otherwise it will return an error.
2461  **/
2462 static int
2463 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2464                             struct hbq_dmabuf *hbq_buf)
2465 {
2466         int rc;
2467         struct lpfc_rqe hrqe;
2468         struct lpfc_rqe drqe;
2469         struct lpfc_queue *hrq;
2470         struct lpfc_queue *drq;
2471
2472         if (hbqno != LPFC_ELS_HBQ)
2473                 return 1;
2474         hrq = phba->sli4_hba.hdr_rq;
2475         drq = phba->sli4_hba.dat_rq;
2476
2477         lockdep_assert_held(&phba->hbalock);
2478         hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2479         hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2480         drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2481         drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2482         rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2483         if (rc < 0)
2484                 return rc;
2485         hbq_buf->tag = (rc | (hbqno << 16));
2486         list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2487         return 0;
2488 }
2489
2490 /* HBQ for ELS and CT traffic. */
2491 static struct lpfc_hbq_init lpfc_els_hbq = {
2492         .rn = 1,
2493         .entry_count = 256,
2494         .mask_count = 0,
2495         .profile = 0,
2496         .ring_mask = (1 << LPFC_ELS_RING),
2497         .buffer_count = 0,
2498         .init_count = 40,
2499         .add_count = 40,
2500 };
2501
2502 /* Array of HBQs */
2503 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2504         &lpfc_els_hbq,
2505 };
2506
2507 /**
2508  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2509  * @phba: Pointer to HBA context object.
2510  * @hbqno: HBQ number.
2511  * @count: Number of HBQ buffers to be posted.
2512  *
2513  * This function is called with no lock held to post more hbq buffers to the
2514  * given HBQ. The function returns the number of HBQ buffers successfully
2515  * posted.
2516  **/
2517 static int
2518 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2519 {
2520         uint32_t i, posted = 0;
2521         unsigned long flags;
2522         struct hbq_dmabuf *hbq_buffer;
2523         LIST_HEAD(hbq_buf_list);
2524         if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2525                 return 0;
2526
2527         if ((phba->hbqs[hbqno].buffer_count + count) >
2528             lpfc_hbq_defs[hbqno]->entry_count)
2529                 count = lpfc_hbq_defs[hbqno]->entry_count -
2530                                         phba->hbqs[hbqno].buffer_count;
2531         if (!count)
2532                 return 0;
2533         /* Allocate HBQ entries */
2534         for (i = 0; i < count; i++) {
2535                 hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2536                 if (!hbq_buffer)
2537                         break;
2538                 list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2539         }
2540         /* Check whether HBQ is still in use */
2541         spin_lock_irqsave(&phba->hbalock, flags);
2542         if (!phba->hbq_in_use)
2543                 goto err;
2544         while (!list_empty(&hbq_buf_list)) {
2545                 list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2546                                  dbuf.list);
2547                 hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2548                                       (hbqno << 16));
2549                 if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2550                         phba->hbqs[hbqno].buffer_count++;
2551                         posted++;
2552                 } else
2553                         (phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2554         }
2555         spin_unlock_irqrestore(&phba->hbalock, flags);
2556         return posted;
2557 err:
2558         spin_unlock_irqrestore(&phba->hbalock, flags);
2559         while (!list_empty(&hbq_buf_list)) {
2560                 list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2561                                  dbuf.list);
2562                 (phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2563         }
2564         return 0;
2565 }
2566
2567 /**
2568  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2569  * @phba: Pointer to HBA context object.
2570  * @qno: HBQ number.
2571  *
2572  * This function posts more buffers to the HBQ. This function
2573  * is called with no lock held. The function returns the number of HBQ entries
2574  * successfully allocated.
2575  **/
2576 int
2577 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2578 {
2579         if (phba->sli_rev == LPFC_SLI_REV4)
2580                 return 0;
2581         else
2582                 return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2583                                          lpfc_hbq_defs[qno]->add_count);
2584 }
2585
2586 /**
2587  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2588  * @phba: Pointer to HBA context object.
2589  * @qno:  HBQ queue number.
2590  *
2591  * This function is called from SLI initialization code path with
2592  * no lock held to post initial HBQ buffers to firmware. The
2593  * function returns the number of HBQ entries successfully allocated.
2594  **/
2595 static int
2596 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2597 {
2598         if (phba->sli_rev == LPFC_SLI_REV4)
2599                 return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2600                                         lpfc_hbq_defs[qno]->entry_count);
2601         else
2602                 return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2603                                          lpfc_hbq_defs[qno]->init_count);
2604 }
2605
2606 /*
2607  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2608  *
2609  * This function removes the first hbq buffer on an hbq list and returns a
2610  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2611  **/
2612 static struct hbq_dmabuf *
2613 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2614 {
2615         struct lpfc_dmabuf *d_buf;
2616
2617         list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2618         if (!d_buf)
2619                 return NULL;
2620         return container_of(d_buf, struct hbq_dmabuf, dbuf);
2621 }
2622
2623 /**
2624  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2625  * @phba: Pointer to HBA context object.
2626  * @hrq: HBQ number.
2627  *
2628  * This function removes the first RQ buffer on an RQ buffer list and returns a
2629  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2630  **/
2631 static struct rqb_dmabuf *
2632 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2633 {
2634         struct lpfc_dmabuf *h_buf;
2635         struct lpfc_rqb *rqbp;
2636
2637         rqbp = hrq->rqbp;
2638         list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2639                          struct lpfc_dmabuf, list);
2640         if (!h_buf)
2641                 return NULL;
2642         rqbp->buffer_count--;
2643         return container_of(h_buf, struct rqb_dmabuf, hbuf);
2644 }
2645
2646 /**
2647  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2648  * @phba: Pointer to HBA context object.
2649  * @tag: Tag of the hbq buffer.
2650  *
2651  * This function searches for the hbq buffer associated with the given tag in
2652  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2653  * otherwise it returns NULL.
2654  **/
2655 static struct hbq_dmabuf *
2656 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2657 {
2658         struct lpfc_dmabuf *d_buf;
2659         struct hbq_dmabuf *hbq_buf;
2660         uint32_t hbqno;
2661
2662         hbqno = tag >> 16;
2663         if (hbqno >= LPFC_MAX_HBQS)
2664                 return NULL;
2665
2666         spin_lock_irq(&phba->hbalock);
2667         list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2668                 hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2669                 if (hbq_buf->tag == tag) {
2670                         spin_unlock_irq(&phba->hbalock);
2671                         return hbq_buf;
2672                 }
2673         }
2674         spin_unlock_irq(&phba->hbalock);
2675         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2676                         "1803 Bad hbq tag. Data: x%x x%x\n",
2677                         tag, phba->hbqs[tag >> 16].buffer_count);
2678         return NULL;
2679 }
2680
2681 /**
2682  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2683  * @phba: Pointer to HBA context object.
2684  * @hbq_buffer: Pointer to HBQ buffer.
2685  *
2686  * This function is called with hbalock. This function gives back
2687  * the hbq buffer to firmware. If the HBQ does not have space to
2688  * post the buffer, it will free the buffer.
2689  **/
2690 void
2691 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2692 {
2693         uint32_t hbqno;
2694
2695         if (hbq_buffer) {
2696                 hbqno = hbq_buffer->tag >> 16;
2697                 if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2698                         (phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2699         }
2700 }
2701
2702 /**
2703  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2704  * @mbxCommand: mailbox command code.
2705  *
2706  * This function is called by the mailbox event handler function to verify
2707  * that the completed mailbox command is a legitimate mailbox command. If the
2708  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2709  * and the mailbox event handler will take the HBA offline.
2710  **/
2711 static int
2712 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2713 {
2714         uint8_t ret;
2715
2716         switch (mbxCommand) {
2717         case MBX_LOAD_SM:
2718         case MBX_READ_NV:
2719         case MBX_WRITE_NV:
2720         case MBX_WRITE_VPARMS:
2721         case MBX_RUN_BIU_DIAG:
2722         case MBX_INIT_LINK:
2723         case MBX_DOWN_LINK:
2724         case MBX_CONFIG_LINK:
2725         case MBX_CONFIG_RING:
2726         case MBX_RESET_RING:
2727         case MBX_READ_CONFIG:
2728         case MBX_READ_RCONFIG:
2729         case MBX_READ_SPARM:
2730         case MBX_READ_STATUS:
2731         case MBX_READ_RPI:
2732         case MBX_READ_XRI:
2733         case MBX_READ_REV:
2734         case MBX_READ_LNK_STAT:
2735         case MBX_REG_LOGIN:
2736         case MBX_UNREG_LOGIN:
2737         case MBX_CLEAR_LA:
2738         case MBX_DUMP_MEMORY:
2739         case MBX_DUMP_CONTEXT:
2740         case MBX_RUN_DIAGS:
2741         case MBX_RESTART:
2742         case MBX_UPDATE_CFG:
2743         case MBX_DOWN_LOAD:
2744         case MBX_DEL_LD_ENTRY:
2745         case MBX_RUN_PROGRAM:
2746         case MBX_SET_MASK:
2747         case MBX_SET_VARIABLE:
2748         case MBX_UNREG_D_ID:
2749         case MBX_KILL_BOARD:
2750         case MBX_CONFIG_FARP:
2751         case MBX_BEACON:
2752         case MBX_LOAD_AREA:
2753         case MBX_RUN_BIU_DIAG64:
2754         case MBX_CONFIG_PORT:
2755         case MBX_READ_SPARM64:
2756         case MBX_READ_RPI64:
2757         case MBX_REG_LOGIN64:
2758         case MBX_READ_TOPOLOGY:
2759         case MBX_WRITE_WWN:
2760         case MBX_SET_DEBUG:
2761         case MBX_LOAD_EXP_ROM:
2762         case MBX_ASYNCEVT_ENABLE:
2763         case MBX_REG_VPI:
2764         case MBX_UNREG_VPI:
2765         case MBX_HEARTBEAT:
2766         case MBX_PORT_CAPABILITIES:
2767         case MBX_PORT_IOV_CONTROL:
2768         case MBX_SLI4_CONFIG:
2769         case MBX_SLI4_REQ_FTRS:
2770         case MBX_REG_FCFI:
2771         case MBX_UNREG_FCFI:
2772         case MBX_REG_VFI:
2773         case MBX_UNREG_VFI:
2774         case MBX_INIT_VPI:
2775         case MBX_INIT_VFI:
2776         case MBX_RESUME_RPI:
2777         case MBX_READ_EVENT_LOG_STATUS:
2778         case MBX_READ_EVENT_LOG:
2779         case MBX_SECURITY_MGMT:
2780         case MBX_AUTH_PORT:
2781         case MBX_ACCESS_VDATA:
2782                 ret = mbxCommand;
2783                 break;
2784         default:
2785                 ret = MBX_SHUTDOWN;
2786                 break;
2787         }
2788         return ret;
2789 }
2790
2791 /**
2792  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2793  * @phba: Pointer to HBA context object.
2794  * @pmboxq: Pointer to mailbox command.
2795  *
2796  * This is completion handler function for mailbox commands issued from
2797  * lpfc_sli_issue_mbox_wait function. This function is called by the
2798  * mailbox event handler function with no lock held. This function
2799  * will wake up thread waiting on the wait queue pointed by context1
2800  * of the mailbox.
2801  **/
2802 void
2803 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2804 {
2805         unsigned long drvr_flag;
2806         struct completion *pmbox_done;
2807
2808         /*
2809          * If pmbox_done is empty, the driver thread gave up waiting and
2810          * continued running.
2811          */
2812         pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2813         spin_lock_irqsave(&phba->hbalock, drvr_flag);
2814         pmbox_done = (struct completion *)pmboxq->context3;
2815         if (pmbox_done)
2816                 complete(pmbox_done);
2817         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2818         return;
2819 }
2820
2821 static void
2822 __lpfc_sli_rpi_release(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
2823 {
2824         unsigned long iflags;
2825
2826         if (ndlp->nlp_flag & NLP_RELEASE_RPI) {
2827                 lpfc_sli4_free_rpi(vport->phba, ndlp->nlp_rpi);
2828                 spin_lock_irqsave(&ndlp->lock, iflags);
2829                 ndlp->nlp_flag &= ~NLP_RELEASE_RPI;
2830                 ndlp->nlp_rpi = LPFC_RPI_ALLOC_ERROR;
2831                 spin_unlock_irqrestore(&ndlp->lock, iflags);
2832         }
2833         ndlp->nlp_flag &= ~NLP_UNREG_INP;
2834 }
2835
2836 /**
2837  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2838  * @phba: Pointer to HBA context object.
2839  * @pmb: Pointer to mailbox object.
2840  *
2841  * This function is the default mailbox completion handler. It
2842  * frees the memory resources associated with the completed mailbox
2843  * command. If the completed command is a REG_LOGIN mailbox command,
2844  * this function will issue a UREG_LOGIN to re-claim the RPI.
2845  **/
2846 void
2847 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2848 {
2849         struct lpfc_vport  *vport = pmb->vport;
2850         struct lpfc_dmabuf *mp;
2851         struct lpfc_nodelist *ndlp;
2852         struct Scsi_Host *shost;
2853         uint16_t rpi, vpi;
2854         int rc;
2855
2856         mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
2857
2858         if (mp) {
2859                 lpfc_mbuf_free(phba, mp->virt, mp->phys);
2860                 kfree(mp);
2861         }
2862
2863         /*
2864          * If a REG_LOGIN succeeded  after node is destroyed or node
2865          * is in re-discovery driver need to cleanup the RPI.
2866          */
2867         if (!(phba->pport->load_flag & FC_UNLOADING) &&
2868             pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2869             !pmb->u.mb.mbxStatus) {
2870                 rpi = pmb->u.mb.un.varWords[0];
2871                 vpi = pmb->u.mb.un.varRegLogin.vpi;
2872                 if (phba->sli_rev == LPFC_SLI_REV4)
2873                         vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2874                 lpfc_unreg_login(phba, vpi, rpi, pmb);
2875                 pmb->vport = vport;
2876                 pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2877                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2878                 if (rc != MBX_NOT_FINISHED)
2879                         return;
2880         }
2881
2882         if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2883                 !(phba->pport->load_flag & FC_UNLOADING) &&
2884                 !pmb->u.mb.mbxStatus) {
2885                 shost = lpfc_shost_from_vport(vport);
2886                 spin_lock_irq(shost->host_lock);
2887                 vport->vpi_state |= LPFC_VPI_REGISTERED;
2888                 vport->fc_flag &= ~FC_VPORT_NEEDS_REG_VPI;
2889                 spin_unlock_irq(shost->host_lock);
2890         }
2891
2892         if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2893                 ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2894                 lpfc_nlp_put(ndlp);
2895                 pmb->ctx_buf = NULL;
2896                 pmb->ctx_ndlp = NULL;
2897         }
2898
2899         if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2900                 ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2901
2902                 /* Check to see if there are any deferred events to process */
2903                 if (ndlp) {
2904                         lpfc_printf_vlog(
2905                                 vport,
2906                                 KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2907                                 "1438 UNREG cmpl deferred mbox x%x "
2908                                 "on NPort x%x Data: x%x x%x x%px x%x x%x\n",
2909                                 ndlp->nlp_rpi, ndlp->nlp_DID,
2910                                 ndlp->nlp_flag, ndlp->nlp_defer_did,
2911                                 ndlp, vport->load_flag, kref_read(&ndlp->kref));
2912
2913                         if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2914                             (ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING)) {
2915                                 ndlp->nlp_flag &= ~NLP_UNREG_INP;
2916                                 ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2917                                 lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2918                         } else {
2919                                 __lpfc_sli_rpi_release(vport, ndlp);
2920                         }
2921
2922                         /* The unreg_login mailbox is complete and had a
2923                          * reference that has to be released.  The PLOGI
2924                          * got its own ref.
2925                          */
2926                         lpfc_nlp_put(ndlp);
2927                         pmb->ctx_ndlp = NULL;
2928                 }
2929         }
2930
2931         /* This nlp_put pairs with lpfc_sli4_resume_rpi */
2932         if (pmb->u.mb.mbxCommand == MBX_RESUME_RPI) {
2933                 ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
2934                 lpfc_nlp_put(ndlp);
2935         }
2936
2937         /* Check security permission status on INIT_LINK mailbox command */
2938         if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2939             (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2940                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2941                                 "2860 SLI authentication is required "
2942                                 "for INIT_LINK but has not done yet\n");
2943
2944         if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2945                 lpfc_sli4_mbox_cmd_free(phba, pmb);
2946         else
2947                 mempool_free(pmb, phba->mbox_mem_pool);
2948 }
2949  /**
2950  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2951  * @phba: Pointer to HBA context object.
2952  * @pmb: Pointer to mailbox object.
2953  *
2954  * This function is the unreg rpi mailbox completion handler. It
2955  * frees the memory resources associated with the completed mailbox
2956  * command. An additional reference is put on the ndlp to prevent
2957  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2958  * the unreg mailbox command completes, this routine puts the
2959  * reference back.
2960  *
2961  **/
2962 void
2963 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2964 {
2965         struct lpfc_vport  *vport = pmb->vport;
2966         struct lpfc_nodelist *ndlp;
2967
2968         ndlp = pmb->ctx_ndlp;
2969         if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2970                 if (phba->sli_rev == LPFC_SLI_REV4 &&
2971                     (bf_get(lpfc_sli_intf_if_type,
2972                      &phba->sli4_hba.sli_intf) >=
2973                      LPFC_SLI_INTF_IF_TYPE_2)) {
2974                         if (ndlp) {
2975                                 lpfc_printf_vlog(
2976                                          vport, KERN_INFO, LOG_MBOX | LOG_SLI,
2977                                          "0010 UNREG_LOGIN vpi:%x "
2978                                          "rpi:%x DID:%x defer x%x flg x%x "
2979                                          "x%px\n",
2980                                          vport->vpi, ndlp->nlp_rpi,
2981                                          ndlp->nlp_DID, ndlp->nlp_defer_did,
2982                                          ndlp->nlp_flag,
2983                                          ndlp);
2984                                 ndlp->nlp_flag &= ~NLP_LOGO_ACC;
2985
2986                                 /* Check to see if there are any deferred
2987                                  * events to process
2988                                  */
2989                                 if ((ndlp->nlp_flag & NLP_UNREG_INP) &&
2990                                     (ndlp->nlp_defer_did !=
2991                                     NLP_EVT_NOTHING_PENDING)) {
2992                                         lpfc_printf_vlog(
2993                                                 vport, KERN_INFO, LOG_DISCOVERY,
2994                                                 "4111 UNREG cmpl deferred "
2995                                                 "clr x%x on "
2996                                                 "NPort x%x Data: x%x x%px\n",
2997                                                 ndlp->nlp_rpi, ndlp->nlp_DID,
2998                                                 ndlp->nlp_defer_did, ndlp);
2999                                         ndlp->nlp_flag &= ~NLP_UNREG_INP;
3000                                         ndlp->nlp_defer_did =
3001                                                 NLP_EVT_NOTHING_PENDING;
3002                                         lpfc_issue_els_plogi(
3003                                                 vport, ndlp->nlp_DID, 0);
3004                                 } else {
3005                                         __lpfc_sli_rpi_release(vport, ndlp);
3006                                 }
3007                                 lpfc_nlp_put(ndlp);
3008                         }
3009                 }
3010         }
3011
3012         mempool_free(pmb, phba->mbox_mem_pool);
3013 }
3014
3015 /**
3016  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
3017  * @phba: Pointer to HBA context object.
3018  *
3019  * This function is called with no lock held. This function processes all
3020  * the completed mailbox commands and gives it to upper layers. The interrupt
3021  * service routine processes mailbox completion interrupt and adds completed
3022  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
3023  * Worker thread call lpfc_sli_handle_mb_event, which will return the
3024  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
3025  * function returns the mailbox commands to the upper layer by calling the
3026  * completion handler function of each mailbox.
3027  **/
3028 int
3029 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
3030 {
3031         MAILBOX_t *pmbox;
3032         LPFC_MBOXQ_t *pmb;
3033         int rc;
3034         LIST_HEAD(cmplq);
3035
3036         phba->sli.slistat.mbox_event++;
3037
3038         /* Get all completed mailboxe buffers into the cmplq */
3039         spin_lock_irq(&phba->hbalock);
3040         list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
3041         spin_unlock_irq(&phba->hbalock);
3042
3043         /* Get a Mailbox buffer to setup mailbox commands for callback */
3044         do {
3045                 list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
3046                 if (pmb == NULL)
3047                         break;
3048
3049                 pmbox = &pmb->u.mb;
3050
3051                 if (pmbox->mbxCommand != MBX_HEARTBEAT) {
3052                         if (pmb->vport) {
3053                                 lpfc_debugfs_disc_trc(pmb->vport,
3054                                         LPFC_DISC_TRC_MBOX_VPORT,
3055                                         "MBOX cmpl vport: cmd:x%x mb:x%x x%x",
3056                                         (uint32_t)pmbox->mbxCommand,
3057                                         pmbox->un.varWords[0],
3058                                         pmbox->un.varWords[1]);
3059                         }
3060                         else {
3061                                 lpfc_debugfs_disc_trc(phba->pport,
3062                                         LPFC_DISC_TRC_MBOX,
3063                                         "MBOX cmpl:       cmd:x%x mb:x%x x%x",
3064                                         (uint32_t)pmbox->mbxCommand,
3065                                         pmbox->un.varWords[0],
3066                                         pmbox->un.varWords[1]);
3067                         }
3068                 }
3069
3070                 /*
3071                  * It is a fatal error if unknown mbox command completion.
3072                  */
3073                 if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
3074                     MBX_SHUTDOWN) {
3075                         /* Unknown mailbox command compl */
3076                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3077                                         "(%d):0323 Unknown Mailbox command "
3078                                         "x%x (x%x/x%x) Cmpl\n",
3079                                         pmb->vport ? pmb->vport->vpi :
3080                                         LPFC_VPORT_UNKNOWN,
3081                                         pmbox->mbxCommand,
3082                                         lpfc_sli_config_mbox_subsys_get(phba,
3083                                                                         pmb),
3084                                         lpfc_sli_config_mbox_opcode_get(phba,
3085                                                                         pmb));
3086                         phba->link_state = LPFC_HBA_ERROR;
3087                         phba->work_hs = HS_FFER3;
3088                         lpfc_handle_eratt(phba);
3089                         continue;
3090                 }
3091
3092                 if (pmbox->mbxStatus) {
3093                         phba->sli.slistat.mbox_stat_err++;
3094                         if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
3095                                 /* Mbox cmd cmpl error - RETRYing */
3096                                 lpfc_printf_log(phba, KERN_INFO,
3097                                         LOG_MBOX | LOG_SLI,
3098                                         "(%d):0305 Mbox cmd cmpl "
3099                                         "error - RETRYing Data: x%x "
3100                                         "(x%x/x%x) x%x x%x x%x\n",
3101                                         pmb->vport ? pmb->vport->vpi :
3102                                         LPFC_VPORT_UNKNOWN,
3103                                         pmbox->mbxCommand,
3104                                         lpfc_sli_config_mbox_subsys_get(phba,
3105                                                                         pmb),
3106                                         lpfc_sli_config_mbox_opcode_get(phba,
3107                                                                         pmb),
3108                                         pmbox->mbxStatus,
3109                                         pmbox->un.varWords[0],
3110                                         pmb->vport ? pmb->vport->port_state :
3111                                         LPFC_VPORT_UNKNOWN);
3112                                 pmbox->mbxStatus = 0;
3113                                 pmbox->mbxOwner = OWN_HOST;
3114                                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3115                                 if (rc != MBX_NOT_FINISHED)
3116                                         continue;
3117                         }
3118                 }
3119
3120                 /* Mailbox cmd <cmd> Cmpl <cmpl> */
3121                 lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
3122                                 "(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
3123                                 "Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
3124                                 "x%x x%x x%x\n",
3125                                 pmb->vport ? pmb->vport->vpi : 0,
3126                                 pmbox->mbxCommand,
3127                                 lpfc_sli_config_mbox_subsys_get(phba, pmb),
3128                                 lpfc_sli_config_mbox_opcode_get(phba, pmb),
3129                                 pmb->mbox_cmpl,
3130                                 *((uint32_t *) pmbox),
3131                                 pmbox->un.varWords[0],
3132                                 pmbox->un.varWords[1],
3133                                 pmbox->un.varWords[2],
3134                                 pmbox->un.varWords[3],
3135                                 pmbox->un.varWords[4],
3136                                 pmbox->un.varWords[5],
3137                                 pmbox->un.varWords[6],
3138                                 pmbox->un.varWords[7],
3139                                 pmbox->un.varWords[8],
3140                                 pmbox->un.varWords[9],
3141                                 pmbox->un.varWords[10]);
3142
3143                 if (pmb->mbox_cmpl)
3144                         pmb->mbox_cmpl(phba,pmb);
3145         } while (1);
3146         return 0;
3147 }
3148
3149 /**
3150  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
3151  * @phba: Pointer to HBA context object.
3152  * @pring: Pointer to driver SLI ring object.
3153  * @tag: buffer tag.
3154  *
3155  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
3156  * is set in the tag the buffer is posted for a particular exchange,
3157  * the function will return the buffer without replacing the buffer.
3158  * If the buffer is for unsolicited ELS or CT traffic, this function
3159  * returns the buffer and also posts another buffer to the firmware.
3160  **/
3161 static struct lpfc_dmabuf *
3162 lpfc_sli_get_buff(struct lpfc_hba *phba,
3163                   struct lpfc_sli_ring *pring,
3164                   uint32_t tag)
3165 {
3166         struct hbq_dmabuf *hbq_entry;
3167
3168         if (tag & QUE_BUFTAG_BIT)
3169                 return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
3170         hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
3171         if (!hbq_entry)
3172                 return NULL;
3173         return &hbq_entry->dbuf;
3174 }
3175
3176 /**
3177  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
3178  *                              containing a NVME LS request.
3179  * @phba: pointer to lpfc hba data structure.
3180  * @piocb: pointer to the iocbq struct representing the sequence starting
3181  *        frame.
3182  *
3183  * This routine initially validates the NVME LS, validates there is a login
3184  * with the port that sent the LS, and then calls the appropriate nvme host
3185  * or target LS request handler.
3186  **/
3187 static void
3188 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
3189 {
3190         struct lpfc_nodelist *ndlp;
3191         struct lpfc_dmabuf *d_buf;
3192         struct hbq_dmabuf *nvmebuf;
3193         struct fc_frame_header *fc_hdr;
3194         struct lpfc_async_xchg_ctx *axchg = NULL;
3195         char *failwhy = NULL;
3196         uint32_t oxid, sid, did, fctl, size;
3197         int ret = 1;
3198
3199         d_buf = piocb->context2;
3200
3201         nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
3202         fc_hdr = nvmebuf->hbuf.virt;
3203         oxid = be16_to_cpu(fc_hdr->fh_ox_id);
3204         sid = sli4_sid_from_fc_hdr(fc_hdr);
3205         did = sli4_did_from_fc_hdr(fc_hdr);
3206         fctl = (fc_hdr->fh_f_ctl[0] << 16 |
3207                 fc_hdr->fh_f_ctl[1] << 8 |
3208                 fc_hdr->fh_f_ctl[2]);
3209         size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
3210
3211         lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
3212                          oxid, size, sid);
3213
3214         if (phba->pport->load_flag & FC_UNLOADING) {
3215                 failwhy = "Driver Unloading";
3216         } else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
3217                 failwhy = "NVME FC4 Disabled";
3218         } else if (!phba->nvmet_support && !phba->pport->localport) {
3219                 failwhy = "No Localport";
3220         } else if (phba->nvmet_support && !phba->targetport) {
3221                 failwhy = "No Targetport";
3222         } else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
3223                 failwhy = "Bad NVME LS R_CTL";
3224         } else if (unlikely((fctl & 0x00FF0000) !=
3225                         (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
3226                 failwhy = "Bad NVME LS F_CTL";
3227         } else {
3228                 axchg = kzalloc(sizeof(*axchg), GFP_ATOMIC);
3229                 if (!axchg)
3230                         failwhy = "No CTX memory";
3231         }
3232
3233         if (unlikely(failwhy)) {
3234                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3235                                 "6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
3236                                 sid, oxid, failwhy);
3237                 goto out_fail;
3238         }
3239
3240         /* validate the source of the LS is logged in */
3241         ndlp = lpfc_findnode_did(phba->pport, sid);
3242         if (!ndlp ||
3243             ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
3244              (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
3245                 lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
3246                                 "6216 NVME Unsol rcv: No ndlp: "
3247                                 "NPort_ID x%x oxid x%x\n",
3248                                 sid, oxid);
3249                 goto out_fail;
3250         }
3251
3252         axchg->phba = phba;
3253         axchg->ndlp = ndlp;
3254         axchg->size = size;
3255         axchg->oxid = oxid;
3256         axchg->sid = sid;
3257         axchg->wqeq = NULL;
3258         axchg->state = LPFC_NVME_STE_LS_RCV;
3259         axchg->entry_cnt = 1;
3260         axchg->rqb_buffer = (void *)nvmebuf;
3261         axchg->hdwq = &phba->sli4_hba.hdwq[0];
3262         axchg->payload = nvmebuf->dbuf.virt;
3263         INIT_LIST_HEAD(&axchg->list);
3264
3265         if (phba->nvmet_support) {
3266                 ret = lpfc_nvmet_handle_lsreq(phba, axchg);
3267                 spin_lock_irq(&ndlp->lock);
3268                 if (!ret && !(ndlp->fc4_xpt_flags & NLP_XPT_HAS_HH)) {
3269                         ndlp->fc4_xpt_flags |= NLP_XPT_HAS_HH;
3270                         spin_unlock_irq(&ndlp->lock);
3271
3272                         /* This reference is a single occurrence to hold the
3273                          * node valid until the nvmet transport calls
3274                          * host_release.
3275                          */
3276                         if (!lpfc_nlp_get(ndlp))
3277                                 goto out_fail;
3278
3279                         lpfc_printf_log(phba, KERN_ERR, LOG_NODE,
3280                                         "6206 NVMET unsol ls_req ndlp x%px "
3281                                         "DID x%x xflags x%x refcnt %d\n",
3282                                         ndlp, ndlp->nlp_DID,
3283                                         ndlp->fc4_xpt_flags,
3284                                         kref_read(&ndlp->kref));
3285                 } else {
3286                         spin_unlock_irq(&ndlp->lock);
3287                 }
3288         } else {
3289                 ret = lpfc_nvme_handle_lsreq(phba, axchg);
3290         }
3291
3292         /* if zero, LS was successfully handled. If non-zero, LS not handled */
3293         if (!ret)
3294                 return;
3295
3296 out_fail:
3297         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3298                         "6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
3299                         "NVMe%s handler failed %d\n",
3300                         did, sid, oxid,
3301                         (phba->nvmet_support) ? "T" : "I", ret);
3302
3303         /* recycle receive buffer */
3304         lpfc_in_buf_free(phba, &nvmebuf->dbuf);
3305
3306         /* If start of new exchange, abort it */
3307         if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
3308                 ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
3309
3310         if (ret)
3311                 kfree(axchg);
3312 }
3313
3314 /**
3315  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
3316  * @phba: Pointer to HBA context object.
3317  * @pring: Pointer to driver SLI ring object.
3318  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
3319  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
3320  * @fch_type: the type for the first frame of the sequence.
3321  *
3322  * This function is called with no lock held. This function uses the r_ctl and
3323  * type of the received sequence to find the correct callback function to call
3324  * to process the sequence.
3325  **/
3326 static int
3327 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3328                          struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
3329                          uint32_t fch_type)
3330 {
3331         int i;
3332
3333         switch (fch_type) {
3334         case FC_TYPE_NVME:
3335                 lpfc_nvme_unsol_ls_handler(phba, saveq);
3336                 return 1;
3337         default:
3338                 break;
3339         }
3340
3341         /* unSolicited Responses */
3342         if (pring->prt[0].profile) {
3343                 if (pring->prt[0].lpfc_sli_rcv_unsol_event)
3344                         (pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
3345                                                                         saveq);
3346                 return 1;
3347         }
3348         /* We must search, based on rctl / type
3349            for the right routine */
3350         for (i = 0; i < pring->num_mask; i++) {
3351                 if ((pring->prt[i].rctl == fch_r_ctl) &&
3352                     (pring->prt[i].type == fch_type)) {
3353                         if (pring->prt[i].lpfc_sli_rcv_unsol_event)
3354                                 (pring->prt[i].lpfc_sli_rcv_unsol_event)
3355                                                 (phba, pring, saveq);
3356                         return 1;
3357                 }
3358         }
3359         return 0;
3360 }
3361
3362 /**
3363  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
3364  * @phba: Pointer to HBA context object.
3365  * @pring: Pointer to driver SLI ring object.
3366  * @saveq: Pointer to the unsolicited iocb.
3367  *
3368  * This function is called with no lock held by the ring event handler
3369  * when there is an unsolicited iocb posted to the response ring by the
3370  * firmware. This function gets the buffer associated with the iocbs
3371  * and calls the event handler for the ring. This function handles both
3372  * qring buffers and hbq buffers.
3373  * When the function returns 1 the caller can free the iocb object otherwise
3374  * upper layer functions will free the iocb objects.
3375  **/
3376 static int
3377 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3378                             struct lpfc_iocbq *saveq)
3379 {
3380         IOCB_t           * irsp;
3381         WORD5            * w5p;
3382         uint32_t           Rctl, Type;
3383         struct lpfc_iocbq *iocbq;
3384         struct lpfc_dmabuf *dmzbuf;
3385
3386         irsp = &(saveq->iocb);
3387
3388         if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
3389                 if (pring->lpfc_sli_rcv_async_status)
3390                         pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
3391                 else
3392                         lpfc_printf_log(phba,
3393                                         KERN_WARNING,
3394                                         LOG_SLI,
3395                                         "0316 Ring %d handler: unexpected "
3396                                         "ASYNC_STATUS iocb received evt_code "
3397                                         "0x%x\n",
3398                                         pring->ringno,
3399                                         irsp->un.asyncstat.evt_code);
3400                 return 1;
3401         }
3402
3403         if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
3404                 (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
3405                 if (irsp->ulpBdeCount > 0) {
3406                         dmzbuf = lpfc_sli_get_buff(phba, pring,
3407                                         irsp->un.ulpWord[3]);
3408                         lpfc_in_buf_free(phba, dmzbuf);
3409                 }
3410
3411                 if (irsp->ulpBdeCount > 1) {
3412                         dmzbuf = lpfc_sli_get_buff(phba, pring,
3413                                         irsp->unsli3.sli3Words[3]);
3414                         lpfc_in_buf_free(phba, dmzbuf);
3415                 }
3416
3417                 if (irsp->ulpBdeCount > 2) {
3418                         dmzbuf = lpfc_sli_get_buff(phba, pring,
3419                                 irsp->unsli3.sli3Words[7]);
3420                         lpfc_in_buf_free(phba, dmzbuf);
3421                 }
3422
3423                 return 1;
3424         }
3425
3426         if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3427                 if (irsp->ulpBdeCount != 0) {
3428                         saveq->context2 = lpfc_sli_get_buff(phba, pring,
3429                                                 irsp->un.ulpWord[3]);
3430                         if (!saveq->context2)
3431                                 lpfc_printf_log(phba,
3432                                         KERN_ERR,
3433                                         LOG_SLI,
3434                                         "0341 Ring %d Cannot find buffer for "
3435                                         "an unsolicited iocb. tag 0x%x\n",
3436                                         pring->ringno,
3437                                         irsp->un.ulpWord[3]);
3438                 }
3439                 if (irsp->ulpBdeCount == 2) {
3440                         saveq->context3 = lpfc_sli_get_buff(phba, pring,
3441                                                 irsp->unsli3.sli3Words[7]);
3442                         if (!saveq->context3)
3443                                 lpfc_printf_log(phba,
3444                                         KERN_ERR,
3445                                         LOG_SLI,
3446                                         "0342 Ring %d Cannot find buffer for an"
3447                                         " unsolicited iocb. tag 0x%x\n",
3448                                         pring->ringno,
3449                                         irsp->unsli3.sli3Words[7]);
3450                 }
3451                 list_for_each_entry(iocbq, &saveq->list, list) {
3452                         irsp = &(iocbq->iocb);
3453                         if (irsp->ulpBdeCount != 0) {
3454                                 iocbq->context2 = lpfc_sli_get_buff(phba, pring,
3455                                                         irsp->un.ulpWord[3]);
3456                                 if (!iocbq->context2)
3457                                         lpfc_printf_log(phba,
3458                                                 KERN_ERR,
3459                                                 LOG_SLI,
3460                                                 "0343 Ring %d Cannot find "
3461                                                 "buffer for an unsolicited iocb"
3462                                                 ". tag 0x%x\n", pring->ringno,
3463                                                 irsp->un.ulpWord[3]);
3464                         }
3465                         if (irsp->ulpBdeCount == 2) {
3466                                 iocbq->context3 = lpfc_sli_get_buff(phba, pring,
3467                                                 irsp->unsli3.sli3Words[7]);
3468                                 if (!iocbq->context3)
3469                                         lpfc_printf_log(phba,
3470                                                 KERN_ERR,
3471                                                 LOG_SLI,
3472                                                 "0344 Ring %d Cannot find "
3473                                                 "buffer for an unsolicited "
3474                                                 "iocb. tag 0x%x\n",
3475                                                 pring->ringno,
3476                                                 irsp->unsli3.sli3Words[7]);
3477                         }
3478                 }
3479         }
3480         if (irsp->ulpBdeCount != 0 &&
3481             (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3482              irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3483                 int found = 0;
3484
3485                 /* search continue save q for same XRI */
3486                 list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3487                         if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3488                                 saveq->iocb.unsli3.rcvsli3.ox_id) {
3489                                 list_add_tail(&saveq->list, &iocbq->list);
3490                                 found = 1;
3491                                 break;
3492                         }
3493                 }
3494                 if (!found)
3495                         list_add_tail(&saveq->clist,
3496                                       &pring->iocb_continue_saveq);
3497                 if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3498                         list_del_init(&iocbq->clist);
3499                         saveq = iocbq;
3500                         irsp = &(saveq->iocb);
3501                 } else
3502                         return 0;
3503         }
3504         if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3505             (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3506             (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3507                 Rctl = FC_RCTL_ELS_REQ;
3508                 Type = FC_TYPE_ELS;
3509         } else {
3510                 w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3511                 Rctl = w5p->hcsw.Rctl;
3512                 Type = w5p->hcsw.Type;
3513
3514                 /* Firmware Workaround */
3515                 if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3516                         (irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3517                          irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3518                         Rctl = FC_RCTL_ELS_REQ;
3519                         Type = FC_TYPE_ELS;
3520                         w5p->hcsw.Rctl = Rctl;
3521                         w5p->hcsw.Type = Type;
3522                 }
3523         }
3524
3525         if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3526                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3527                                 "0313 Ring %d handler: unexpected Rctl x%x "
3528                                 "Type x%x received\n",
3529                                 pring->ringno, Rctl, Type);
3530
3531         return 1;
3532 }
3533
3534 /**
3535  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3536  * @phba: Pointer to HBA context object.
3537  * @pring: Pointer to driver SLI ring object.
3538  * @prspiocb: Pointer to response iocb object.
3539  *
3540  * This function looks up the iocb_lookup table to get the command iocb
3541  * corresponding to the given response iocb using the iotag of the
3542  * response iocb. The driver calls this function with the hbalock held
3543  * for SLI3 ports or the ring lock held for SLI4 ports.
3544  * This function returns the command iocb object if it finds the command
3545  * iocb else returns NULL.
3546  **/
3547 static struct lpfc_iocbq *
3548 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3549                       struct lpfc_sli_ring *pring,
3550                       struct lpfc_iocbq *prspiocb)
3551 {
3552         struct lpfc_iocbq *cmd_iocb = NULL;
3553         uint16_t iotag;
3554         spinlock_t *temp_lock = NULL;
3555         unsigned long iflag = 0;
3556
3557         if (phba->sli_rev == LPFC_SLI_REV4)
3558                 temp_lock = &pring->ring_lock;
3559         else
3560                 temp_lock = &phba->hbalock;
3561
3562         spin_lock_irqsave(temp_lock, iflag);
3563         iotag = prspiocb->iocb.ulpIoTag;
3564
3565         if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3566                 cmd_iocb = phba->sli.iocbq_lookup[iotag];
3567                 if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3568                         /* remove from txcmpl queue list */
3569                         list_del_init(&cmd_iocb->list);
3570                         cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3571                         pring->txcmplq_cnt--;
3572                         spin_unlock_irqrestore(temp_lock, iflag);
3573                         return cmd_iocb;
3574                 }
3575         }
3576
3577         spin_unlock_irqrestore(temp_lock, iflag);
3578         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3579                         "0317 iotag x%x is out of "
3580                         "range: max iotag x%x wd0 x%x\n",
3581                         iotag, phba->sli.last_iotag,
3582                         *(((uint32_t *) &prspiocb->iocb) + 7));
3583         return NULL;
3584 }
3585
3586 /**
3587  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3588  * @phba: Pointer to HBA context object.
3589  * @pring: Pointer to driver SLI ring object.
3590  * @iotag: IOCB tag.
3591  *
3592  * This function looks up the iocb_lookup table to get the command iocb
3593  * corresponding to the given iotag. The driver calls this function with
3594  * the ring lock held because this function is an SLI4 port only helper.
3595  * This function returns the command iocb object if it finds the command
3596  * iocb else returns NULL.
3597  **/
3598 static struct lpfc_iocbq *
3599 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3600                              struct lpfc_sli_ring *pring, uint16_t iotag)
3601 {
3602         struct lpfc_iocbq *cmd_iocb = NULL;
3603         spinlock_t *temp_lock = NULL;
3604         unsigned long iflag = 0;
3605
3606         if (phba->sli_rev == LPFC_SLI_REV4)
3607                 temp_lock = &pring->ring_lock;
3608         else
3609                 temp_lock = &phba->hbalock;
3610
3611         spin_lock_irqsave(temp_lock, iflag);
3612         if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3613                 cmd_iocb = phba->sli.iocbq_lookup[iotag];
3614                 if (cmd_iocb->iocb_flag & LPFC_IO_ON_TXCMPLQ) {
3615                         /* remove from txcmpl queue list */
3616                         list_del_init(&cmd_iocb->list);
3617                         cmd_iocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
3618                         pring->txcmplq_cnt--;
3619                         spin_unlock_irqrestore(temp_lock, iflag);
3620                         return cmd_iocb;
3621                 }
3622         }
3623
3624         spin_unlock_irqrestore(temp_lock, iflag);
3625         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3626                         "0372 iotag x%x lookup error: max iotag (x%x) "
3627                         "iocb_flag x%x\n",
3628                         iotag, phba->sli.last_iotag,
3629                         cmd_iocb ? cmd_iocb->iocb_flag : 0xffff);
3630         return NULL;
3631 }
3632
3633 /**
3634  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3635  * @phba: Pointer to HBA context object.
3636  * @pring: Pointer to driver SLI ring object.
3637  * @saveq: Pointer to the response iocb to be processed.
3638  *
3639  * This function is called by the ring event handler for non-fcp
3640  * rings when there is a new response iocb in the response ring.
3641  * The caller is not required to hold any locks. This function
3642  * gets the command iocb associated with the response iocb and
3643  * calls the completion handler for the command iocb. If there
3644  * is no completion handler, the function will free the resources
3645  * associated with command iocb. If the response iocb is for
3646  * an already aborted command iocb, the status of the completion
3647  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3648  * This function always returns 1.
3649  **/
3650 static int
3651 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3652                           struct lpfc_iocbq *saveq)
3653 {
3654         struct lpfc_iocbq *cmdiocbp;
3655         int rc = 1;
3656         unsigned long iflag;
3657
3658         cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3659         if (cmdiocbp) {
3660                 if (cmdiocbp->iocb_cmpl) {
3661                         /*
3662                          * If an ELS command failed send an event to mgmt
3663                          * application.
3664                          */
3665                         if (saveq->iocb.ulpStatus &&
3666                              (pring->ringno == LPFC_ELS_RING) &&
3667                              (cmdiocbp->iocb.ulpCommand ==
3668                                 CMD_ELS_REQUEST64_CR))
3669                                 lpfc_send_els_failure_event(phba,
3670                                         cmdiocbp, saveq);
3671
3672                         /*
3673                          * Post all ELS completions to the worker thread.
3674                          * All other are passed to the completion callback.
3675                          */
3676                         if (pring->ringno == LPFC_ELS_RING) {
3677                                 if ((phba->sli_rev < LPFC_SLI_REV4) &&
3678                                     (cmdiocbp->iocb_flag &
3679                                                         LPFC_DRIVER_ABORTED)) {
3680                                         spin_lock_irqsave(&phba->hbalock,
3681                                                           iflag);
3682                                         cmdiocbp->iocb_flag &=
3683                                                 ~LPFC_DRIVER_ABORTED;
3684                                         spin_unlock_irqrestore(&phba->hbalock,
3685                                                                iflag);
3686                                         saveq->iocb.ulpStatus =
3687                                                 IOSTAT_LOCAL_REJECT;
3688                                         saveq->iocb.un.ulpWord[4] =
3689                                                 IOERR_SLI_ABORTED;
3690
3691                                         /* Firmware could still be in progress
3692                                          * of DMAing payload, so don't free data
3693                                          * buffer till after a hbeat.
3694                                          */
3695                                         spin_lock_irqsave(&phba->hbalock,
3696                                                           iflag);
3697                                         saveq->iocb_flag |= LPFC_DELAY_MEM_FREE;
3698                                         spin_unlock_irqrestore(&phba->hbalock,
3699                                                                iflag);
3700                                 }
3701                                 if (phba->sli_rev == LPFC_SLI_REV4) {
3702                                         if (saveq->iocb_flag &
3703                                             LPFC_EXCHANGE_BUSY) {
3704                                                 /* Set cmdiocb flag for the
3705                                                  * exchange busy so sgl (xri)
3706                                                  * will not be released until
3707                                                  * the abort xri is received
3708                                                  * from hba.
3709                                                  */
3710                                                 spin_lock_irqsave(
3711                                                         &phba->hbalock, iflag);
3712                                                 cmdiocbp->iocb_flag |=
3713                                                         LPFC_EXCHANGE_BUSY;
3714                                                 spin_unlock_irqrestore(
3715                                                         &phba->hbalock, iflag);
3716                                         }
3717                                         if (cmdiocbp->iocb_flag &
3718                                             LPFC_DRIVER_ABORTED) {
3719                                                 /*
3720                                                  * Clear LPFC_DRIVER_ABORTED
3721                                                  * bit in case it was driver
3722                                                  * initiated abort.
3723                                                  */
3724                                                 spin_lock_irqsave(
3725                                                         &phba->hbalock, iflag);
3726                                                 cmdiocbp->iocb_flag &=
3727                                                         ~LPFC_DRIVER_ABORTED;
3728                                                 spin_unlock_irqrestore(
3729                                                         &phba->hbalock, iflag);
3730                                                 cmdiocbp->iocb.ulpStatus =
3731                                                         IOSTAT_LOCAL_REJECT;
3732                                                 cmdiocbp->iocb.un.ulpWord[4] =
3733                                                         IOERR_ABORT_REQUESTED;
3734                                                 /*
3735                                                  * For SLI4, irsiocb contains
3736                                                  * NO_XRI in sli_xritag, it
3737                                                  * shall not affect releasing
3738                                                  * sgl (xri) process.
3739                                                  */
3740                                                 saveq->iocb.ulpStatus =
3741                                                         IOSTAT_LOCAL_REJECT;
3742                                                 saveq->iocb.un.ulpWord[4] =
3743                                                         IOERR_SLI_ABORTED;
3744                                                 spin_lock_irqsave(
3745                                                         &phba->hbalock, iflag);
3746                                                 saveq->iocb_flag |=
3747                                                         LPFC_DELAY_MEM_FREE;
3748                                                 spin_unlock_irqrestore(
3749                                                         &phba->hbalock, iflag);
3750                                         }
3751                                 }
3752                         }
3753                         (cmdiocbp->iocb_cmpl) (phba, cmdiocbp, saveq);
3754                 } else
3755                         lpfc_sli_release_iocbq(phba, cmdiocbp);
3756         } else {
3757                 /*
3758                  * Unknown initiating command based on the response iotag.
3759                  * This could be the case on the ELS ring because of
3760                  * lpfc_els_abort().
3761                  */
3762                 if (pring->ringno != LPFC_ELS_RING) {
3763                         /*
3764                          * Ring <ringno> handler: unexpected completion IoTag
3765                          * <IoTag>
3766                          */
3767                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3768                                          "0322 Ring %d handler: "
3769                                          "unexpected completion IoTag x%x "
3770                                          "Data: x%x x%x x%x x%x\n",
3771                                          pring->ringno,
3772                                          saveq->iocb.ulpIoTag,
3773                                          saveq->iocb.ulpStatus,
3774                                          saveq->iocb.un.ulpWord[4],
3775                                          saveq->iocb.ulpCommand,
3776                                          saveq->iocb.ulpContext);
3777                 }
3778         }
3779
3780         return rc;
3781 }
3782
3783 /**
3784  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3785  * @phba: Pointer to HBA context object.
3786  * @pring: Pointer to driver SLI ring object.
3787  *
3788  * This function is called from the iocb ring event handlers when
3789  * put pointer is ahead of the get pointer for a ring. This function signal
3790  * an error attention condition to the worker thread and the worker
3791  * thread will transition the HBA to offline state.
3792  **/
3793 static void
3794 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3795 {
3796         struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3797         /*
3798          * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3799          * rsp ring <portRspMax>
3800          */
3801         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3802                         "0312 Ring %d handler: portRspPut %d "
3803                         "is bigger than rsp ring %d\n",
3804                         pring->ringno, le32_to_cpu(pgp->rspPutInx),
3805                         pring->sli.sli3.numRiocb);
3806
3807         phba->link_state = LPFC_HBA_ERROR;
3808
3809         /*
3810          * All error attention handlers are posted to
3811          * worker thread
3812          */
3813         phba->work_ha |= HA_ERATT;
3814         phba->work_hs = HS_FFER3;
3815
3816         lpfc_worker_wake_up(phba);
3817
3818         return;
3819 }
3820
3821 /**
3822  * lpfc_poll_eratt - Error attention polling timer timeout handler
3823  * @t: Context to fetch pointer to address of HBA context object from.
3824  *
3825  * This function is invoked by the Error Attention polling timer when the
3826  * timer times out. It will check the SLI Error Attention register for
3827  * possible attention events. If so, it will post an Error Attention event
3828  * and wake up worker thread to process it. Otherwise, it will set up the
3829  * Error Attention polling timer for the next poll.
3830  **/
3831 void lpfc_poll_eratt(struct timer_list *t)
3832 {
3833         struct lpfc_hba *phba;
3834         uint32_t eratt = 0;
3835         uint64_t sli_intr, cnt;
3836
3837         phba = from_timer(phba, t, eratt_poll);
3838
3839         /* Here we will also keep track of interrupts per sec of the hba */
3840         sli_intr = phba->sli.slistat.sli_intr;
3841
3842         if (phba->sli.slistat.sli_prev_intr > sli_intr)
3843                 cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3844                         sli_intr);
3845         else
3846                 cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3847
3848         /* 64-bit integer division not supported on 32-bit x86 - use do_div */
3849         do_div(cnt, phba->eratt_poll_interval);
3850         phba->sli.slistat.sli_ips = cnt;
3851
3852         phba->sli.slistat.sli_prev_intr = sli_intr;
3853
3854         /* Check chip HA register for error event */
3855         eratt = lpfc_sli_check_eratt(phba);
3856
3857         if (eratt)
3858                 /* Tell the worker thread there is work to do */
3859                 lpfc_worker_wake_up(phba);
3860         else
3861                 /* Restart the timer for next eratt poll */
3862                 mod_timer(&phba->eratt_poll,
3863                           jiffies +
3864                           msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3865         return;
3866 }
3867
3868
3869 /**
3870  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3871  * @phba: Pointer to HBA context object.
3872  * @pring: Pointer to driver SLI ring object.
3873  * @mask: Host attention register mask for this ring.
3874  *
3875  * This function is called from the interrupt context when there is a ring
3876  * event for the fcp ring. The caller does not hold any lock.
3877  * The function processes each response iocb in the response ring until it
3878  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3879  * LE bit set. The function will call the completion handler of the command iocb
3880  * if the response iocb indicates a completion for a command iocb or it is
3881  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3882  * function if this is an unsolicited iocb.
3883  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3884  * to check it explicitly.
3885  */
3886 int
3887 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3888                                 struct lpfc_sli_ring *pring, uint32_t mask)
3889 {
3890         struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3891         IOCB_t *irsp = NULL;
3892         IOCB_t *entry = NULL;
3893         struct lpfc_iocbq *cmdiocbq = NULL;
3894         struct lpfc_iocbq rspiocbq;
3895         uint32_t status;
3896         uint32_t portRspPut, portRspMax;
3897         int rc = 1;
3898         lpfc_iocb_type type;
3899         unsigned long iflag;
3900         uint32_t rsp_cmpl = 0;
3901
3902         spin_lock_irqsave(&phba->hbalock, iflag);
3903         pring->stats.iocb_event++;
3904
3905         /*
3906          * The next available response entry should never exceed the maximum
3907          * entries.  If it does, treat it as an adapter hardware error.
3908          */
3909         portRspMax = pring->sli.sli3.numRiocb;
3910         portRspPut = le32_to_cpu(pgp->rspPutInx);
3911         if (unlikely(portRspPut >= portRspMax)) {
3912                 lpfc_sli_rsp_pointers_error(phba, pring);
3913                 spin_unlock_irqrestore(&phba->hbalock, iflag);
3914                 return 1;
3915         }
3916         if (phba->fcp_ring_in_use) {
3917                 spin_unlock_irqrestore(&phba->hbalock, iflag);
3918                 return 1;
3919         } else
3920                 phba->fcp_ring_in_use = 1;
3921
3922         rmb();
3923         while (pring->sli.sli3.rspidx != portRspPut) {
3924                 /*
3925                  * Fetch an entry off the ring and copy it into a local data
3926                  * structure.  The copy involves a byte-swap since the
3927                  * network byte order and pci byte orders are different.
3928                  */
3929                 entry = lpfc_resp_iocb(phba, pring);
3930                 phba->last_completion_time = jiffies;
3931
3932                 if (++pring->sli.sli3.rspidx >= portRspMax)
3933                         pring->sli.sli3.rspidx = 0;
3934
3935                 lpfc_sli_pcimem_bcopy((uint32_t *) entry,
3936                                       (uint32_t *) &rspiocbq.iocb,
3937                                       phba->iocb_rsp_size);
3938                 INIT_LIST_HEAD(&(rspiocbq.list));
3939                 irsp = &rspiocbq.iocb;
3940
3941                 type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
3942                 pring->stats.iocb_rsp++;
3943                 rsp_cmpl++;
3944
3945                 if (unlikely(irsp->ulpStatus)) {
3946                         /*
3947                          * If resource errors reported from HBA, reduce
3948                          * queuedepths of the SCSI device.
3949                          */
3950                         if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
3951                             ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
3952                              IOERR_NO_RESOURCES)) {
3953                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
3954                                 phba->lpfc_rampdown_queue_depth(phba);
3955                                 spin_lock_irqsave(&phba->hbalock, iflag);
3956                         }
3957
3958                         /* Rsp ring <ringno> error: IOCB */
3959                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3960                                         "0336 Rsp Ring %d error: IOCB Data: "
3961                                         "x%x x%x x%x x%x x%x x%x x%x x%x\n",
3962                                         pring->ringno,
3963                                         irsp->un.ulpWord[0],
3964                                         irsp->un.ulpWord[1],
3965                                         irsp->un.ulpWord[2],
3966                                         irsp->un.ulpWord[3],
3967                                         irsp->un.ulpWord[4],
3968                                         irsp->un.ulpWord[5],
3969                                         *(uint32_t *)&irsp->un1,
3970                                         *((uint32_t *)&irsp->un1 + 1));
3971                 }
3972
3973                 switch (type) {
3974                 case LPFC_ABORT_IOCB:
3975                 case LPFC_SOL_IOCB:
3976                         /*
3977                          * Idle exchange closed via ABTS from port.  No iocb
3978                          * resources need to be recovered.
3979                          */
3980                         if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
3981                                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
3982                                                 "0333 IOCB cmd 0x%x"
3983                                                 " processed. Skipping"
3984                                                 " completion\n",
3985                                                 irsp->ulpCommand);
3986                                 break;
3987                         }
3988
3989                         spin_unlock_irqrestore(&phba->hbalock, iflag);
3990                         cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
3991                                                          &rspiocbq);
3992                         spin_lock_irqsave(&phba->hbalock, iflag);
3993                         if (unlikely(!cmdiocbq))
3994                                 break;
3995                         if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED)
3996                                 cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
3997                         if (cmdiocbq->iocb_cmpl) {
3998                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
3999                                 (cmdiocbq->iocb_cmpl)(phba, cmdiocbq,
4000                                                       &rspiocbq);
4001                                 spin_lock_irqsave(&phba->hbalock, iflag);
4002                         }
4003                         break;
4004                 case LPFC_UNSOL_IOCB:
4005                         spin_unlock_irqrestore(&phba->hbalock, iflag);
4006                         lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
4007                         spin_lock_irqsave(&phba->hbalock, iflag);
4008                         break;
4009                 default:
4010                         if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
4011                                 char adaptermsg[LPFC_MAX_ADPTMSG];
4012                                 memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4013                                 memcpy(&adaptermsg[0], (uint8_t *) irsp,
4014                                        MAX_MSG_DATA);
4015                                 dev_warn(&((phba->pcidev)->dev),
4016                                          "lpfc%d: %s\n",
4017                                          phba->brd_no, adaptermsg);
4018                         } else {
4019                                 /* Unknown IOCB command */
4020                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4021                                                 "0334 Unknown IOCB command "
4022                                                 "Data: x%x, x%x x%x x%x x%x\n",
4023                                                 type, irsp->ulpCommand,
4024                                                 irsp->ulpStatus,
4025                                                 irsp->ulpIoTag,
4026                                                 irsp->ulpContext);
4027                         }
4028                         break;
4029                 }
4030
4031                 /*
4032                  * The response IOCB has been processed.  Update the ring
4033                  * pointer in SLIM.  If the port response put pointer has not
4034                  * been updated, sync the pgp->rspPutInx and fetch the new port
4035                  * response put pointer.
4036                  */
4037                 writel(pring->sli.sli3.rspidx,
4038                         &phba->host_gp[pring->ringno].rspGetInx);
4039
4040                 if (pring->sli.sli3.rspidx == portRspPut)
4041                         portRspPut = le32_to_cpu(pgp->rspPutInx);
4042         }
4043
4044         if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
4045                 pring->stats.iocb_rsp_full++;
4046                 status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4047                 writel(status, phba->CAregaddr);
4048                 readl(phba->CAregaddr);
4049         }
4050         if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4051                 pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4052                 pring->stats.iocb_cmd_empty++;
4053
4054                 /* Force update of the local copy of cmdGetInx */
4055                 pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4056                 lpfc_sli_resume_iocb(phba, pring);
4057
4058                 if ((pring->lpfc_sli_cmd_available))
4059                         (pring->lpfc_sli_cmd_available) (phba, pring);
4060
4061         }
4062
4063         phba->fcp_ring_in_use = 0;
4064         spin_unlock_irqrestore(&phba->hbalock, iflag);
4065         return rc;
4066 }
4067
4068 /**
4069  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
4070  * @phba: Pointer to HBA context object.
4071  * @pring: Pointer to driver SLI ring object.
4072  * @rspiocbp: Pointer to driver response IOCB object.
4073  *
4074  * This function is called from the worker thread when there is a slow-path
4075  * response IOCB to process. This function chains all the response iocbs until
4076  * seeing the iocb with the LE bit set. The function will call
4077  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
4078  * completion of a command iocb. The function will call the
4079  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
4080  * The function frees the resources or calls the completion handler if this
4081  * iocb is an abort completion. The function returns NULL when the response
4082  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
4083  * this function shall chain the iocb on to the iocb_continueq and return the
4084  * response iocb passed in.
4085  **/
4086 static struct lpfc_iocbq *
4087 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
4088                         struct lpfc_iocbq *rspiocbp)
4089 {
4090         struct lpfc_iocbq *saveq;
4091         struct lpfc_iocbq *cmdiocbp;
4092         struct lpfc_iocbq *next_iocb;
4093         IOCB_t *irsp = NULL;
4094         uint32_t free_saveq;
4095         uint8_t iocb_cmd_type;
4096         lpfc_iocb_type type;
4097         unsigned long iflag;
4098         int rc;
4099
4100         spin_lock_irqsave(&phba->hbalock, iflag);
4101         /* First add the response iocb to the countinueq list */
4102         list_add_tail(&rspiocbp->list, &(pring->iocb_continueq));
4103         pring->iocb_continueq_cnt++;
4104
4105         /* Now, determine whether the list is completed for processing */
4106         irsp = &rspiocbp->iocb;
4107         if (irsp->ulpLe) {
4108                 /*
4109                  * By default, the driver expects to free all resources
4110                  * associated with this iocb completion.
4111                  */
4112                 free_saveq = 1;
4113                 saveq = list_get_first(&pring->iocb_continueq,
4114                                        struct lpfc_iocbq, list);
4115                 irsp = &(saveq->iocb);
4116                 list_del_init(&pring->iocb_continueq);
4117                 pring->iocb_continueq_cnt = 0;
4118
4119                 pring->stats.iocb_rsp++;
4120
4121                 /*
4122                  * If resource errors reported from HBA, reduce
4123                  * queuedepths of the SCSI device.
4124                  */
4125                 if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
4126                     ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
4127                      IOERR_NO_RESOURCES)) {
4128                         spin_unlock_irqrestore(&phba->hbalock, iflag);
4129                         phba->lpfc_rampdown_queue_depth(phba);
4130                         spin_lock_irqsave(&phba->hbalock, iflag);
4131                 }
4132
4133                 if (irsp->ulpStatus) {
4134                         /* Rsp ring <ringno> error: IOCB */
4135                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4136                                         "0328 Rsp Ring %d error: "
4137                                         "IOCB Data: "
4138                                         "x%x x%x x%x x%x "
4139                                         "x%x x%x x%x x%x "
4140                                         "x%x x%x x%x x%x "
4141                                         "x%x x%x x%x x%x\n",
4142                                         pring->ringno,
4143                                         irsp->un.ulpWord[0],
4144                                         irsp->un.ulpWord[1],
4145                                         irsp->un.ulpWord[2],
4146                                         irsp->un.ulpWord[3],
4147                                         irsp->un.ulpWord[4],
4148                                         irsp->un.ulpWord[5],
4149                                         *(((uint32_t *) irsp) + 6),
4150                                         *(((uint32_t *) irsp) + 7),
4151                                         *(((uint32_t *) irsp) + 8),
4152                                         *(((uint32_t *) irsp) + 9),
4153                                         *(((uint32_t *) irsp) + 10),
4154                                         *(((uint32_t *) irsp) + 11),
4155                                         *(((uint32_t *) irsp) + 12),
4156                                         *(((uint32_t *) irsp) + 13),
4157                                         *(((uint32_t *) irsp) + 14),
4158                                         *(((uint32_t *) irsp) + 15));
4159                 }
4160
4161                 /*
4162                  * Fetch the IOCB command type and call the correct completion
4163                  * routine. Solicited and Unsolicited IOCBs on the ELS ring
4164                  * get freed back to the lpfc_iocb_list by the discovery
4165                  * kernel thread.
4166                  */
4167                 iocb_cmd_type = irsp->ulpCommand & CMD_IOCB_MASK;
4168                 type = lpfc_sli_iocb_cmd_type(iocb_cmd_type);
4169                 switch (type) {
4170                 case LPFC_SOL_IOCB:
4171                         spin_unlock_irqrestore(&phba->hbalock, iflag);
4172                         rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
4173                         spin_lock_irqsave(&phba->hbalock, iflag);
4174                         break;
4175
4176                 case LPFC_UNSOL_IOCB:
4177                         spin_unlock_irqrestore(&phba->hbalock, iflag);
4178                         rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
4179                         spin_lock_irqsave(&phba->hbalock, iflag);
4180                         if (!rc)
4181                                 free_saveq = 0;
4182                         break;
4183
4184                 case LPFC_ABORT_IOCB:
4185                         cmdiocbp = NULL;
4186                         if (irsp->ulpCommand != CMD_XRI_ABORTED_CX) {
4187                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4188                                 cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring,
4189                                                                  saveq);
4190                                 spin_lock_irqsave(&phba->hbalock, iflag);
4191                         }
4192                         if (cmdiocbp) {
4193                                 /* Call the specified completion routine */
4194                                 if (cmdiocbp->iocb_cmpl) {
4195                                         spin_unlock_irqrestore(&phba->hbalock,
4196                                                                iflag);
4197                                         (cmdiocbp->iocb_cmpl)(phba, cmdiocbp,
4198                                                               saveq);
4199                                         spin_lock_irqsave(&phba->hbalock,
4200                                                           iflag);
4201                                 } else
4202                                         __lpfc_sli_release_iocbq(phba,
4203                                                                  cmdiocbp);
4204                         }
4205                         break;
4206
4207                 case LPFC_UNKNOWN_IOCB:
4208                         if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
4209                                 char adaptermsg[LPFC_MAX_ADPTMSG];
4210                                 memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4211                                 memcpy(&adaptermsg[0], (uint8_t *)irsp,
4212                                        MAX_MSG_DATA);
4213                                 dev_warn(&((phba->pcidev)->dev),
4214                                          "lpfc%d: %s\n",
4215                                          phba->brd_no, adaptermsg);
4216                         } else {
4217                                 /* Unknown IOCB command */
4218                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4219                                                 "0335 Unknown IOCB "
4220                                                 "command Data: x%x "
4221                                                 "x%x x%x x%x\n",
4222                                                 irsp->ulpCommand,
4223                                                 irsp->ulpStatus,
4224                                                 irsp->ulpIoTag,
4225                                                 irsp->ulpContext);
4226                         }
4227                         break;
4228                 }
4229
4230                 if (free_saveq) {
4231                         list_for_each_entry_safe(rspiocbp, next_iocb,
4232                                                  &saveq->list, list) {
4233                                 list_del_init(&rspiocbp->list);
4234                                 __lpfc_sli_release_iocbq(phba, rspiocbp);
4235                         }
4236                         __lpfc_sli_release_iocbq(phba, saveq);
4237                 }
4238                 rspiocbp = NULL;
4239         }
4240         spin_unlock_irqrestore(&phba->hbalock, iflag);
4241         return rspiocbp;
4242 }
4243
4244 /**
4245  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
4246  * @phba: Pointer to HBA context object.
4247  * @pring: Pointer to driver SLI ring object.
4248  * @mask: Host attention register mask for this ring.
4249  *
4250  * This routine wraps the actual slow_ring event process routine from the
4251  * API jump table function pointer from the lpfc_hba struct.
4252  **/
4253 void
4254 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
4255                                 struct lpfc_sli_ring *pring, uint32_t mask)
4256 {
4257         phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
4258 }
4259
4260 /**
4261  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
4262  * @phba: Pointer to HBA context object.
4263  * @pring: Pointer to driver SLI ring object.
4264  * @mask: Host attention register mask for this ring.
4265  *
4266  * This function is called from the worker thread when there is a ring event
4267  * for non-fcp rings. The caller does not hold any lock. The function will
4268  * remove each response iocb in the response ring and calls the handle
4269  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4270  **/
4271 static void
4272 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
4273                                    struct lpfc_sli_ring *pring, uint32_t mask)
4274 {
4275         struct lpfc_pgp *pgp;
4276         IOCB_t *entry;
4277         IOCB_t *irsp = NULL;
4278         struct lpfc_iocbq *rspiocbp = NULL;
4279         uint32_t portRspPut, portRspMax;
4280         unsigned long iflag;
4281         uint32_t status;
4282
4283         pgp = &phba->port_gp[pring->ringno];
4284         spin_lock_irqsave(&phba->hbalock, iflag);
4285         pring->stats.iocb_event++;
4286
4287         /*
4288          * The next available response entry should never exceed the maximum
4289          * entries.  If it does, treat it as an adapter hardware error.
4290          */
4291         portRspMax = pring->sli.sli3.numRiocb;
4292         portRspPut = le32_to_cpu(pgp->rspPutInx);
4293         if (portRspPut >= portRspMax) {
4294                 /*
4295                  * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
4296                  * rsp ring <portRspMax>
4297                  */
4298                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4299                                 "0303 Ring %d handler: portRspPut %d "
4300                                 "is bigger than rsp ring %d\n",
4301                                 pring->ringno, portRspPut, portRspMax);
4302
4303                 phba->link_state = LPFC_HBA_ERROR;
4304                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4305
4306                 phba->work_hs = HS_FFER3;
4307                 lpfc_handle_eratt(phba);
4308
4309                 return;
4310         }
4311
4312         rmb();
4313         while (pring->sli.sli3.rspidx != portRspPut) {
4314                 /*
4315                  * Build a completion list and call the appropriate handler.
4316                  * The process is to get the next available response iocb, get
4317                  * a free iocb from the list, copy the response data into the
4318                  * free iocb, insert to the continuation list, and update the
4319                  * next response index to slim.  This process makes response
4320                  * iocb's in the ring available to DMA as fast as possible but
4321                  * pays a penalty for a copy operation.  Since the iocb is
4322                  * only 32 bytes, this penalty is considered small relative to
4323                  * the PCI reads for register values and a slim write.  When
4324                  * the ulpLe field is set, the entire Command has been
4325                  * received.
4326                  */
4327                 entry = lpfc_resp_iocb(phba, pring);
4328
4329                 phba->last_completion_time = jiffies;
4330                 rspiocbp = __lpfc_sli_get_iocbq(phba);
4331                 if (rspiocbp == NULL) {
4332                         printk(KERN_ERR "%s: out of buffers! Failing "
4333                                "completion.\n", __func__);
4334                         break;
4335                 }
4336
4337                 lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
4338                                       phba->iocb_rsp_size);
4339                 irsp = &rspiocbp->iocb;
4340
4341                 if (++pring->sli.sli3.rspidx >= portRspMax)
4342                         pring->sli.sli3.rspidx = 0;
4343
4344                 if (pring->ringno == LPFC_ELS_RING) {
4345                         lpfc_debugfs_slow_ring_trc(phba,
4346                         "IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
4347                                 *(((uint32_t *) irsp) + 4),
4348                                 *(((uint32_t *) irsp) + 6),
4349                                 *(((uint32_t *) irsp) + 7));
4350                 }
4351
4352                 writel(pring->sli.sli3.rspidx,
4353                         &phba->host_gp[pring->ringno].rspGetInx);
4354
4355                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4356                 /* Handle the response IOCB */
4357                 rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
4358                 spin_lock_irqsave(&phba->hbalock, iflag);
4359
4360                 /*
4361                  * If the port response put pointer has not been updated, sync
4362                  * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
4363                  * response put pointer.
4364                  */
4365                 if (pring->sli.sli3.rspidx == portRspPut) {
4366                         portRspPut = le32_to_cpu(pgp->rspPutInx);
4367                 }
4368         } /* while (pring->sli.sli3.rspidx != portRspPut) */
4369
4370         if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
4371                 /* At least one response entry has been freed */
4372                 pring->stats.iocb_rsp_full++;
4373                 /* SET RxRE_RSP in Chip Att register */
4374                 status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4375                 writel(status, phba->CAregaddr);
4376                 readl(phba->CAregaddr); /* flush */
4377         }
4378         if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4379                 pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4380                 pring->stats.iocb_cmd_empty++;
4381
4382                 /* Force update of the local copy of cmdGetInx */
4383                 pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4384                 lpfc_sli_resume_iocb(phba, pring);
4385
4386                 if ((pring->lpfc_sli_cmd_available))
4387                         (pring->lpfc_sli_cmd_available) (phba, pring);
4388
4389         }
4390
4391         spin_unlock_irqrestore(&phba->hbalock, iflag);
4392         return;
4393 }
4394
4395 /**
4396  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
4397  * @phba: Pointer to HBA context object.
4398  * @pring: Pointer to driver SLI ring object.
4399  * @mask: Host attention register mask for this ring.
4400  *
4401  * This function is called from the worker thread when there is a pending
4402  * ELS response iocb on the driver internal slow-path response iocb worker
4403  * queue. The caller does not hold any lock. The function will remove each
4404  * response iocb from the response worker queue and calls the handle
4405  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4406  **/
4407 static void
4408 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
4409                                    struct lpfc_sli_ring *pring, uint32_t mask)
4410 {
4411         struct lpfc_iocbq *irspiocbq;
4412         struct hbq_dmabuf *dmabuf;
4413         struct lpfc_cq_event *cq_event;
4414         unsigned long iflag;
4415         int count = 0;
4416
4417         spin_lock_irqsave(&phba->hbalock, iflag);
4418         phba->hba_flag &= ~HBA_SP_QUEUE_EVT;
4419         spin_unlock_irqrestore(&phba->hbalock, iflag);
4420         while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4421                 /* Get the response iocb from the head of work queue */
4422                 spin_lock_irqsave(&phba->hbalock, iflag);
4423                 list_remove_head(&phba->sli4_hba.sp_queue_event,
4424                                  cq_event, struct lpfc_cq_event, list);
4425                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4426
4427                 switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4428                 case CQE_CODE_COMPL_WQE:
4429                         irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4430                                                  cq_event);
4431                         /* Translate ELS WCQE to response IOCBQ */
4432                         irspiocbq = lpfc_sli4_els_wcqe_to_rspiocbq(phba,
4433                                                                    irspiocbq);
4434                         if (irspiocbq)
4435                                 lpfc_sli_sp_handle_rspiocb(phba, pring,
4436                                                            irspiocbq);
4437                         count++;
4438                         break;
4439                 case CQE_CODE_RECEIVE:
4440                 case CQE_CODE_RECEIVE_V1:
4441                         dmabuf = container_of(cq_event, struct hbq_dmabuf,
4442                                               cq_event);
4443                         lpfc_sli4_handle_received_buffer(phba, dmabuf);
4444                         count++;
4445                         break;
4446                 default:
4447                         break;
4448                 }
4449
4450                 /* Limit the number of events to 64 to avoid soft lockups */
4451                 if (count == 64)
4452                         break;
4453         }
4454 }
4455
4456 /**
4457  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4458  * @phba: Pointer to HBA context object.
4459  * @pring: Pointer to driver SLI ring object.
4460  *
4461  * This function aborts all iocbs in the given ring and frees all the iocb
4462  * objects in txq. This function issues an abort iocb for all the iocb commands
4463  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4464  * the return of this function. The caller is not required to hold any locks.
4465  **/
4466 void
4467 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4468 {
4469         LIST_HEAD(completions);
4470         struct lpfc_iocbq *iocb, *next_iocb;
4471
4472         if (pring->ringno == LPFC_ELS_RING) {
4473                 lpfc_fabric_abort_hba(phba);
4474         }
4475
4476         /* Error everything on txq and txcmplq
4477          * First do the txq.
4478          */
4479         if (phba->sli_rev >= LPFC_SLI_REV4) {
4480                 spin_lock_irq(&pring->ring_lock);
4481                 list_splice_init(&pring->txq, &completions);
4482                 pring->txq_cnt = 0;
4483                 spin_unlock_irq(&pring->ring_lock);
4484
4485                 spin_lock_irq(&phba->hbalock);
4486                 /* Next issue ABTS for everything on the txcmplq */
4487                 list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4488                         lpfc_sli_issue_abort_iotag(phba, pring, iocb, NULL);
4489                 spin_unlock_irq(&phba->hbalock);
4490         } else {
4491                 spin_lock_irq(&phba->hbalock);
4492                 list_splice_init(&pring->txq, &completions);
4493                 pring->txq_cnt = 0;
4494
4495                 /* Next issue ABTS for everything on the txcmplq */
4496                 list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list)
4497                         lpfc_sli_issue_abort_iotag(phba, pring, iocb, NULL);
4498                 spin_unlock_irq(&phba->hbalock);
4499         }
4500         /* Make sure HBA is alive */
4501         lpfc_issue_hb_tmo(phba);
4502
4503         /* Cancel all the IOCBs from the completions list */
4504         lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
4505                               IOERR_SLI_ABORTED);
4506 }
4507
4508 /**
4509  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4510  * @phba: Pointer to HBA context object.
4511  *
4512  * This function aborts all iocbs in FCP rings and frees all the iocb
4513  * objects in txq. This function issues an abort iocb for all the iocb commands
4514  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4515  * the return of this function. The caller is not required to hold any locks.
4516  **/
4517 void
4518 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4519 {
4520         struct lpfc_sli *psli = &phba->sli;
4521         struct lpfc_sli_ring  *pring;
4522         uint32_t i;
4523
4524         /* Look on all the FCP Rings for the iotag */
4525         if (phba->sli_rev >= LPFC_SLI_REV4) {
4526                 for (i = 0; i < phba->cfg_hdw_queue; i++) {
4527                         pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4528                         lpfc_sli_abort_iocb_ring(phba, pring);
4529                 }
4530         } else {
4531                 pring = &psli->sli3_ring[LPFC_FCP_RING];
4532                 lpfc_sli_abort_iocb_ring(phba, pring);
4533         }
4534 }
4535
4536 /**
4537  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4538  * @phba: Pointer to HBA context object.
4539  *
4540  * This function flushes all iocbs in the IO ring and frees all the iocb
4541  * objects in txq and txcmplq. This function will not issue abort iocbs
4542  * for all the iocb commands in txcmplq, they will just be returned with
4543  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4544  * slot has been permanently disabled.
4545  **/
4546 void
4547 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4548 {
4549         LIST_HEAD(txq);
4550         LIST_HEAD(txcmplq);
4551         struct lpfc_sli *psli = &phba->sli;
4552         struct lpfc_sli_ring  *pring;
4553         uint32_t i;
4554         struct lpfc_iocbq *piocb, *next_iocb;
4555
4556         spin_lock_irq(&phba->hbalock);
4557         if (phba->hba_flag & HBA_IOQ_FLUSH ||
4558             !phba->sli4_hba.hdwq) {
4559                 spin_unlock_irq(&phba->hbalock);
4560                 return;
4561         }
4562         /* Indicate the I/O queues are flushed */
4563         phba->hba_flag |= HBA_IOQ_FLUSH;
4564         spin_unlock_irq(&phba->hbalock);
4565
4566         /* Look on all the FCP Rings for the iotag */
4567         if (phba->sli_rev >= LPFC_SLI_REV4) {
4568                 for (i = 0; i < phba->cfg_hdw_queue; i++) {
4569                         pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4570
4571                         spin_lock_irq(&pring->ring_lock);
4572                         /* Retrieve everything on txq */
4573                         list_splice_init(&pring->txq, &txq);
4574                         list_for_each_entry_safe(piocb, next_iocb,
4575                                                  &pring->txcmplq, list)
4576                                 piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4577                         /* Retrieve everything on the txcmplq */
4578                         list_splice_init(&pring->txcmplq, &txcmplq);
4579                         pring->txq_cnt = 0;
4580                         pring->txcmplq_cnt = 0;
4581                         spin_unlock_irq(&pring->ring_lock);
4582
4583                         /* Flush the txq */
4584                         lpfc_sli_cancel_iocbs(phba, &txq,
4585                                               IOSTAT_LOCAL_REJECT,
4586                                               IOERR_SLI_DOWN);
4587                         /* Flush the txcmplq */
4588                         lpfc_sli_cancel_iocbs(phba, &txcmplq,
4589                                               IOSTAT_LOCAL_REJECT,
4590                                               IOERR_SLI_DOWN);
4591                         if (unlikely(pci_channel_offline(phba->pcidev)))
4592                                 lpfc_sli4_io_xri_aborted(phba, NULL, 0);
4593                 }
4594         } else {
4595                 pring = &psli->sli3_ring[LPFC_FCP_RING];
4596
4597                 spin_lock_irq(&phba->hbalock);
4598                 /* Retrieve everything on txq */
4599                 list_splice_init(&pring->txq, &txq);
4600                 list_for_each_entry_safe(piocb, next_iocb,
4601                                          &pring->txcmplq, list)
4602                         piocb->iocb_flag &= ~LPFC_IO_ON_TXCMPLQ;
4603                 /* Retrieve everything on the txcmplq */
4604                 list_splice_init(&pring->txcmplq, &txcmplq);
4605                 pring->txq_cnt = 0;
4606                 pring->txcmplq_cnt = 0;
4607                 spin_unlock_irq(&phba->hbalock);
4608
4609                 /* Flush the txq */
4610                 lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4611                                       IOERR_SLI_DOWN);
4612                 /* Flush the txcmpq */
4613                 lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4614                                       IOERR_SLI_DOWN);
4615         }
4616 }
4617
4618 /**
4619  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4620  * @phba: Pointer to HBA context object.
4621  * @mask: Bit mask to be checked.
4622  *
4623  * This function reads the host status register and compares
4624  * with the provided bit mask to check if HBA completed
4625  * the restart. This function will wait in a loop for the
4626  * HBA to complete restart. If the HBA does not restart within
4627  * 15 iterations, the function will reset the HBA again. The
4628  * function returns 1 when HBA fail to restart otherwise returns
4629  * zero.
4630  **/
4631 static int
4632 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4633 {
4634         uint32_t status;
4635         int i = 0;
4636         int retval = 0;
4637
4638         /* Read the HBA Host Status Register */
4639         if (lpfc_readl(phba->HSregaddr, &status))
4640                 return 1;
4641
4642         phba->hba_flag |= HBA_NEEDS_CFG_PORT;
4643
4644         /*
4645          * Check status register every 100ms for 5 retries, then every
4646          * 500ms for 5, then every 2.5 sec for 5, then reset board and
4647          * every 2.5 sec for 4.
4648          * Break our of the loop if errors occurred during init.
4649          */
4650         while (((status & mask) != mask) &&
4651                !(status & HS_FFERM) &&
4652                i++ < 20) {
4653
4654                 if (i <= 5)
4655                         msleep(10);
4656                 else if (i <= 10)
4657                         msleep(500);
4658                 else
4659                         msleep(2500);
4660
4661                 if (i == 15) {
4662                                 /* Do post */
4663                         phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4664                         lpfc_sli_brdrestart(phba);
4665                 }
4666                 /* Read the HBA Host Status Register */
4667                 if (lpfc_readl(phba->HSregaddr, &status)) {
4668                         retval = 1;
4669                         break;
4670                 }
4671         }
4672
4673         /* Check to see if any errors occurred during init */
4674         if ((status & HS_FFERM) || (i >= 20)) {
4675                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4676                                 "2751 Adapter failed to restart, "
4677                                 "status reg x%x, FW Data: A8 x%x AC x%x\n",
4678                                 status,
4679                                 readl(phba->MBslimaddr + 0xa8),
4680                                 readl(phba->MBslimaddr + 0xac));
4681                 phba->link_state = LPFC_HBA_ERROR;
4682                 retval = 1;
4683         }
4684
4685         return retval;
4686 }
4687
4688 /**
4689  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4690  * @phba: Pointer to HBA context object.
4691  * @mask: Bit mask to be checked.
4692  *
4693  * This function checks the host status register to check if HBA is
4694  * ready. This function will wait in a loop for the HBA to be ready
4695  * If the HBA is not ready , the function will will reset the HBA PCI
4696  * function again. The function returns 1 when HBA fail to be ready
4697  * otherwise returns zero.
4698  **/
4699 static int
4700 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4701 {
4702         uint32_t status;
4703         int retval = 0;
4704
4705         /* Read the HBA Host Status Register */
4706         status = lpfc_sli4_post_status_check(phba);
4707
4708         if (status) {
4709                 phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4710                 lpfc_sli_brdrestart(phba);
4711                 status = lpfc_sli4_post_status_check(phba);
4712         }
4713
4714         /* Check to see if any errors occurred during init */
4715         if (status) {
4716                 phba->link_state = LPFC_HBA_ERROR;
4717                 retval = 1;
4718         } else
4719                 phba->sli4_hba.intr_enable = 0;
4720
4721         phba->hba_flag &= ~HBA_SETUP;
4722         return retval;
4723 }
4724
4725 /**
4726  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4727  * @phba: Pointer to HBA context object.
4728  * @mask: Bit mask to be checked.
4729  *
4730  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4731  * from the API jump table function pointer from the lpfc_hba struct.
4732  **/
4733 int
4734 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4735 {
4736         return phba->lpfc_sli_brdready(phba, mask);
4737 }
4738
4739 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4740
4741 /**
4742  * lpfc_reset_barrier - Make HBA ready for HBA reset
4743  * @phba: Pointer to HBA context object.
4744  *
4745  * This function is called before resetting an HBA. This function is called
4746  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4747  **/
4748 void lpfc_reset_barrier(struct lpfc_hba *phba)
4749 {
4750         uint32_t __iomem *resp_buf;
4751         uint32_t __iomem *mbox_buf;
4752         volatile uint32_t mbox;
4753         uint32_t hc_copy, ha_copy, resp_data;
4754         int  i;
4755         uint8_t hdrtype;
4756
4757         lockdep_assert_held(&phba->hbalock);
4758
4759         pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4760         if (hdrtype != 0x80 ||
4761             (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4762              FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4763                 return;
4764
4765         /*
4766          * Tell the other part of the chip to suspend temporarily all
4767          * its DMA activity.
4768          */
4769         resp_buf = phba->MBslimaddr;
4770
4771         /* Disable the error attention */
4772         if (lpfc_readl(phba->HCregaddr, &hc_copy))
4773                 return;
4774         writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4775         readl(phba->HCregaddr); /* flush */
4776         phba->link_flag |= LS_IGNORE_ERATT;
4777
4778         if (lpfc_readl(phba->HAregaddr, &ha_copy))
4779                 return;
4780         if (ha_copy & HA_ERATT) {
4781                 /* Clear Chip error bit */
4782                 writel(HA_ERATT, phba->HAregaddr);
4783                 phba->pport->stopped = 1;
4784         }
4785
4786         mbox = 0;
4787         ((MAILBOX_t *)&mbox)->mbxCommand = MBX_KILL_BOARD;
4788         ((MAILBOX_t *)&mbox)->mbxOwner = OWN_CHIP;
4789
4790         writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4791         mbox_buf = phba->MBslimaddr;
4792         writel(mbox, mbox_buf);
4793
4794         for (i = 0; i < 50; i++) {
4795                 if (lpfc_readl((resp_buf + 1), &resp_data))
4796                         return;
4797                 if (resp_data != ~(BARRIER_TEST_PATTERN))
4798                         mdelay(1);
4799                 else
4800                         break;
4801         }
4802         resp_data = 0;
4803         if (lpfc_readl((resp_buf + 1), &resp_data))
4804                 return;
4805         if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4806                 if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4807                     phba->pport->stopped)
4808                         goto restore_hc;
4809                 else
4810                         goto clear_errat;
4811         }
4812
4813         ((MAILBOX_t *)&mbox)->mbxOwner = OWN_HOST;
4814         resp_data = 0;
4815         for (i = 0; i < 500; i++) {
4816                 if (lpfc_readl(resp_buf, &resp_data))
4817                         return;
4818                 if (resp_data != mbox)
4819                         mdelay(1);
4820                 else
4821                         break;
4822         }
4823
4824 clear_errat:
4825
4826         while (++i < 500) {
4827                 if (lpfc_readl(phba->HAregaddr, &ha_copy))
4828                         return;
4829                 if (!(ha_copy & HA_ERATT))
4830                         mdelay(1);
4831                 else
4832                         break;
4833         }
4834
4835         if (readl(phba->HAregaddr) & HA_ERATT) {
4836                 writel(HA_ERATT, phba->HAregaddr);
4837                 phba->pport->stopped = 1;
4838         }
4839
4840 restore_hc:
4841         phba->link_flag &= ~LS_IGNORE_ERATT;
4842         writel(hc_copy, phba->HCregaddr);
4843         readl(phba->HCregaddr); /* flush */
4844 }
4845
4846 /**
4847  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4848  * @phba: Pointer to HBA context object.
4849  *
4850  * This function issues a kill_board mailbox command and waits for
4851  * the error attention interrupt. This function is called for stopping
4852  * the firmware processing. The caller is not required to hold any
4853  * locks. This function calls lpfc_hba_down_post function to free
4854  * any pending commands after the kill. The function will return 1 when it
4855  * fails to kill the board else will return 0.
4856  **/
4857 int
4858 lpfc_sli_brdkill(struct lpfc_hba *phba)
4859 {
4860         struct lpfc_sli *psli;
4861         LPFC_MBOXQ_t *pmb;
4862         uint32_t status;
4863         uint32_t ha_copy;
4864         int retval;
4865         int i = 0;
4866
4867         psli = &phba->sli;
4868
4869         /* Kill HBA */
4870         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4871                         "0329 Kill HBA Data: x%x x%x\n",
4872                         phba->pport->port_state, psli->sli_flag);
4873
4874         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4875         if (!pmb)
4876                 return 1;
4877
4878         /* Disable the error attention */
4879         spin_lock_irq(&phba->hbalock);
4880         if (lpfc_readl(phba->HCregaddr, &status)) {
4881                 spin_unlock_irq(&phba->hbalock);
4882                 mempool_free(pmb, phba->mbox_mem_pool);
4883                 return 1;
4884         }
4885         status &= ~HC_ERINT_ENA;
4886         writel(status, phba->HCregaddr);
4887         readl(phba->HCregaddr); /* flush */
4888         phba->link_flag |= LS_IGNORE_ERATT;
4889         spin_unlock_irq(&phba->hbalock);
4890
4891         lpfc_kill_board(phba, pmb);
4892         pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
4893         retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
4894
4895         if (retval != MBX_SUCCESS) {
4896                 if (retval != MBX_BUSY)
4897                         mempool_free(pmb, phba->mbox_mem_pool);
4898                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4899                                 "2752 KILL_BOARD command failed retval %d\n",
4900                                 retval);
4901                 spin_lock_irq(&phba->hbalock);
4902                 phba->link_flag &= ~LS_IGNORE_ERATT;
4903                 spin_unlock_irq(&phba->hbalock);
4904                 return 1;
4905         }
4906
4907         spin_lock_irq(&phba->hbalock);
4908         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
4909         spin_unlock_irq(&phba->hbalock);
4910
4911         mempool_free(pmb, phba->mbox_mem_pool);
4912
4913         /* There is no completion for a KILL_BOARD mbox cmd. Check for an error
4914          * attention every 100ms for 3 seconds. If we don't get ERATT after
4915          * 3 seconds we still set HBA_ERROR state because the status of the
4916          * board is now undefined.
4917          */
4918         if (lpfc_readl(phba->HAregaddr, &ha_copy))
4919                 return 1;
4920         while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
4921                 mdelay(100);
4922                 if (lpfc_readl(phba->HAregaddr, &ha_copy))
4923                         return 1;
4924         }
4925
4926         del_timer_sync(&psli->mbox_tmo);
4927         if (ha_copy & HA_ERATT) {
4928                 writel(HA_ERATT, phba->HAregaddr);
4929                 phba->pport->stopped = 1;
4930         }
4931         spin_lock_irq(&phba->hbalock);
4932         psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
4933         psli->mbox_active = NULL;
4934         phba->link_flag &= ~LS_IGNORE_ERATT;
4935         spin_unlock_irq(&phba->hbalock);
4936
4937         lpfc_hba_down_post(phba);
4938         phba->link_state = LPFC_HBA_ERROR;
4939
4940         return ha_copy & HA_ERATT ? 0 : 1;
4941 }
4942
4943 /**
4944  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
4945  * @phba: Pointer to HBA context object.
4946  *
4947  * This function resets the HBA by writing HC_INITFF to the control
4948  * register. After the HBA resets, this function resets all the iocb ring
4949  * indices. This function disables PCI layer parity checking during
4950  * the reset.
4951  * This function returns 0 always.
4952  * The caller is not required to hold any locks.
4953  **/
4954 int
4955 lpfc_sli_brdreset(struct lpfc_hba *phba)
4956 {
4957         struct lpfc_sli *psli;
4958         struct lpfc_sli_ring *pring;
4959         uint16_t cfg_value;
4960         int i;
4961
4962         psli = &phba->sli;
4963
4964         /* Reset HBA */
4965         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4966                         "0325 Reset HBA Data: x%x x%x\n",
4967                         (phba->pport) ? phba->pport->port_state : 0,
4968                         psli->sli_flag);
4969
4970         /* perform board reset */
4971         phba->fc_eventTag = 0;
4972         phba->link_events = 0;
4973         phba->hba_flag |= HBA_NEEDS_CFG_PORT;
4974         if (phba->pport) {
4975                 phba->pport->fc_myDID = 0;
4976                 phba->pport->fc_prevDID = 0;
4977         }
4978
4979         /* Turn off parity checking and serr during the physical reset */
4980         if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
4981                 return -EIO;
4982
4983         pci_write_config_word(phba->pcidev, PCI_COMMAND,
4984                               (cfg_value &
4985                                ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
4986
4987         psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
4988
4989         /* Now toggle INITFF bit in the Host Control Register */
4990         writel(HC_INITFF, phba->HCregaddr);
4991         mdelay(1);
4992         readl(phba->HCregaddr); /* flush */
4993         writel(0, phba->HCregaddr);
4994         readl(phba->HCregaddr); /* flush */
4995
4996         /* Restore PCI cmd register */
4997         pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
4998
4999         /* Initialize relevant SLI info */
5000         for (i = 0; i < psli->num_rings; i++) {
5001                 pring = &psli->sli3_ring[i];
5002                 pring->flag = 0;
5003                 pring->sli.sli3.rspidx = 0;
5004                 pring->sli.sli3.next_cmdidx  = 0;
5005                 pring->sli.sli3.local_getidx = 0;
5006                 pring->sli.sli3.cmdidx = 0;
5007                 pring->missbufcnt = 0;
5008         }
5009
5010         phba->link_state = LPFC_WARM_START;
5011         return 0;
5012 }
5013
5014 /**
5015  * lpfc_sli4_brdreset - Reset a sli-4 HBA
5016  * @phba: Pointer to HBA context object.
5017  *
5018  * This function resets a SLI4 HBA. This function disables PCI layer parity
5019  * checking during resets the device. The caller is not required to hold
5020  * any locks.
5021  *
5022  * This function returns 0 on success else returns negative error code.
5023  **/
5024 int
5025 lpfc_sli4_brdreset(struct lpfc_hba *phba)
5026 {
5027         struct lpfc_sli *psli = &phba->sli;
5028         uint16_t cfg_value;
5029         int rc = 0;
5030
5031         /* Reset HBA */
5032         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5033                         "0295 Reset HBA Data: x%x x%x x%x\n",
5034                         phba->pport->port_state, psli->sli_flag,
5035                         phba->hba_flag);
5036
5037         /* perform board reset */
5038         phba->fc_eventTag = 0;
5039         phba->link_events = 0;
5040         phba->pport->fc_myDID = 0;
5041         phba->pport->fc_prevDID = 0;
5042         phba->hba_flag &= ~HBA_SETUP;
5043
5044         spin_lock_irq(&phba->hbalock);
5045         psli->sli_flag &= ~(LPFC_PROCESS_LA);
5046         phba->fcf.fcf_flag = 0;
5047         spin_unlock_irq(&phba->hbalock);
5048
5049         /* SLI4 INTF 2: if FW dump is being taken skip INIT_PORT */
5050         if (phba->hba_flag & HBA_FW_DUMP_OP) {
5051                 phba->hba_flag &= ~HBA_FW_DUMP_OP;
5052                 return rc;
5053         }
5054
5055         /* Now physically reset the device */
5056         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5057                         "0389 Performing PCI function reset!\n");
5058
5059         /* Turn off parity checking and serr during the physical reset */
5060         if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
5061                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5062                                 "3205 PCI read Config failed\n");
5063                 return -EIO;
5064         }
5065
5066         pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
5067                               ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5068
5069         /* Perform FCoE PCI function reset before freeing queue memory */
5070         rc = lpfc_pci_function_reset(phba);
5071
5072         /* Restore PCI cmd register */
5073         pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5074
5075         return rc;
5076 }
5077
5078 /**
5079  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
5080  * @phba: Pointer to HBA context object.
5081  *
5082  * This function is called in the SLI initialization code path to
5083  * restart the HBA. The caller is not required to hold any lock.
5084  * This function writes MBX_RESTART mailbox command to the SLIM and
5085  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
5086  * function to free any pending commands. The function enables
5087  * POST only during the first initialization. The function returns zero.
5088  * The function does not guarantee completion of MBX_RESTART mailbox
5089  * command before the return of this function.
5090  **/
5091 static int
5092 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
5093 {
5094         MAILBOX_t *mb;
5095         struct lpfc_sli *psli;
5096         volatile uint32_t word0;
5097         void __iomem *to_slim;
5098         uint32_t hba_aer_enabled;
5099
5100         spin_lock_irq(&phba->hbalock);
5101
5102         /* Take PCIe device Advanced Error Reporting (AER) state */
5103         hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
5104
5105         psli = &phba->sli;
5106
5107         /* Restart HBA */
5108         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5109                         "0337 Restart HBA Data: x%x x%x\n",
5110                         (phba->pport) ? phba->pport->port_state : 0,
5111                         psli->sli_flag);
5112
5113         word0 = 0;
5114         mb = (MAILBOX_t *) &word0;
5115         mb->mbxCommand = MBX_RESTART;
5116         mb->mbxHc = 1;
5117
5118         lpfc_reset_barrier(phba);
5119
5120         to_slim = phba->MBslimaddr;
5121         writel(*(uint32_t *) mb, to_slim);
5122         readl(to_slim); /* flush */
5123
5124         /* Only skip post after fc_ffinit is completed */
5125         if (phba->pport && phba->pport->port_state)
5126                 word0 = 1;      /* This is really setting up word1 */
5127         else
5128                 word0 = 0;      /* This is really setting up word1 */
5129         to_slim = phba->MBslimaddr + sizeof (uint32_t);
5130         writel(*(uint32_t *) mb, to_slim);
5131         readl(to_slim); /* flush */
5132
5133         lpfc_sli_brdreset(phba);
5134         if (phba->pport)
5135                 phba->pport->stopped = 0;
5136         phba->link_state = LPFC_INIT_START;
5137         phba->hba_flag = 0;
5138         spin_unlock_irq(&phba->hbalock);
5139
5140         memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5141         psli->stats_start = ktime_get_seconds();
5142
5143         /* Give the INITFF and Post time to settle. */
5144         mdelay(100);
5145
5146         /* Reset HBA AER if it was enabled, note hba_flag was reset above */
5147         if (hba_aer_enabled)
5148                 pci_disable_pcie_error_reporting(phba->pcidev);
5149
5150         lpfc_hba_down_post(phba);
5151
5152         return 0;
5153 }
5154
5155 /**
5156  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
5157  * @phba: Pointer to HBA context object.
5158  *
5159  * This function is called in the SLI initialization code path to restart
5160  * a SLI4 HBA. The caller is not required to hold any lock.
5161  * At the end of the function, it calls lpfc_hba_down_post function to
5162  * free any pending commands.
5163  **/
5164 static int
5165 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
5166 {
5167         struct lpfc_sli *psli = &phba->sli;
5168         uint32_t hba_aer_enabled;
5169         int rc;
5170
5171         /* Restart HBA */
5172         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5173                         "0296 Restart HBA Data: x%x x%x\n",
5174                         phba->pport->port_state, psli->sli_flag);
5175
5176         /* Take PCIe device Advanced Error Reporting (AER) state */
5177         hba_aer_enabled = phba->hba_flag & HBA_AER_ENABLED;
5178
5179         rc = lpfc_sli4_brdreset(phba);
5180         if (rc) {
5181                 phba->link_state = LPFC_HBA_ERROR;
5182                 goto hba_down_queue;
5183         }
5184
5185         spin_lock_irq(&phba->hbalock);
5186         phba->pport->stopped = 0;
5187         phba->link_state = LPFC_INIT_START;
5188         phba->hba_flag = 0;
5189         spin_unlock_irq(&phba->hbalock);
5190
5191         memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5192         psli->stats_start = ktime_get_seconds();
5193
5194         /* Reset HBA AER if it was enabled, note hba_flag was reset above */
5195         if (hba_aer_enabled)
5196                 pci_disable_pcie_error_reporting(phba->pcidev);
5197
5198 hba_down_queue:
5199         lpfc_hba_down_post(phba);
5200         lpfc_sli4_queue_destroy(phba);
5201
5202         return rc;
5203 }
5204
5205 /**
5206  * lpfc_sli_brdrestart - Wrapper func for restarting hba
5207  * @phba: Pointer to HBA context object.
5208  *
5209  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
5210  * API jump table function pointer from the lpfc_hba struct.
5211 **/
5212 int
5213 lpfc_sli_brdrestart(struct lpfc_hba *phba)
5214 {
5215         return phba->lpfc_sli_brdrestart(phba);
5216 }
5217
5218 /**
5219  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
5220  * @phba: Pointer to HBA context object.
5221  *
5222  * This function is called after a HBA restart to wait for successful
5223  * restart of the HBA. Successful restart of the HBA is indicated by
5224  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
5225  * iteration, the function will restart the HBA again. The function returns
5226  * zero if HBA successfully restarted else returns negative error code.
5227  **/
5228 int
5229 lpfc_sli_chipset_init(struct lpfc_hba *phba)
5230 {
5231         uint32_t status, i = 0;
5232
5233         /* Read the HBA Host Status Register */
5234         if (lpfc_readl(phba->HSregaddr, &status))
5235                 return -EIO;
5236
5237         /* Check status register to see what current state is */
5238         i = 0;
5239         while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
5240
5241                 /* Check every 10ms for 10 retries, then every 100ms for 90
5242                  * retries, then every 1 sec for 50 retires for a total of
5243                  * ~60 seconds before reset the board again and check every
5244                  * 1 sec for 50 retries. The up to 60 seconds before the
5245                  * board ready is required by the Falcon FIPS zeroization
5246                  * complete, and any reset the board in between shall cause
5247                  * restart of zeroization, further delay the board ready.
5248                  */
5249                 if (i++ >= 200) {
5250                         /* Adapter failed to init, timeout, status reg
5251                            <status> */
5252                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5253                                         "0436 Adapter failed to init, "
5254                                         "timeout, status reg x%x, "
5255                                         "FW Data: A8 x%x AC x%x\n", status,
5256                                         readl(phba->MBslimaddr + 0xa8),
5257                                         readl(phba->MBslimaddr + 0xac));
5258                         phba->link_state = LPFC_HBA_ERROR;
5259                         return -ETIMEDOUT;
5260                 }
5261
5262                 /* Check to see if any errors occurred during init */
5263                 if (status & HS_FFERM) {
5264                         /* ERROR: During chipset initialization */
5265                         /* Adapter failed to init, chipset, status reg
5266                            <status> */
5267                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5268                                         "0437 Adapter failed to init, "
5269                                         "chipset, status reg x%x, "
5270                                         "FW Data: A8 x%x AC x%x\n", status,
5271                                         readl(phba->MBslimaddr + 0xa8),
5272                                         readl(phba->MBslimaddr + 0xac));
5273                         phba->link_state = LPFC_HBA_ERROR;
5274                         return -EIO;
5275                 }
5276
5277                 if (i <= 10)
5278                         msleep(10);
5279                 else if (i <= 100)
5280                         msleep(100);
5281                 else
5282                         msleep(1000);
5283
5284                 if (i == 150) {
5285                         /* Do post */
5286                         phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5287                         lpfc_sli_brdrestart(phba);
5288                 }
5289                 /* Read the HBA Host Status Register */
5290                 if (lpfc_readl(phba->HSregaddr, &status))
5291                         return -EIO;
5292         }
5293
5294         /* Check to see if any errors occurred during init */
5295         if (status & HS_FFERM) {
5296                 /* ERROR: During chipset initialization */
5297                 /* Adapter failed to init, chipset, status reg <status> */
5298                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5299                                 "0438 Adapter failed to init, chipset, "
5300                                 "status reg x%x, "
5301                                 "FW Data: A8 x%x AC x%x\n", status,
5302                                 readl(phba->MBslimaddr + 0xa8),
5303                                 readl(phba->MBslimaddr + 0xac));
5304                 phba->link_state = LPFC_HBA_ERROR;
5305                 return -EIO;
5306         }
5307
5308         phba->hba_flag |= HBA_NEEDS_CFG_PORT;
5309
5310         /* Clear all interrupt enable conditions */
5311         writel(0, phba->HCregaddr);
5312         readl(phba->HCregaddr); /* flush */
5313
5314         /* setup host attn register */
5315         writel(0xffffffff, phba->HAregaddr);
5316         readl(phba->HAregaddr); /* flush */
5317         return 0;
5318 }
5319
5320 /**
5321  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
5322  *
5323  * This function calculates and returns the number of HBQs required to be
5324  * configured.
5325  **/
5326 int
5327 lpfc_sli_hbq_count(void)
5328 {
5329         return ARRAY_SIZE(lpfc_hbq_defs);
5330 }
5331
5332 /**
5333  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
5334  *
5335  * This function adds the number of hbq entries in every HBQ to get
5336  * the total number of hbq entries required for the HBA and returns
5337  * the total count.
5338  **/
5339 static int
5340 lpfc_sli_hbq_entry_count(void)
5341 {
5342         int  hbq_count = lpfc_sli_hbq_count();
5343         int  count = 0;
5344         int  i;
5345
5346         for (i = 0; i < hbq_count; ++i)
5347                 count += lpfc_hbq_defs[i]->entry_count;
5348         return count;
5349 }
5350
5351 /**
5352  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
5353  *
5354  * This function calculates amount of memory required for all hbq entries
5355  * to be configured and returns the total memory required.
5356  **/
5357 int
5358 lpfc_sli_hbq_size(void)
5359 {
5360         return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
5361 }
5362
5363 /**
5364  * lpfc_sli_hbq_setup - configure and initialize HBQs
5365  * @phba: Pointer to HBA context object.
5366  *
5367  * This function is called during the SLI initialization to configure
5368  * all the HBQs and post buffers to the HBQ. The caller is not
5369  * required to hold any locks. This function will return zero if successful
5370  * else it will return negative error code.
5371  **/
5372 static int
5373 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
5374 {
5375         int  hbq_count = lpfc_sli_hbq_count();
5376         LPFC_MBOXQ_t *pmb;
5377         MAILBOX_t *pmbox;
5378         uint32_t hbqno;
5379         uint32_t hbq_entry_index;
5380
5381                                 /* Get a Mailbox buffer to setup mailbox
5382                                  * commands for HBA initialization
5383                                  */
5384         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5385
5386         if (!pmb)
5387                 return -ENOMEM;
5388
5389         pmbox = &pmb->u.mb;
5390
5391         /* Initialize the struct lpfc_sli_hbq structure for each hbq */
5392         phba->link_state = LPFC_INIT_MBX_CMDS;
5393         phba->hbq_in_use = 1;
5394
5395         hbq_entry_index = 0;
5396         for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
5397                 phba->hbqs[hbqno].next_hbqPutIdx = 0;
5398                 phba->hbqs[hbqno].hbqPutIdx      = 0;
5399                 phba->hbqs[hbqno].local_hbqGetIdx   = 0;
5400                 phba->hbqs[hbqno].entry_count =
5401                         lpfc_hbq_defs[hbqno]->entry_count;
5402                 lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
5403                         hbq_entry_index, pmb);
5404                 hbq_entry_index += phba->hbqs[hbqno].entry_count;
5405
5406                 if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
5407                         /* Adapter failed to init, mbxCmd <cmd> CFG_RING,
5408                            mbxStatus <status>, ring <num> */
5409
5410                         lpfc_printf_log(phba, KERN_ERR,
5411                                         LOG_SLI | LOG_VPORT,
5412                                         "1805 Adapter failed to init. "
5413                                         "Data: x%x x%x x%x\n",
5414                                         pmbox->mbxCommand,
5415                                         pmbox->mbxStatus, hbqno);
5416
5417                         phba->link_state = LPFC_HBA_ERROR;
5418                         mempool_free(pmb, phba->mbox_mem_pool);
5419                         return -ENXIO;
5420                 }
5421         }
5422         phba->hbq_count = hbq_count;
5423
5424         mempool_free(pmb, phba->mbox_mem_pool);
5425
5426         /* Initially populate or replenish the HBQs */
5427         for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5428                 lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5429         return 0;
5430 }
5431
5432 /**
5433  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5434  * @phba: Pointer to HBA context object.
5435  *
5436  * This function is called during the SLI initialization to configure
5437  * all the HBQs and post buffers to the HBQ. The caller is not
5438  * required to hold any locks. This function will return zero if successful
5439  * else it will return negative error code.
5440  **/
5441 static int
5442 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5443 {
5444         phba->hbq_in_use = 1;
5445         /**
5446          * Specific case when the MDS diagnostics is enabled and supported.
5447          * The receive buffer count is truncated to manage the incoming
5448          * traffic.
5449          **/
5450         if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5451                 phba->hbqs[LPFC_ELS_HBQ].entry_count =
5452                         lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5453         else
5454                 phba->hbqs[LPFC_ELS_HBQ].entry_count =
5455                         lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5456         phba->hbq_count = 1;
5457         lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5458         /* Initially populate or replenish the HBQs */
5459         return 0;
5460 }
5461
5462 /**
5463  * lpfc_sli_config_port - Issue config port mailbox command
5464  * @phba: Pointer to HBA context object.
5465  * @sli_mode: sli mode - 2/3
5466  *
5467  * This function is called by the sli initialization code path
5468  * to issue config_port mailbox command. This function restarts the
5469  * HBA firmware and issues a config_port mailbox command to configure
5470  * the SLI interface in the sli mode specified by sli_mode
5471  * variable. The caller is not required to hold any locks.
5472  * The function returns 0 if successful, else returns negative error
5473  * code.
5474  **/
5475 int
5476 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5477 {
5478         LPFC_MBOXQ_t *pmb;
5479         uint32_t resetcount = 0, rc = 0, done = 0;
5480
5481         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5482         if (!pmb) {
5483                 phba->link_state = LPFC_HBA_ERROR;
5484                 return -ENOMEM;
5485         }
5486
5487         phba->sli_rev = sli_mode;
5488         while (resetcount < 2 && !done) {
5489                 spin_lock_irq(&phba->hbalock);
5490                 phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5491                 spin_unlock_irq(&phba->hbalock);
5492                 phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5493                 lpfc_sli_brdrestart(phba);
5494                 rc = lpfc_sli_chipset_init(phba);
5495                 if (rc)
5496                         break;
5497
5498                 spin_lock_irq(&phba->hbalock);
5499                 phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5500                 spin_unlock_irq(&phba->hbalock);
5501                 resetcount++;
5502
5503                 /* Call pre CONFIG_PORT mailbox command initialization.  A
5504                  * value of 0 means the call was successful.  Any other
5505                  * nonzero value is a failure, but if ERESTART is returned,
5506                  * the driver may reset the HBA and try again.
5507                  */
5508                 rc = lpfc_config_port_prep(phba);
5509                 if (rc == -ERESTART) {
5510                         phba->link_state = LPFC_LINK_UNKNOWN;
5511                         continue;
5512                 } else if (rc)
5513                         break;
5514
5515                 phba->link_state = LPFC_INIT_MBX_CMDS;
5516                 lpfc_config_port(phba, pmb);
5517                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5518                 phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5519                                         LPFC_SLI3_HBQ_ENABLED |
5520                                         LPFC_SLI3_CRP_ENABLED |
5521                                         LPFC_SLI3_DSS_ENABLED);
5522                 if (rc != MBX_SUCCESS) {
5523                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5524                                 "0442 Adapter failed to init, mbxCmd x%x "
5525                                 "CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5526                                 pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5527                         spin_lock_irq(&phba->hbalock);
5528                         phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5529                         spin_unlock_irq(&phba->hbalock);
5530                         rc = -ENXIO;
5531                 } else {
5532                         /* Allow asynchronous mailbox command to go through */
5533                         spin_lock_irq(&phba->hbalock);
5534                         phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5535                         spin_unlock_irq(&phba->hbalock);
5536                         done = 1;
5537
5538                         if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5539                             (pmb->u.mb.un.varCfgPort.gasabt == 0))
5540                                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5541                                         "3110 Port did not grant ASABT\n");
5542                 }
5543         }
5544         if (!done) {
5545                 rc = -EINVAL;
5546                 goto do_prep_failed;
5547         }
5548         if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5549                 if (!pmb->u.mb.un.varCfgPort.cMA) {
5550                         rc = -ENXIO;
5551                         goto do_prep_failed;
5552                 }
5553                 if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5554                         phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5555                         phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5556                         phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5557                                 phba->max_vpi : phba->max_vports;
5558
5559                 } else
5560                         phba->max_vpi = 0;
5561                 if (pmb->u.mb.un.varCfgPort.gerbm)
5562                         phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5563                 if (pmb->u.mb.un.varCfgPort.gcrp)
5564                         phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5565
5566                 phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5567                 phba->port_gp = phba->mbox->us.s3_pgp.port;
5568
5569                 if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5570                         if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5571                                 phba->cfg_enable_bg = 0;
5572                                 phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5573                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5574                                                 "0443 Adapter did not grant "
5575                                                 "BlockGuard\n");
5576                         }
5577                 }
5578         } else {
5579                 phba->hbq_get = NULL;
5580                 phba->port_gp = phba->mbox->us.s2.port;
5581                 phba->max_vpi = 0;
5582         }
5583 do_prep_failed:
5584         mempool_free(pmb, phba->mbox_mem_pool);
5585         return rc;
5586 }
5587
5588
5589 /**
5590  * lpfc_sli_hba_setup - SLI initialization function
5591  * @phba: Pointer to HBA context object.
5592  *
5593  * This function is the main SLI initialization function. This function
5594  * is called by the HBA initialization code, HBA reset code and HBA
5595  * error attention handler code. Caller is not required to hold any
5596  * locks. This function issues config_port mailbox command to configure
5597  * the SLI, setup iocb rings and HBQ rings. In the end the function
5598  * calls the config_port_post function to issue init_link mailbox
5599  * command and to start the discovery. The function will return zero
5600  * if successful, else it will return negative error code.
5601  **/
5602 int
5603 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5604 {
5605         uint32_t rc;
5606         int  i;
5607         int longs;
5608
5609         /* Enable ISR already does config_port because of config_msi mbx */
5610         if (phba->hba_flag & HBA_NEEDS_CFG_PORT) {
5611                 rc = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
5612                 if (rc)
5613                         return -EIO;
5614                 phba->hba_flag &= ~HBA_NEEDS_CFG_PORT;
5615         }
5616         phba->fcp_embed_io = 0; /* SLI4 FC support only */
5617
5618         /* Enable PCIe device Advanced Error Reporting (AER) if configured */
5619         if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
5620                 rc = pci_enable_pcie_error_reporting(phba->pcidev);
5621                 if (!rc) {
5622                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5623                                         "2709 This device supports "
5624                                         "Advanced Error Reporting (AER)\n");
5625                         spin_lock_irq(&phba->hbalock);
5626                         phba->hba_flag |= HBA_AER_ENABLED;
5627                         spin_unlock_irq(&phba->hbalock);
5628                 } else {
5629                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5630                                         "2708 This device does not support "
5631                                         "Advanced Error Reporting (AER): %d\n",
5632                                         rc);
5633                         phba->cfg_aer_support = 0;
5634                 }
5635         }
5636
5637         if (phba->sli_rev == 3) {
5638                 phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5639                 phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5640         } else {
5641                 phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5642                 phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5643                 phba->sli3_options = 0;
5644         }
5645
5646         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5647                         "0444 Firmware in SLI %x mode. Max_vpi %d\n",
5648                         phba->sli_rev, phba->max_vpi);
5649         rc = lpfc_sli_ring_map(phba);
5650
5651         if (rc)
5652                 goto lpfc_sli_hba_setup_error;
5653
5654         /* Initialize VPIs. */
5655         if (phba->sli_rev == LPFC_SLI_REV3) {
5656                 /*
5657                  * The VPI bitmask and physical ID array are allocated
5658                  * and initialized once only - at driver load.  A port
5659                  * reset doesn't need to reinitialize this memory.
5660                  */
5661                 if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5662                         longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5663                         phba->vpi_bmask = kcalloc(longs,
5664                                                   sizeof(unsigned long),
5665                                                   GFP_KERNEL);
5666                         if (!phba->vpi_bmask) {
5667                                 rc = -ENOMEM;
5668                                 goto lpfc_sli_hba_setup_error;
5669                         }
5670
5671                         phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5672                                                 sizeof(uint16_t),
5673                                                 GFP_KERNEL);
5674                         if (!phba->vpi_ids) {
5675                                 kfree(phba->vpi_bmask);
5676                                 rc = -ENOMEM;
5677                                 goto lpfc_sli_hba_setup_error;
5678                         }
5679                         for (i = 0; i < phba->max_vpi; i++)
5680                                 phba->vpi_ids[i] = i;
5681                 }
5682         }
5683
5684         /* Init HBQs */
5685         if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5686                 rc = lpfc_sli_hbq_setup(phba);
5687                 if (rc)
5688                         goto lpfc_sli_hba_setup_error;
5689         }
5690         spin_lock_irq(&phba->hbalock);
5691         phba->sli.sli_flag |= LPFC_PROCESS_LA;
5692         spin_unlock_irq(&phba->hbalock);
5693
5694         rc = lpfc_config_port_post(phba);
5695         if (rc)
5696                 goto lpfc_sli_hba_setup_error;
5697
5698         return rc;
5699
5700 lpfc_sli_hba_setup_error:
5701         phba->link_state = LPFC_HBA_ERROR;
5702         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5703                         "0445 Firmware initialization failed\n");
5704         return rc;
5705 }
5706
5707 /**
5708  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5709  * @phba: Pointer to HBA context object.
5710  *
5711  * This function issue a dump mailbox command to read config region
5712  * 23 and parse the records in the region and populate driver
5713  * data structure.
5714  **/
5715 static int
5716 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5717 {
5718         LPFC_MBOXQ_t *mboxq;
5719         struct lpfc_dmabuf *mp;
5720         struct lpfc_mqe *mqe;
5721         uint32_t data_length;
5722         int rc;
5723
5724         /* Program the default value of vlan_id and fc_map */
5725         phba->valid_vlan = 0;
5726         phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5727         phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5728         phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5729
5730         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5731         if (!mboxq)
5732                 return -ENOMEM;
5733
5734         mqe = &mboxq->u.mqe;
5735         if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5736                 rc = -ENOMEM;
5737                 goto out_free_mboxq;
5738         }
5739
5740         mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
5741         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5742
5743         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5744                         "(%d):2571 Mailbox cmd x%x Status x%x "
5745                         "Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5746                         "x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5747                         "CQ: x%x x%x x%x x%x\n",
5748                         mboxq->vport ? mboxq->vport->vpi : 0,
5749                         bf_get(lpfc_mqe_command, mqe),
5750                         bf_get(lpfc_mqe_status, mqe),
5751                         mqe->un.mb_words[0], mqe->un.mb_words[1],
5752                         mqe->un.mb_words[2], mqe->un.mb_words[3],
5753                         mqe->un.mb_words[4], mqe->un.mb_words[5],
5754                         mqe->un.mb_words[6], mqe->un.mb_words[7],
5755                         mqe->un.mb_words[8], mqe->un.mb_words[9],
5756                         mqe->un.mb_words[10], mqe->un.mb_words[11],
5757                         mqe->un.mb_words[12], mqe->un.mb_words[13],
5758                         mqe->un.mb_words[14], mqe->un.mb_words[15],
5759                         mqe->un.mb_words[16], mqe->un.mb_words[50],
5760                         mboxq->mcqe.word0,
5761                         mboxq->mcqe.mcqe_tag0,  mboxq->mcqe.mcqe_tag1,
5762                         mboxq->mcqe.trailer);
5763
5764         if (rc) {
5765                 lpfc_mbuf_free(phba, mp->virt, mp->phys);
5766                 kfree(mp);
5767                 rc = -EIO;
5768                 goto out_free_mboxq;
5769         }
5770         data_length = mqe->un.mb_words[5];
5771         if (data_length > DMP_RGN23_SIZE) {
5772                 lpfc_mbuf_free(phba, mp->virt, mp->phys);
5773                 kfree(mp);
5774                 rc = -EIO;
5775                 goto out_free_mboxq;
5776         }
5777
5778         lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5779         lpfc_mbuf_free(phba, mp->virt, mp->phys);
5780         kfree(mp);
5781         rc = 0;
5782
5783 out_free_mboxq:
5784         mempool_free(mboxq, phba->mbox_mem_pool);
5785         return rc;
5786 }
5787
5788 /**
5789  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5790  * @phba: pointer to lpfc hba data structure.
5791  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5792  * @vpd: pointer to the memory to hold resulting port vpd data.
5793  * @vpd_size: On input, the number of bytes allocated to @vpd.
5794  *            On output, the number of data bytes in @vpd.
5795  *
5796  * This routine executes a READ_REV SLI4 mailbox command.  In
5797  * addition, this routine gets the port vpd data.
5798  *
5799  * Return codes
5800  *      0 - successful
5801  *      -ENOMEM - could not allocated memory.
5802  **/
5803 static int
5804 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5805                     uint8_t *vpd, uint32_t *vpd_size)
5806 {
5807         int rc = 0;
5808         uint32_t dma_size;
5809         struct lpfc_dmabuf *dmabuf;
5810         struct lpfc_mqe *mqe;
5811
5812         dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5813         if (!dmabuf)
5814                 return -ENOMEM;
5815
5816         /*
5817          * Get a DMA buffer for the vpd data resulting from the READ_REV
5818          * mailbox command.
5819          */
5820         dma_size = *vpd_size;
5821         dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5822                                           &dmabuf->phys, GFP_KERNEL);
5823         if (!dmabuf->virt) {
5824                 kfree(dmabuf);
5825                 return -ENOMEM;
5826         }
5827
5828         /*
5829          * The SLI4 implementation of READ_REV conflicts at word1,
5830          * bits 31:16 and SLI4 adds vpd functionality not present
5831          * in SLI3.  This code corrects the conflicts.
5832          */
5833         lpfc_read_rev(phba, mboxq);
5834         mqe = &mboxq->u.mqe;
5835         mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5836         mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5837         mqe->un.read_rev.word1 &= 0x0000FFFF;
5838         bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5839         bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5840
5841         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5842         if (rc) {
5843                 dma_free_coherent(&phba->pcidev->dev, dma_size,
5844                                   dmabuf->virt, dmabuf->phys);
5845                 kfree(dmabuf);
5846                 return -EIO;
5847         }
5848
5849         /*
5850          * The available vpd length cannot be bigger than the
5851          * DMA buffer passed to the port.  Catch the less than
5852          * case and update the caller's size.
5853          */
5854         if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5855                 *vpd_size = mqe->un.read_rev.avail_vpd_len;
5856
5857         memcpy(vpd, dmabuf->virt, *vpd_size);
5858
5859         dma_free_coherent(&phba->pcidev->dev, dma_size,
5860                           dmabuf->virt, dmabuf->phys);
5861         kfree(dmabuf);
5862         return 0;
5863 }
5864
5865 /**
5866  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5867  * @phba: pointer to lpfc hba data structure.
5868  *
5869  * This routine retrieves SLI4 device physical port name this PCI function
5870  * is attached to.
5871  *
5872  * Return codes
5873  *      0 - successful
5874  *      otherwise - failed to retrieve controller attributes
5875  **/
5876 static int
5877 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5878 {
5879         LPFC_MBOXQ_t *mboxq;
5880         struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5881         struct lpfc_controller_attribute *cntl_attr;
5882         void *virtaddr = NULL;
5883         uint32_t alloclen, reqlen;
5884         uint32_t shdr_status, shdr_add_status;
5885         union lpfc_sli4_cfg_shdr *shdr;
5886         int rc;
5887
5888         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5889         if (!mboxq)
5890                 return -ENOMEM;
5891
5892         /* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5893         reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5894         alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5895                         LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5896                         LPFC_SLI4_MBX_NEMBED);
5897
5898         if (alloclen < reqlen) {
5899                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5900                                 "3084 Allocated DMA memory size (%d) is "
5901                                 "less than the requested DMA memory size "
5902                                 "(%d)\n", alloclen, reqlen);
5903                 rc = -ENOMEM;
5904                 goto out_free_mboxq;
5905         }
5906         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5907         virtaddr = mboxq->sge_array->addr[0];
5908         mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5909         shdr = &mbx_cntl_attr->cfg_shdr;
5910         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5911         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5912         if (shdr_status || shdr_add_status || rc) {
5913                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5914                                 "3085 Mailbox x%x (x%x/x%x) failed, "
5915                                 "rc:x%x, status:x%x, add_status:x%x\n",
5916                                 bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5917                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5918                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5919                                 rc, shdr_status, shdr_add_status);
5920                 rc = -ENXIO;
5921                 goto out_free_mboxq;
5922         }
5923
5924         cntl_attr = &mbx_cntl_attr->cntl_attr;
5925         phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
5926         phba->sli4_hba.lnk_info.lnk_tp =
5927                 bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
5928         phba->sli4_hba.lnk_info.lnk_no =
5929                 bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
5930         phba->sli4_hba.flash_id = bf_get(lpfc_cntl_attr_flash_id, cntl_attr);
5931         phba->sli4_hba.asic_rev = bf_get(lpfc_cntl_attr_asic_rev, cntl_attr);
5932
5933         memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
5934         strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
5935                 sizeof(phba->BIOSVersion));
5936
5937         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5938                         "3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s, "
5939                         "flash_id: x%02x, asic_rev: x%02x\n",
5940                         phba->sli4_hba.lnk_info.lnk_tp,
5941                         phba->sli4_hba.lnk_info.lnk_no,
5942                         phba->BIOSVersion, phba->sli4_hba.flash_id,
5943                         phba->sli4_hba.asic_rev);
5944 out_free_mboxq:
5945         if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
5946                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
5947         else
5948                 mempool_free(mboxq, phba->mbox_mem_pool);
5949         return rc;
5950 }
5951
5952 /**
5953  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
5954  * @phba: pointer to lpfc hba data structure.
5955  *
5956  * This routine retrieves SLI4 device physical port name this PCI function
5957  * is attached to.
5958  *
5959  * Return codes
5960  *      0 - successful
5961  *      otherwise - failed to retrieve physical port name
5962  **/
5963 static int
5964 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
5965 {
5966         LPFC_MBOXQ_t *mboxq;
5967         struct lpfc_mbx_get_port_name *get_port_name;
5968         uint32_t shdr_status, shdr_add_status;
5969         union lpfc_sli4_cfg_shdr *shdr;
5970         char cport_name = 0;
5971         int rc;
5972
5973         /* We assume nothing at this point */
5974         phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5975         phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
5976
5977         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5978         if (!mboxq)
5979                 return -ENOMEM;
5980         /* obtain link type and link number via READ_CONFIG */
5981         phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
5982         lpfc_sli4_read_config(phba);
5983         if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
5984                 goto retrieve_ppname;
5985
5986         /* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
5987         rc = lpfc_sli4_get_ctl_attr(phba);
5988         if (rc)
5989                 goto out_free_mboxq;
5990
5991 retrieve_ppname:
5992         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5993                 LPFC_MBOX_OPCODE_GET_PORT_NAME,
5994                 sizeof(struct lpfc_mbx_get_port_name) -
5995                 sizeof(struct lpfc_sli4_cfg_mhdr),
5996                 LPFC_SLI4_MBX_EMBED);
5997         get_port_name = &mboxq->u.mqe.un.get_port_name;
5998         shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
5999         bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
6000         bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
6001                 phba->sli4_hba.lnk_info.lnk_tp);
6002         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6003         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6004         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6005         if (shdr_status || shdr_add_status || rc) {
6006                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6007                                 "3087 Mailbox x%x (x%x/x%x) failed: "
6008                                 "rc:x%x, status:x%x, add_status:x%x\n",
6009                                 bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6010                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6011                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6012                                 rc, shdr_status, shdr_add_status);
6013                 rc = -ENXIO;
6014                 goto out_free_mboxq;
6015         }
6016         switch (phba->sli4_hba.lnk_info.lnk_no) {
6017         case LPFC_LINK_NUMBER_0:
6018                 cport_name = bf_get(lpfc_mbx_get_port_name_name0,
6019                                 &get_port_name->u.response);
6020                 phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6021                 break;
6022         case LPFC_LINK_NUMBER_1:
6023                 cport_name = bf_get(lpfc_mbx_get_port_name_name1,
6024                                 &get_port_name->u.response);
6025                 phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6026                 break;
6027         case LPFC_LINK_NUMBER_2:
6028                 cport_name = bf_get(lpfc_mbx_get_port_name_name2,
6029                                 &get_port_name->u.response);
6030                 phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6031                 break;
6032         case LPFC_LINK_NUMBER_3:
6033                 cport_name = bf_get(lpfc_mbx_get_port_name_name3,
6034                                 &get_port_name->u.response);
6035                 phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6036                 break;
6037         default:
6038                 break;
6039         }
6040
6041         if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
6042                 phba->Port[0] = cport_name;
6043                 phba->Port[1] = '\0';
6044                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6045                                 "3091 SLI get port name: %s\n", phba->Port);
6046         }
6047
6048 out_free_mboxq:
6049         if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6050                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
6051         else
6052                 mempool_free(mboxq, phba->mbox_mem_pool);
6053         return rc;
6054 }
6055
6056 /**
6057  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
6058  * @phba: pointer to lpfc hba data structure.
6059  *
6060  * This routine is called to explicitly arm the SLI4 device's completion and
6061  * event queues
6062  **/
6063 static void
6064 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
6065 {
6066         int qidx;
6067         struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
6068         struct lpfc_sli4_hdw_queue *qp;
6069         struct lpfc_queue *eq;
6070
6071         sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
6072         sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
6073         if (sli4_hba->nvmels_cq)
6074                 sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
6075                                            LPFC_QUEUE_REARM);
6076
6077         if (sli4_hba->hdwq) {
6078                 /* Loop thru all Hardware Queues */
6079                 for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
6080                         qp = &sli4_hba->hdwq[qidx];
6081                         /* ARM the corresponding CQ */
6082                         sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
6083                                                 LPFC_QUEUE_REARM);
6084                 }
6085
6086                 /* Loop thru all IRQ vectors */
6087                 for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
6088                         eq = sli4_hba->hba_eq_hdl[qidx].eq;
6089                         /* ARM the corresponding EQ */
6090                         sli4_hba->sli4_write_eq_db(phba, eq,
6091                                                    0, LPFC_QUEUE_REARM);
6092                 }
6093         }
6094
6095         if (phba->nvmet_support) {
6096                 for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
6097                         sli4_hba->sli4_write_cq_db(phba,
6098                                 sli4_hba->nvmet_cqset[qidx], 0,
6099                                 LPFC_QUEUE_REARM);
6100                 }
6101         }
6102 }
6103
6104 /**
6105  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
6106  * @phba: Pointer to HBA context object.
6107  * @type: The resource extent type.
6108  * @extnt_count: buffer to hold port available extent count.
6109  * @extnt_size: buffer to hold element count per extent.
6110  *
6111  * This function calls the port and retrievs the number of available
6112  * extents and their size for a particular extent type.
6113  *
6114  * Returns: 0 if successful.  Nonzero otherwise.
6115  **/
6116 int
6117 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
6118                                uint16_t *extnt_count, uint16_t *extnt_size)
6119 {
6120         int rc = 0;
6121         uint32_t length;
6122         uint32_t mbox_tmo;
6123         struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
6124         LPFC_MBOXQ_t *mbox;
6125
6126         mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6127         if (!mbox)
6128                 return -ENOMEM;
6129
6130         /* Find out how many extents are available for this resource type */
6131         length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
6132                   sizeof(struct lpfc_sli4_cfg_mhdr));
6133         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6134                          LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
6135                          length, LPFC_SLI4_MBX_EMBED);
6136
6137         /* Send an extents count of 0 - the GET doesn't use it. */
6138         rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6139                                         LPFC_SLI4_MBX_EMBED);
6140         if (unlikely(rc)) {
6141                 rc = -EIO;
6142                 goto err_exit;
6143         }
6144
6145         if (!phba->sli4_hba.intr_enable)
6146                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6147         else {
6148                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6149                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6150         }
6151         if (unlikely(rc)) {
6152                 rc = -EIO;
6153                 goto err_exit;
6154         }
6155
6156         rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
6157         if (bf_get(lpfc_mbox_hdr_status,
6158                    &rsrc_info->header.cfg_shdr.response)) {
6159                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6160                                 "2930 Failed to get resource extents "
6161                                 "Status 0x%x Add'l Status 0x%x\n",
6162                                 bf_get(lpfc_mbox_hdr_status,
6163                                        &rsrc_info->header.cfg_shdr.response),
6164                                 bf_get(lpfc_mbox_hdr_add_status,
6165                                        &rsrc_info->header.cfg_shdr.response));
6166                 rc = -EIO;
6167                 goto err_exit;
6168         }
6169
6170         *extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
6171                               &rsrc_info->u.rsp);
6172         *extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
6173                              &rsrc_info->u.rsp);
6174
6175         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6176                         "3162 Retrieved extents type-%d from port: count:%d, "
6177                         "size:%d\n", type, *extnt_count, *extnt_size);
6178
6179 err_exit:
6180         mempool_free(mbox, phba->mbox_mem_pool);
6181         return rc;
6182 }
6183
6184 /**
6185  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
6186  * @phba: Pointer to HBA context object.
6187  * @type: The extent type to check.
6188  *
6189  * This function reads the current available extents from the port and checks
6190  * if the extent count or extent size has changed since the last access.
6191  * Callers use this routine post port reset to understand if there is a
6192  * extent reprovisioning requirement.
6193  *
6194  * Returns:
6195  *   -Error: error indicates problem.
6196  *   1: Extent count or size has changed.
6197  *   0: No changes.
6198  **/
6199 static int
6200 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
6201 {
6202         uint16_t curr_ext_cnt, rsrc_ext_cnt;
6203         uint16_t size_diff, rsrc_ext_size;
6204         int rc = 0;
6205         struct lpfc_rsrc_blks *rsrc_entry;
6206         struct list_head *rsrc_blk_list = NULL;
6207
6208         size_diff = 0;
6209         curr_ext_cnt = 0;
6210         rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6211                                             &rsrc_ext_cnt,
6212                                             &rsrc_ext_size);
6213         if (unlikely(rc))
6214                 return -EIO;
6215
6216         switch (type) {
6217         case LPFC_RSC_TYPE_FCOE_RPI:
6218                 rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6219                 break;
6220         case LPFC_RSC_TYPE_FCOE_VPI:
6221                 rsrc_blk_list = &phba->lpfc_vpi_blk_list;
6222                 break;
6223         case LPFC_RSC_TYPE_FCOE_XRI:
6224                 rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6225                 break;
6226         case LPFC_RSC_TYPE_FCOE_VFI:
6227                 rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6228                 break;
6229         default:
6230                 break;
6231         }
6232
6233         list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
6234                 curr_ext_cnt++;
6235                 if (rsrc_entry->rsrc_size != rsrc_ext_size)
6236                         size_diff++;
6237         }
6238
6239         if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
6240                 rc = 1;
6241
6242         return rc;
6243 }
6244
6245 /**
6246  * lpfc_sli4_cfg_post_extnts -
6247  * @phba: Pointer to HBA context object.
6248  * @extnt_cnt: number of available extents.
6249  * @type: the extent type (rpi, xri, vfi, vpi).
6250  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
6251  * @mbox: pointer to the caller's allocated mailbox structure.
6252  *
6253  * This function executes the extents allocation request.  It also
6254  * takes care of the amount of memory needed to allocate or get the
6255  * allocated extents. It is the caller's responsibility to evaluate
6256  * the response.
6257  *
6258  * Returns:
6259  *   -Error:  Error value describes the condition found.
6260  *   0: if successful
6261  **/
6262 static int
6263 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
6264                           uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
6265 {
6266         int rc = 0;
6267         uint32_t req_len;
6268         uint32_t emb_len;
6269         uint32_t alloc_len, mbox_tmo;
6270
6271         /* Calculate the total requested length of the dma memory */
6272         req_len = extnt_cnt * sizeof(uint16_t);
6273
6274         /*
6275          * Calculate the size of an embedded mailbox.  The uint32_t
6276          * accounts for extents-specific word.
6277          */
6278         emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6279                 sizeof(uint32_t);
6280
6281         /*
6282          * Presume the allocation and response will fit into an embedded
6283          * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6284          */
6285         *emb = LPFC_SLI4_MBX_EMBED;
6286         if (req_len > emb_len) {
6287                 req_len = extnt_cnt * sizeof(uint16_t) +
6288                         sizeof(union lpfc_sli4_cfg_shdr) +
6289                         sizeof(uint32_t);
6290                 *emb = LPFC_SLI4_MBX_NEMBED;
6291         }
6292
6293         alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6294                                      LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
6295                                      req_len, *emb);
6296         if (alloc_len < req_len) {
6297                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6298                         "2982 Allocated DMA memory size (x%x) is "
6299                         "less than the requested DMA memory "
6300                         "size (x%x)\n", alloc_len, req_len);
6301                 return -ENOMEM;
6302         }
6303         rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
6304         if (unlikely(rc))
6305                 return -EIO;
6306
6307         if (!phba->sli4_hba.intr_enable)
6308                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6309         else {
6310                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6311                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6312         }
6313
6314         if (unlikely(rc))
6315                 rc = -EIO;
6316         return rc;
6317 }
6318
6319 /**
6320  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
6321  * @phba: Pointer to HBA context object.
6322  * @type:  The resource extent type to allocate.
6323  *
6324  * This function allocates the number of elements for the specified
6325  * resource type.
6326  **/
6327 static int
6328 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
6329 {
6330         bool emb = false;
6331         uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
6332         uint16_t rsrc_id, rsrc_start, j, k;
6333         uint16_t *ids;
6334         int i, rc;
6335         unsigned long longs;
6336         unsigned long *bmask;
6337         struct lpfc_rsrc_blks *rsrc_blks;
6338         LPFC_MBOXQ_t *mbox;
6339         uint32_t length;
6340         struct lpfc_id_range *id_array = NULL;
6341         void *virtaddr = NULL;
6342         struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6343         struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6344         struct list_head *ext_blk_list;
6345
6346         rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6347                                             &rsrc_cnt,
6348                                             &rsrc_size);
6349         if (unlikely(rc))
6350                 return -EIO;
6351
6352         if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
6353                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6354                         "3009 No available Resource Extents "
6355                         "for resource type 0x%x: Count: 0x%x, "
6356                         "Size 0x%x\n", type, rsrc_cnt,
6357                         rsrc_size);
6358                 return -ENOMEM;
6359         }
6360
6361         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
6362                         "2903 Post resource extents type-0x%x: "
6363                         "count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
6364
6365         mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6366         if (!mbox)
6367                 return -ENOMEM;
6368
6369         rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
6370         if (unlikely(rc)) {
6371                 rc = -EIO;
6372                 goto err_exit;
6373         }
6374
6375         /*
6376          * Figure out where the response is located.  Then get local pointers
6377          * to the response data.  The port does not guarantee to respond to
6378          * all extents counts request so update the local variable with the
6379          * allocated count from the port.
6380          */
6381         if (emb == LPFC_SLI4_MBX_EMBED) {
6382                 rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6383                 id_array = &rsrc_ext->u.rsp.id[0];
6384                 rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6385         } else {
6386                 virtaddr = mbox->sge_array->addr[0];
6387                 n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6388                 rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6389                 id_array = &n_rsrc->id;
6390         }
6391
6392         longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6393         rsrc_id_cnt = rsrc_cnt * rsrc_size;
6394
6395         /*
6396          * Based on the resource size and count, correct the base and max
6397          * resource values.
6398          */
6399         length = sizeof(struct lpfc_rsrc_blks);
6400         switch (type) {
6401         case LPFC_RSC_TYPE_FCOE_RPI:
6402                 phba->sli4_hba.rpi_bmask = kcalloc(longs,
6403                                                    sizeof(unsigned long),
6404                                                    GFP_KERNEL);
6405                 if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6406                         rc = -ENOMEM;
6407                         goto err_exit;
6408                 }
6409                 phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6410                                                  sizeof(uint16_t),
6411                                                  GFP_KERNEL);
6412                 if (unlikely(!phba->sli4_hba.rpi_ids)) {
6413                         kfree(phba->sli4_hba.rpi_bmask);
6414                         rc = -ENOMEM;
6415                         goto err_exit;
6416                 }
6417
6418                 /*
6419                  * The next_rpi was initialized with the maximum available
6420                  * count but the port may allocate a smaller number.  Catch
6421                  * that case and update the next_rpi.
6422                  */
6423                 phba->sli4_hba.next_rpi = rsrc_id_cnt;
6424
6425                 /* Initialize local ptrs for common extent processing later. */
6426                 bmask = phba->sli4_hba.rpi_bmask;
6427                 ids = phba->sli4_hba.rpi_ids;
6428                 ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6429                 break;
6430         case LPFC_RSC_TYPE_FCOE_VPI:
6431                 phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6432                                           GFP_KERNEL);
6433                 if (unlikely(!phba->vpi_bmask)) {
6434                         rc = -ENOMEM;
6435                         goto err_exit;
6436                 }
6437                 phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6438                                          GFP_KERNEL);
6439                 if (unlikely(!phba->vpi_ids)) {
6440                         kfree(phba->vpi_bmask);
6441                         rc = -ENOMEM;
6442                         goto err_exit;
6443                 }
6444
6445                 /* Initialize local ptrs for common extent processing later. */
6446                 bmask = phba->vpi_bmask;
6447                 ids = phba->vpi_ids;
6448                 ext_blk_list = &phba->lpfc_vpi_blk_list;
6449                 break;
6450         case LPFC_RSC_TYPE_FCOE_XRI:
6451                 phba->sli4_hba.xri_bmask = kcalloc(longs,
6452                                                    sizeof(unsigned long),
6453                                                    GFP_KERNEL);
6454                 if (unlikely(!phba->sli4_hba.xri_bmask)) {
6455                         rc = -ENOMEM;
6456                         goto err_exit;
6457                 }
6458                 phba->sli4_hba.max_cfg_param.xri_used = 0;
6459                 phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6460                                                  sizeof(uint16_t),
6461                                                  GFP_KERNEL);
6462                 if (unlikely(!phba->sli4_hba.xri_ids)) {
6463                         kfree(phba->sli4_hba.xri_bmask);
6464                         rc = -ENOMEM;
6465                         goto err_exit;
6466                 }
6467
6468                 /* Initialize local ptrs for common extent processing later. */
6469                 bmask = phba->sli4_hba.xri_bmask;
6470                 ids = phba->sli4_hba.xri_ids;
6471                 ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6472                 break;
6473         case LPFC_RSC_TYPE_FCOE_VFI:
6474                 phba->sli4_hba.vfi_bmask = kcalloc(longs,
6475                                                    sizeof(unsigned long),
6476                                                    GFP_KERNEL);
6477                 if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6478                         rc = -ENOMEM;
6479                         goto err_exit;
6480                 }
6481                 phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6482                                                  sizeof(uint16_t),
6483                                                  GFP_KERNEL);
6484                 if (unlikely(!phba->sli4_hba.vfi_ids)) {
6485                         kfree(phba->sli4_hba.vfi_bmask);
6486                         rc = -ENOMEM;
6487                         goto err_exit;
6488                 }
6489
6490                 /* Initialize local ptrs for common extent processing later. */
6491                 bmask = phba->sli4_hba.vfi_bmask;
6492                 ids = phba->sli4_hba.vfi_ids;
6493                 ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6494                 break;
6495         default:
6496                 /* Unsupported Opcode.  Fail call. */
6497                 id_array = NULL;
6498                 bmask = NULL;
6499                 ids = NULL;
6500                 ext_blk_list = NULL;
6501                 goto err_exit;
6502         }
6503
6504         /*
6505          * Complete initializing the extent configuration with the
6506          * allocated ids assigned to this function.  The bitmask serves
6507          * as an index into the array and manages the available ids.  The
6508          * array just stores the ids communicated to the port via the wqes.
6509          */
6510         for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6511                 if ((i % 2) == 0)
6512                         rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6513                                          &id_array[k]);
6514                 else
6515                         rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6516                                          &id_array[k]);
6517
6518                 rsrc_blks = kzalloc(length, GFP_KERNEL);
6519                 if (unlikely(!rsrc_blks)) {
6520                         rc = -ENOMEM;
6521                         kfree(bmask);
6522                         kfree(ids);
6523                         goto err_exit;
6524                 }
6525                 rsrc_blks->rsrc_start = rsrc_id;
6526                 rsrc_blks->rsrc_size = rsrc_size;
6527                 list_add_tail(&rsrc_blks->list, ext_blk_list);
6528                 rsrc_start = rsrc_id;
6529                 if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6530                         phba->sli4_hba.io_xri_start = rsrc_start +
6531                                 lpfc_sli4_get_iocb_cnt(phba);
6532                 }
6533
6534                 while (rsrc_id < (rsrc_start + rsrc_size)) {
6535                         ids[j] = rsrc_id;
6536                         rsrc_id++;
6537                         j++;
6538                 }
6539                 /* Entire word processed.  Get next word.*/
6540                 if ((i % 2) == 1)
6541                         k++;
6542         }
6543  err_exit:
6544         lpfc_sli4_mbox_cmd_free(phba, mbox);
6545         return rc;
6546 }
6547
6548
6549
6550 /**
6551  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6552  * @phba: Pointer to HBA context object.
6553  * @type: the extent's type.
6554  *
6555  * This function deallocates all extents of a particular resource type.
6556  * SLI4 does not allow for deallocating a particular extent range.  It
6557  * is the caller's responsibility to release all kernel memory resources.
6558  **/
6559 static int
6560 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6561 {
6562         int rc;
6563         uint32_t length, mbox_tmo = 0;
6564         LPFC_MBOXQ_t *mbox;
6565         struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6566         struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6567
6568         mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6569         if (!mbox)
6570                 return -ENOMEM;
6571
6572         /*
6573          * This function sends an embedded mailbox because it only sends the
6574          * the resource type.  All extents of this type are released by the
6575          * port.
6576          */
6577         length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6578                   sizeof(struct lpfc_sli4_cfg_mhdr));
6579         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6580                          LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6581                          length, LPFC_SLI4_MBX_EMBED);
6582
6583         /* Send an extents count of 0 - the dealloc doesn't use it. */
6584         rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6585                                         LPFC_SLI4_MBX_EMBED);
6586         if (unlikely(rc)) {
6587                 rc = -EIO;
6588                 goto out_free_mbox;
6589         }
6590         if (!phba->sli4_hba.intr_enable)
6591                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6592         else {
6593                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6594                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6595         }
6596         if (unlikely(rc)) {
6597                 rc = -EIO;
6598                 goto out_free_mbox;
6599         }
6600
6601         dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6602         if (bf_get(lpfc_mbox_hdr_status,
6603                    &dealloc_rsrc->header.cfg_shdr.response)) {
6604                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6605                                 "2919 Failed to release resource extents "
6606                                 "for type %d - Status 0x%x Add'l Status 0x%x. "
6607                                 "Resource memory not released.\n",
6608                                 type,
6609                                 bf_get(lpfc_mbox_hdr_status,
6610                                     &dealloc_rsrc->header.cfg_shdr.response),
6611                                 bf_get(lpfc_mbox_hdr_add_status,
6612                                     &dealloc_rsrc->header.cfg_shdr.response));
6613                 rc = -EIO;
6614                 goto out_free_mbox;
6615         }
6616
6617         /* Release kernel memory resources for the specific type. */
6618         switch (type) {
6619         case LPFC_RSC_TYPE_FCOE_VPI:
6620                 kfree(phba->vpi_bmask);
6621                 kfree(phba->vpi_ids);
6622                 bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6623                 list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6624                                     &phba->lpfc_vpi_blk_list, list) {
6625                         list_del_init(&rsrc_blk->list);
6626                         kfree(rsrc_blk);
6627                 }
6628                 phba->sli4_hba.max_cfg_param.vpi_used = 0;
6629                 break;
6630         case LPFC_RSC_TYPE_FCOE_XRI:
6631                 kfree(phba->sli4_hba.xri_bmask);
6632                 kfree(phba->sli4_hba.xri_ids);
6633                 list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6634                                     &phba->sli4_hba.lpfc_xri_blk_list, list) {
6635                         list_del_init(&rsrc_blk->list);
6636                         kfree(rsrc_blk);
6637                 }
6638                 break;
6639         case LPFC_RSC_TYPE_FCOE_VFI:
6640                 kfree(phba->sli4_hba.vfi_bmask);
6641                 kfree(phba->sli4_hba.vfi_ids);
6642                 bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6643                 list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6644                                     &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6645                         list_del_init(&rsrc_blk->list);
6646                         kfree(rsrc_blk);
6647                 }
6648                 break;
6649         case LPFC_RSC_TYPE_FCOE_RPI:
6650                 /* RPI bitmask and physical id array are cleaned up earlier. */
6651                 list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6652                                     &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6653                         list_del_init(&rsrc_blk->list);
6654                         kfree(rsrc_blk);
6655                 }
6656                 break;
6657         default:
6658                 break;
6659         }
6660
6661         bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6662
6663  out_free_mbox:
6664         mempool_free(mbox, phba->mbox_mem_pool);
6665         return rc;
6666 }
6667
6668 static void
6669 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6670                   uint32_t feature)
6671 {
6672         uint32_t len;
6673         u32 sig_freq = 0;
6674
6675         len = sizeof(struct lpfc_mbx_set_feature) -
6676                 sizeof(struct lpfc_sli4_cfg_mhdr);
6677         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6678                          LPFC_MBOX_OPCODE_SET_FEATURES, len,
6679                          LPFC_SLI4_MBX_EMBED);
6680
6681         switch (feature) {
6682         case LPFC_SET_UE_RECOVERY:
6683                 bf_set(lpfc_mbx_set_feature_UER,
6684                        &mbox->u.mqe.un.set_feature, 1);
6685                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6686                 mbox->u.mqe.un.set_feature.param_len = 8;
6687                 break;
6688         case LPFC_SET_MDS_DIAGS:
6689                 bf_set(lpfc_mbx_set_feature_mds,
6690                        &mbox->u.mqe.un.set_feature, 1);
6691                 bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6692                        &mbox->u.mqe.un.set_feature, 1);
6693                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6694                 mbox->u.mqe.un.set_feature.param_len = 8;
6695                 break;
6696         case LPFC_SET_CGN_SIGNAL:
6697                 if (phba->cmf_active_mode == LPFC_CFG_OFF)
6698                         sig_freq = 0;
6699                 else
6700                         sig_freq = phba->cgn_sig_freq;
6701
6702                 if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6703                         bf_set(lpfc_mbx_set_feature_CGN_alarm_freq,
6704                                &mbox->u.mqe.un.set_feature, sig_freq);
6705                         bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6706                                &mbox->u.mqe.un.set_feature, sig_freq);
6707                 }
6708
6709                 if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY)
6710                         bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6711                                &mbox->u.mqe.un.set_feature, sig_freq);
6712
6713                 if (phba->cmf_active_mode == LPFC_CFG_OFF ||
6714                     phba->cgn_reg_signal == EDC_CG_SIG_NOTSUPPORTED)
6715                         sig_freq = 0;
6716                 else
6717                         sig_freq = lpfc_acqe_cgn_frequency;
6718
6719                 bf_set(lpfc_mbx_set_feature_CGN_acqe_freq,
6720                        &mbox->u.mqe.un.set_feature, sig_freq);
6721
6722                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_CGN_SIGNAL;
6723                 mbox->u.mqe.un.set_feature.param_len = 12;
6724                 break;
6725         case LPFC_SET_DUAL_DUMP:
6726                 bf_set(lpfc_mbx_set_feature_dd,
6727                        &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6728                 bf_set(lpfc_mbx_set_feature_ddquery,
6729                        &mbox->u.mqe.un.set_feature, 0);
6730                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6731                 mbox->u.mqe.un.set_feature.param_len = 4;
6732                 break;
6733         case LPFC_SET_ENABLE_MI:
6734                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_MI;
6735                 mbox->u.mqe.un.set_feature.param_len = 4;
6736                 bf_set(lpfc_mbx_set_feature_milunq, &mbox->u.mqe.un.set_feature,
6737                        phba->pport->cfg_lun_queue_depth);
6738                 bf_set(lpfc_mbx_set_feature_mi, &mbox->u.mqe.un.set_feature,
6739                        phba->sli4_hba.pc_sli4_params.mi_ver);
6740                 break;
6741         case LPFC_SET_ENABLE_CMF:
6742                 bf_set(lpfc_mbx_set_feature_dd, &mbox->u.mqe.un.set_feature, 1);
6743                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_CMF;
6744                 mbox->u.mqe.un.set_feature.param_len = 4;
6745                 bf_set(lpfc_mbx_set_feature_cmf,
6746                        &mbox->u.mqe.un.set_feature, 1);
6747                 break;
6748         }
6749         return;
6750 }
6751
6752 /**
6753  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6754  * @phba: Pointer to HBA context object.
6755  *
6756  * Disable FW logging into host memory on the adapter. To
6757  * be done before reading logs from the host memory.
6758  **/
6759 void
6760 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6761 {
6762         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6763
6764         spin_lock_irq(&phba->hbalock);
6765         ras_fwlog->state = INACTIVE;
6766         spin_unlock_irq(&phba->hbalock);
6767
6768         /* Disable FW logging to host memory */
6769         writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6770                phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6771
6772         /* Wait 10ms for firmware to stop using DMA buffer */
6773         usleep_range(10 * 1000, 20 * 1000);
6774 }
6775
6776 /**
6777  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6778  * @phba: Pointer to HBA context object.
6779  *
6780  * This function is called to free memory allocated for RAS FW logging
6781  * support in the driver.
6782  **/
6783 void
6784 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6785 {
6786         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6787         struct lpfc_dmabuf *dmabuf, *next;
6788
6789         if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6790                 list_for_each_entry_safe(dmabuf, next,
6791                                     &ras_fwlog->fwlog_buff_list,
6792                                     list) {
6793                         list_del(&dmabuf->list);
6794                         dma_free_coherent(&phba->pcidev->dev,
6795                                           LPFC_RAS_MAX_ENTRY_SIZE,
6796                                           dmabuf->virt, dmabuf->phys);
6797                         kfree(dmabuf);
6798                 }
6799         }
6800
6801         if (ras_fwlog->lwpd.virt) {
6802                 dma_free_coherent(&phba->pcidev->dev,
6803                                   sizeof(uint32_t) * 2,
6804                                   ras_fwlog->lwpd.virt,
6805                                   ras_fwlog->lwpd.phys);
6806                 ras_fwlog->lwpd.virt = NULL;
6807         }
6808
6809         spin_lock_irq(&phba->hbalock);
6810         ras_fwlog->state = INACTIVE;
6811         spin_unlock_irq(&phba->hbalock);
6812 }
6813
6814 /**
6815  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6816  * @phba: Pointer to HBA context object.
6817  * @fwlog_buff_count: Count of buffers to be created.
6818  *
6819  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6820  * to update FW log is posted to the adapter.
6821  * Buffer count is calculated based on module param ras_fwlog_buffsize
6822  * Size of each buffer posted to FW is 64K.
6823  **/
6824
6825 static int
6826 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6827                         uint32_t fwlog_buff_count)
6828 {
6829         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6830         struct lpfc_dmabuf *dmabuf;
6831         int rc = 0, i = 0;
6832
6833         /* Initialize List */
6834         INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6835
6836         /* Allocate memory for the LWPD */
6837         ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6838                                             sizeof(uint32_t) * 2,
6839                                             &ras_fwlog->lwpd.phys,
6840                                             GFP_KERNEL);
6841         if (!ras_fwlog->lwpd.virt) {
6842                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6843                                 "6185 LWPD Memory Alloc Failed\n");
6844
6845                 return -ENOMEM;
6846         }
6847
6848         ras_fwlog->fw_buffcount = fwlog_buff_count;
6849         for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6850                 dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6851                                  GFP_KERNEL);
6852                 if (!dmabuf) {
6853                         rc = -ENOMEM;
6854                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6855                                         "6186 Memory Alloc failed FW logging");
6856                         goto free_mem;
6857                 }
6858
6859                 dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6860                                                   LPFC_RAS_MAX_ENTRY_SIZE,
6861                                                   &dmabuf->phys, GFP_KERNEL);
6862                 if (!dmabuf->virt) {
6863                         kfree(dmabuf);
6864                         rc = -ENOMEM;
6865                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6866                                         "6187 DMA Alloc Failed FW logging");
6867                         goto free_mem;
6868                 }
6869                 dmabuf->buffer_tag = i;
6870                 list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6871         }
6872
6873 free_mem:
6874         if (rc)
6875                 lpfc_sli4_ras_dma_free(phba);
6876
6877         return rc;
6878 }
6879
6880 /**
6881  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6882  * @phba: pointer to lpfc hba data structure.
6883  * @pmb: pointer to the driver internal queue element for mailbox command.
6884  *
6885  * Completion handler for driver's RAS MBX command to the device.
6886  **/
6887 static void
6888 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6889 {
6890         MAILBOX_t *mb;
6891         union lpfc_sli4_cfg_shdr *shdr;
6892         uint32_t shdr_status, shdr_add_status;
6893         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6894
6895         mb = &pmb->u.mb;
6896
6897         shdr = (union lpfc_sli4_cfg_shdr *)
6898                 &pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6899         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6900         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6901
6902         if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6903                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6904                                 "6188 FW LOG mailbox "
6905                                 "completed with status x%x add_status x%x,"
6906                                 " mbx status x%x\n",
6907                                 shdr_status, shdr_add_status, mb->mbxStatus);
6908
6909                 ras_fwlog->ras_hwsupport = false;
6910                 goto disable_ras;
6911         }
6912
6913         spin_lock_irq(&phba->hbalock);
6914         ras_fwlog->state = ACTIVE;
6915         spin_unlock_irq(&phba->hbalock);
6916         mempool_free(pmb, phba->mbox_mem_pool);
6917
6918         return;
6919
6920 disable_ras:
6921         /* Free RAS DMA memory */
6922         lpfc_sli4_ras_dma_free(phba);
6923         mempool_free(pmb, phba->mbox_mem_pool);
6924 }
6925
6926 /**
6927  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
6928  * @phba: pointer to lpfc hba data structure.
6929  * @fwlog_level: Logging verbosity level.
6930  * @fwlog_enable: Enable/Disable logging.
6931  *
6932  * Initialize memory and post mailbox command to enable FW logging in host
6933  * memory.
6934  **/
6935 int
6936 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
6937                          uint32_t fwlog_level,
6938                          uint32_t fwlog_enable)
6939 {
6940         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6941         struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
6942         struct lpfc_dmabuf *dmabuf;
6943         LPFC_MBOXQ_t *mbox;
6944         uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
6945         int rc = 0;
6946
6947         spin_lock_irq(&phba->hbalock);
6948         ras_fwlog->state = INACTIVE;
6949         spin_unlock_irq(&phba->hbalock);
6950
6951         fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
6952                           phba->cfg_ras_fwlog_buffsize);
6953         fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
6954
6955         /*
6956          * If re-enabling FW logging support use earlier allocated
6957          * DMA buffers while posting MBX command.
6958          **/
6959         if (!ras_fwlog->lwpd.virt) {
6960                 rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
6961                 if (rc) {
6962                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6963                                         "6189 FW Log Memory Allocation Failed");
6964                         return rc;
6965                 }
6966         }
6967
6968         /* Setup Mailbox command */
6969         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6970         if (!mbox) {
6971                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6972                                 "6190 RAS MBX Alloc Failed");
6973                 rc = -ENOMEM;
6974                 goto mem_free;
6975         }
6976
6977         ras_fwlog->fw_loglevel = fwlog_level;
6978         len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
6979                 sizeof(struct lpfc_sli4_cfg_mhdr));
6980
6981         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
6982                          LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
6983                          len, LPFC_SLI4_MBX_EMBED);
6984
6985         mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
6986         bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
6987                fwlog_enable);
6988         bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
6989                ras_fwlog->fw_loglevel);
6990         bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
6991                ras_fwlog->fw_buffcount);
6992         bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
6993                LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
6994
6995         /* Update DMA buffer address */
6996         list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
6997                 memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
6998
6999                 mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
7000                         putPaddrLow(dmabuf->phys);
7001
7002                 mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
7003                         putPaddrHigh(dmabuf->phys);
7004         }
7005
7006         /* Update LPWD address */
7007         mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
7008         mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
7009
7010         spin_lock_irq(&phba->hbalock);
7011         ras_fwlog->state = REG_INPROGRESS;
7012         spin_unlock_irq(&phba->hbalock);
7013         mbox->vport = phba->pport;
7014         mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
7015
7016         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
7017
7018         if (rc == MBX_NOT_FINISHED) {
7019                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7020                                 "6191 FW-Log Mailbox failed. "
7021                                 "status %d mbxStatus : x%x", rc,
7022                                 bf_get(lpfc_mqe_status, &mbox->u.mqe));
7023                 mempool_free(mbox, phba->mbox_mem_pool);
7024                 rc = -EIO;
7025                 goto mem_free;
7026         } else
7027                 rc = 0;
7028 mem_free:
7029         if (rc)
7030                 lpfc_sli4_ras_dma_free(phba);
7031
7032         return rc;
7033 }
7034
7035 /**
7036  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
7037  * @phba: Pointer to HBA context object.
7038  *
7039  * Check if RAS is supported on the adapter and initialize it.
7040  **/
7041 void
7042 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
7043 {
7044         /* Check RAS FW Log needs to be enabled or not */
7045         if (lpfc_check_fwlog_support(phba))
7046                 return;
7047
7048         lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
7049                                  LPFC_RAS_ENABLE_LOGGING);
7050 }
7051
7052 /**
7053  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
7054  * @phba: Pointer to HBA context object.
7055  *
7056  * This function allocates all SLI4 resource identifiers.
7057  **/
7058 int
7059 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
7060 {
7061         int i, rc, error = 0;
7062         uint16_t count, base;
7063         unsigned long longs;
7064
7065         if (!phba->sli4_hba.rpi_hdrs_in_use)
7066                 phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
7067         if (phba->sli4_hba.extents_in_use) {
7068                 /*
7069                  * The port supports resource extents. The XRI, VPI, VFI, RPI
7070                  * resource extent count must be read and allocated before
7071                  * provisioning the resource id arrays.
7072                  */
7073                 if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7074                     LPFC_IDX_RSRC_RDY) {
7075                         /*
7076                          * Extent-based resources are set - the driver could
7077                          * be in a port reset. Figure out if any corrective
7078                          * actions need to be taken.
7079                          */
7080                         rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7081                                                  LPFC_RSC_TYPE_FCOE_VFI);
7082                         if (rc != 0)
7083                                 error++;
7084                         rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7085                                                  LPFC_RSC_TYPE_FCOE_VPI);
7086                         if (rc != 0)
7087                                 error++;
7088                         rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7089                                                  LPFC_RSC_TYPE_FCOE_XRI);
7090                         if (rc != 0)
7091                                 error++;
7092                         rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7093                                                  LPFC_RSC_TYPE_FCOE_RPI);
7094                         if (rc != 0)
7095                                 error++;
7096
7097                         /*
7098                          * It's possible that the number of resources
7099                          * provided to this port instance changed between
7100                          * resets.  Detect this condition and reallocate
7101                          * resources.  Otherwise, there is no action.
7102                          */
7103                         if (error) {
7104                                 lpfc_printf_log(phba, KERN_INFO,
7105                                                 LOG_MBOX | LOG_INIT,
7106                                                 "2931 Detected extent resource "
7107                                                 "change.  Reallocating all "
7108                                                 "extents.\n");
7109                                 rc = lpfc_sli4_dealloc_extent(phba,
7110                                                  LPFC_RSC_TYPE_FCOE_VFI);
7111                                 rc = lpfc_sli4_dealloc_extent(phba,
7112                                                  LPFC_RSC_TYPE_FCOE_VPI);
7113                                 rc = lpfc_sli4_dealloc_extent(phba,
7114                                                  LPFC_RSC_TYPE_FCOE_XRI);
7115                                 rc = lpfc_sli4_dealloc_extent(phba,
7116                                                  LPFC_RSC_TYPE_FCOE_RPI);
7117                         } else
7118                                 return 0;
7119                 }
7120
7121                 rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7122                 if (unlikely(rc))
7123                         goto err_exit;
7124
7125                 rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7126                 if (unlikely(rc))
7127                         goto err_exit;
7128
7129                 rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7130                 if (unlikely(rc))
7131                         goto err_exit;
7132
7133                 rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7134                 if (unlikely(rc))
7135                         goto err_exit;
7136                 bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7137                        LPFC_IDX_RSRC_RDY);
7138                 return rc;
7139         } else {
7140                 /*
7141                  * The port does not support resource extents.  The XRI, VPI,
7142                  * VFI, RPI resource ids were determined from READ_CONFIG.
7143                  * Just allocate the bitmasks and provision the resource id
7144                  * arrays.  If a port reset is active, the resources don't
7145                  * need any action - just exit.
7146                  */
7147                 if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7148                     LPFC_IDX_RSRC_RDY) {
7149                         lpfc_sli4_dealloc_resource_identifiers(phba);
7150                         lpfc_sli4_remove_rpis(phba);
7151                 }
7152                 /* RPIs. */
7153                 count = phba->sli4_hba.max_cfg_param.max_rpi;
7154                 if (count <= 0) {
7155                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7156                                         "3279 Invalid provisioning of "
7157                                         "rpi:%d\n", count);
7158                         rc = -EINVAL;
7159                         goto err_exit;
7160                 }
7161                 base = phba->sli4_hba.max_cfg_param.rpi_base;
7162                 longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7163                 phba->sli4_hba.rpi_bmask = kcalloc(longs,
7164                                                    sizeof(unsigned long),
7165                                                    GFP_KERNEL);
7166                 if (unlikely(!phba->sli4_hba.rpi_bmask)) {
7167                         rc = -ENOMEM;
7168                         goto err_exit;
7169                 }
7170                 phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
7171                                                  GFP_KERNEL);
7172                 if (unlikely(!phba->sli4_hba.rpi_ids)) {
7173                         rc = -ENOMEM;
7174                         goto free_rpi_bmask;
7175                 }
7176
7177                 for (i = 0; i < count; i++)
7178                         phba->sli4_hba.rpi_ids[i] = base + i;
7179
7180                 /* VPIs. */
7181                 count = phba->sli4_hba.max_cfg_param.max_vpi;
7182                 if (count <= 0) {
7183                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7184                                         "3280 Invalid provisioning of "
7185                                         "vpi:%d\n", count);
7186                         rc = -EINVAL;
7187                         goto free_rpi_ids;
7188                 }
7189                 base = phba->sli4_hba.max_cfg_param.vpi_base;
7190                 longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7191                 phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
7192                                           GFP_KERNEL);
7193                 if (unlikely(!phba->vpi_bmask)) {
7194                         rc = -ENOMEM;
7195                         goto free_rpi_ids;
7196                 }
7197                 phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
7198                                         GFP_KERNEL);
7199                 if (unlikely(!phba->vpi_ids)) {
7200                         rc = -ENOMEM;
7201                         goto free_vpi_bmask;
7202                 }
7203
7204                 for (i = 0; i < count; i++)
7205                         phba->vpi_ids[i] = base + i;
7206
7207                 /* XRIs. */
7208                 count = phba->sli4_hba.max_cfg_param.max_xri;
7209                 if (count <= 0) {
7210                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7211                                         "3281 Invalid provisioning of "
7212                                         "xri:%d\n", count);
7213                         rc = -EINVAL;
7214                         goto free_vpi_ids;
7215                 }
7216                 base = phba->sli4_hba.max_cfg_param.xri_base;
7217                 longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7218                 phba->sli4_hba.xri_bmask = kcalloc(longs,
7219                                                    sizeof(unsigned long),
7220                                                    GFP_KERNEL);
7221                 if (unlikely(!phba->sli4_hba.xri_bmask)) {
7222                         rc = -ENOMEM;
7223                         goto free_vpi_ids;
7224                 }
7225                 phba->sli4_hba.max_cfg_param.xri_used = 0;
7226                 phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
7227                                                  GFP_KERNEL);
7228                 if (unlikely(!phba->sli4_hba.xri_ids)) {
7229                         rc = -ENOMEM;
7230                         goto free_xri_bmask;
7231                 }
7232
7233                 for (i = 0; i < count; i++)
7234                         phba->sli4_hba.xri_ids[i] = base + i;
7235
7236                 /* VFIs. */
7237                 count = phba->sli4_hba.max_cfg_param.max_vfi;
7238                 if (count <= 0) {
7239                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7240                                         "3282 Invalid provisioning of "
7241                                         "vfi:%d\n", count);
7242                         rc = -EINVAL;
7243                         goto free_xri_ids;
7244                 }
7245                 base = phba->sli4_hba.max_cfg_param.vfi_base;
7246                 longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7247                 phba->sli4_hba.vfi_bmask = kcalloc(longs,
7248                                                    sizeof(unsigned long),
7249                                                    GFP_KERNEL);
7250                 if (unlikely(!phba->sli4_hba.vfi_bmask)) {
7251                         rc = -ENOMEM;
7252                         goto free_xri_ids;
7253                 }
7254                 phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
7255                                                  GFP_KERNEL);
7256                 if (unlikely(!phba->sli4_hba.vfi_ids)) {
7257                         rc = -ENOMEM;
7258                         goto free_vfi_bmask;
7259                 }
7260
7261                 for (i = 0; i < count; i++)
7262                         phba->sli4_hba.vfi_ids[i] = base + i;
7263
7264                 /*
7265                  * Mark all resources ready.  An HBA reset doesn't need
7266                  * to reset the initialization.
7267                  */
7268                 bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7269                        LPFC_IDX_RSRC_RDY);
7270                 return 0;
7271         }
7272
7273  free_vfi_bmask:
7274         kfree(phba->sli4_hba.vfi_bmask);
7275         phba->sli4_hba.vfi_bmask = NULL;
7276  free_xri_ids:
7277         kfree(phba->sli4_hba.xri_ids);
7278         phba->sli4_hba.xri_ids = NULL;
7279  free_xri_bmask:
7280         kfree(phba->sli4_hba.xri_bmask);
7281         phba->sli4_hba.xri_bmask = NULL;
7282  free_vpi_ids:
7283         kfree(phba->vpi_ids);
7284         phba->vpi_ids = NULL;
7285  free_vpi_bmask:
7286         kfree(phba->vpi_bmask);
7287         phba->vpi_bmask = NULL;
7288  free_rpi_ids:
7289         kfree(phba->sli4_hba.rpi_ids);
7290         phba->sli4_hba.rpi_ids = NULL;
7291  free_rpi_bmask:
7292         kfree(phba->sli4_hba.rpi_bmask);
7293         phba->sli4_hba.rpi_bmask = NULL;
7294  err_exit:
7295         return rc;
7296 }
7297
7298 /**
7299  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
7300  * @phba: Pointer to HBA context object.
7301  *
7302  * This function allocates the number of elements for the specified
7303  * resource type.
7304  **/
7305 int
7306 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
7307 {
7308         if (phba->sli4_hba.extents_in_use) {
7309                 lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7310                 lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7311                 lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7312                 lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7313         } else {
7314                 kfree(phba->vpi_bmask);
7315                 phba->sli4_hba.max_cfg_param.vpi_used = 0;
7316                 kfree(phba->vpi_ids);
7317                 bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7318                 kfree(phba->sli4_hba.xri_bmask);
7319                 kfree(phba->sli4_hba.xri_ids);
7320                 kfree(phba->sli4_hba.vfi_bmask);
7321                 kfree(phba->sli4_hba.vfi_ids);
7322                 bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7323                 bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7324         }
7325
7326         return 0;
7327 }
7328
7329 /**
7330  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
7331  * @phba: Pointer to HBA context object.
7332  * @type: The resource extent type.
7333  * @extnt_cnt: buffer to hold port extent count response
7334  * @extnt_size: buffer to hold port extent size response.
7335  *
7336  * This function calls the port to read the host allocated extents
7337  * for a particular type.
7338  **/
7339 int
7340 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
7341                                uint16_t *extnt_cnt, uint16_t *extnt_size)
7342 {
7343         bool emb;
7344         int rc = 0;
7345         uint16_t curr_blks = 0;
7346         uint32_t req_len, emb_len;
7347         uint32_t alloc_len, mbox_tmo;
7348         struct list_head *blk_list_head;
7349         struct lpfc_rsrc_blks *rsrc_blk;
7350         LPFC_MBOXQ_t *mbox;
7351         void *virtaddr = NULL;
7352         struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
7353         struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
7354         union  lpfc_sli4_cfg_shdr *shdr;
7355
7356         switch (type) {
7357         case LPFC_RSC_TYPE_FCOE_VPI:
7358                 blk_list_head = &phba->lpfc_vpi_blk_list;
7359                 break;
7360         case LPFC_RSC_TYPE_FCOE_XRI:
7361                 blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
7362                 break;
7363         case LPFC_RSC_TYPE_FCOE_VFI:
7364                 blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
7365                 break;
7366         case LPFC_RSC_TYPE_FCOE_RPI:
7367                 blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
7368                 break;
7369         default:
7370                 return -EIO;
7371         }
7372
7373         /* Count the number of extents currently allocatd for this type. */
7374         list_for_each_entry(rsrc_blk, blk_list_head, list) {
7375                 if (curr_blks == 0) {
7376                         /*
7377                          * The GET_ALLOCATED mailbox does not return the size,
7378                          * just the count.  The size should be just the size
7379                          * stored in the current allocated block and all sizes
7380                          * for an extent type are the same so set the return
7381                          * value now.
7382                          */
7383                         *extnt_size = rsrc_blk->rsrc_size;
7384                 }
7385                 curr_blks++;
7386         }
7387
7388         /*
7389          * Calculate the size of an embedded mailbox.  The uint32_t
7390          * accounts for extents-specific word.
7391          */
7392         emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
7393                 sizeof(uint32_t);
7394
7395         /*
7396          * Presume the allocation and response will fit into an embedded
7397          * mailbox.  If not true, reconfigure to a non-embedded mailbox.
7398          */
7399         emb = LPFC_SLI4_MBX_EMBED;
7400         req_len = emb_len;
7401         if (req_len > emb_len) {
7402                 req_len = curr_blks * sizeof(uint16_t) +
7403                         sizeof(union lpfc_sli4_cfg_shdr) +
7404                         sizeof(uint32_t);
7405                 emb = LPFC_SLI4_MBX_NEMBED;
7406         }
7407
7408         mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7409         if (!mbox)
7410                 return -ENOMEM;
7411         memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
7412
7413         alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7414                                      LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
7415                                      req_len, emb);
7416         if (alloc_len < req_len) {
7417                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7418                         "2983 Allocated DMA memory size (x%x) is "
7419                         "less than the requested DMA memory "
7420                         "size (x%x)\n", alloc_len, req_len);
7421                 rc = -ENOMEM;
7422                 goto err_exit;
7423         }
7424         rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
7425         if (unlikely(rc)) {
7426                 rc = -EIO;
7427                 goto err_exit;
7428         }
7429
7430         if (!phba->sli4_hba.intr_enable)
7431                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7432         else {
7433                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7434                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7435         }
7436
7437         if (unlikely(rc)) {
7438                 rc = -EIO;
7439                 goto err_exit;
7440         }
7441
7442         /*
7443          * Figure out where the response is located.  Then get local pointers
7444          * to the response data.  The port does not guarantee to respond to
7445          * all extents counts request so update the local variable with the
7446          * allocated count from the port.
7447          */
7448         if (emb == LPFC_SLI4_MBX_EMBED) {
7449                 rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7450                 shdr = &rsrc_ext->header.cfg_shdr;
7451                 *extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7452         } else {
7453                 virtaddr = mbox->sge_array->addr[0];
7454                 n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7455                 shdr = &n_rsrc->cfg_shdr;
7456                 *extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7457         }
7458
7459         if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7460                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7461                         "2984 Failed to read allocated resources "
7462                         "for type %d - Status 0x%x Add'l Status 0x%x.\n",
7463                         type,
7464                         bf_get(lpfc_mbox_hdr_status, &shdr->response),
7465                         bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7466                 rc = -EIO;
7467                 goto err_exit;
7468         }
7469  err_exit:
7470         lpfc_sli4_mbox_cmd_free(phba, mbox);
7471         return rc;
7472 }
7473
7474 /**
7475  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7476  * @phba: pointer to lpfc hba data structure.
7477  * @sgl_list: linked link of sgl buffers to post
7478  * @cnt: number of linked list buffers
7479  *
7480  * This routine walks the list of buffers that have been allocated and
7481  * repost them to the port by using SGL block post. This is needed after a
7482  * pci_function_reset/warm_start or start. It attempts to construct blocks
7483  * of buffer sgls which contains contiguous xris and uses the non-embedded
7484  * SGL block post mailbox commands to post them to the port. For single
7485  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7486  * mailbox command for posting.
7487  *
7488  * Returns: 0 = success, non-zero failure.
7489  **/
7490 static int
7491 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7492                           struct list_head *sgl_list, int cnt)
7493 {
7494         struct lpfc_sglq *sglq_entry = NULL;
7495         struct lpfc_sglq *sglq_entry_next = NULL;
7496         struct lpfc_sglq *sglq_entry_first = NULL;
7497         int status, total_cnt;
7498         int post_cnt = 0, num_posted = 0, block_cnt = 0;
7499         int last_xritag = NO_XRI;
7500         LIST_HEAD(prep_sgl_list);
7501         LIST_HEAD(blck_sgl_list);
7502         LIST_HEAD(allc_sgl_list);
7503         LIST_HEAD(post_sgl_list);
7504         LIST_HEAD(free_sgl_list);
7505
7506         spin_lock_irq(&phba->hbalock);
7507         spin_lock(&phba->sli4_hba.sgl_list_lock);
7508         list_splice_init(sgl_list, &allc_sgl_list);
7509         spin_unlock(&phba->sli4_hba.sgl_list_lock);
7510         spin_unlock_irq(&phba->hbalock);
7511
7512         total_cnt = cnt;
7513         list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7514                                  &allc_sgl_list, list) {
7515                 list_del_init(&sglq_entry->list);
7516                 block_cnt++;
7517                 if ((last_xritag != NO_XRI) &&
7518                     (sglq_entry->sli4_xritag != last_xritag + 1)) {
7519                         /* a hole in xri block, form a sgl posting block */
7520                         list_splice_init(&prep_sgl_list, &blck_sgl_list);
7521                         post_cnt = block_cnt - 1;
7522                         /* prepare list for next posting block */
7523                         list_add_tail(&sglq_entry->list, &prep_sgl_list);
7524                         block_cnt = 1;
7525                 } else {
7526                         /* prepare list for next posting block */
7527                         list_add_tail(&sglq_entry->list, &prep_sgl_list);
7528                         /* enough sgls for non-embed sgl mbox command */
7529                         if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7530                                 list_splice_init(&prep_sgl_list,
7531                                                  &blck_sgl_list);
7532                                 post_cnt = block_cnt;
7533                                 block_cnt = 0;
7534                         }
7535                 }
7536                 num_posted++;
7537
7538                 /* keep track of last sgl's xritag */
7539                 last_xritag = sglq_entry->sli4_xritag;
7540
7541                 /* end of repost sgl list condition for buffers */
7542                 if (num_posted == total_cnt) {
7543                         if (post_cnt == 0) {
7544                                 list_splice_init(&prep_sgl_list,
7545                                                  &blck_sgl_list);
7546                                 post_cnt = block_cnt;
7547                         } else if (block_cnt == 1) {
7548                                 status = lpfc_sli4_post_sgl(phba,
7549                                                 sglq_entry->phys, 0,
7550                                                 sglq_entry->sli4_xritag);
7551                                 if (!status) {
7552                                         /* successful, put sgl to posted list */
7553                                         list_add_tail(&sglq_entry->list,
7554                                                       &post_sgl_list);
7555                                 } else {
7556                                         /* Failure, put sgl to free list */
7557                                         lpfc_printf_log(phba, KERN_WARNING,
7558                                                 LOG_SLI,
7559                                                 "3159 Failed to post "
7560                                                 "sgl, xritag:x%x\n",
7561                                                 sglq_entry->sli4_xritag);
7562                                         list_add_tail(&sglq_entry->list,
7563                                                       &free_sgl_list);
7564                                         total_cnt--;
7565                                 }
7566                         }
7567                 }
7568
7569                 /* continue until a nembed page worth of sgls */
7570                 if (post_cnt == 0)
7571                         continue;
7572
7573                 /* post the buffer list sgls as a block */
7574                 status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7575                                                  post_cnt);
7576
7577                 if (!status) {
7578                         /* success, put sgl list to posted sgl list */
7579                         list_splice_init(&blck_sgl_list, &post_sgl_list);
7580                 } else {
7581                         /* Failure, put sgl list to free sgl list */
7582                         sglq_entry_first = list_first_entry(&blck_sgl_list,
7583                                                             struct lpfc_sglq,
7584                                                             list);
7585                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7586                                         "3160 Failed to post sgl-list, "
7587                                         "xritag:x%x-x%x\n",
7588                                         sglq_entry_first->sli4_xritag,
7589                                         (sglq_entry_first->sli4_xritag +
7590                                          post_cnt - 1));
7591                         list_splice_init(&blck_sgl_list, &free_sgl_list);
7592                         total_cnt -= post_cnt;
7593                 }
7594
7595                 /* don't reset xirtag due to hole in xri block */
7596                 if (block_cnt == 0)
7597                         last_xritag = NO_XRI;
7598
7599                 /* reset sgl post count for next round of posting */
7600                 post_cnt = 0;
7601         }
7602
7603         /* free the sgls failed to post */
7604         lpfc_free_sgl_list(phba, &free_sgl_list);
7605
7606         /* push sgls posted to the available list */
7607         if (!list_empty(&post_sgl_list)) {
7608                 spin_lock_irq(&phba->hbalock);
7609                 spin_lock(&phba->sli4_hba.sgl_list_lock);
7610                 list_splice_init(&post_sgl_list, sgl_list);
7611                 spin_unlock(&phba->sli4_hba.sgl_list_lock);
7612                 spin_unlock_irq(&phba->hbalock);
7613         } else {
7614                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7615                                 "3161 Failure to post sgl to port.\n");
7616                 return -EIO;
7617         }
7618
7619         /* return the number of XRIs actually posted */
7620         return total_cnt;
7621 }
7622
7623 /**
7624  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7625  * @phba: pointer to lpfc hba data structure.
7626  *
7627  * This routine walks the list of nvme buffers that have been allocated and
7628  * repost them to the port by using SGL block post. This is needed after a
7629  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7630  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7631  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7632  *
7633  * Returns: 0 = success, non-zero failure.
7634  **/
7635 static int
7636 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7637 {
7638         LIST_HEAD(post_nblist);
7639         int num_posted, rc = 0;
7640
7641         /* get all NVME buffers need to repost to a local list */
7642         lpfc_io_buf_flush(phba, &post_nblist);
7643
7644         /* post the list of nvme buffer sgls to port if available */
7645         if (!list_empty(&post_nblist)) {
7646                 num_posted = lpfc_sli4_post_io_sgl_list(
7647                         phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7648                 /* failed to post any nvme buffer, return error */
7649                 if (num_posted == 0)
7650                         rc = -EIO;
7651         }
7652         return rc;
7653 }
7654
7655 static void
7656 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7657 {
7658         uint32_t len;
7659
7660         len = sizeof(struct lpfc_mbx_set_host_data) -
7661                 sizeof(struct lpfc_sli4_cfg_mhdr);
7662         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7663                          LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7664                          LPFC_SLI4_MBX_EMBED);
7665
7666         mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7667         mbox->u.mqe.un.set_host_data.param_len =
7668                                         LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7669         snprintf(mbox->u.mqe.un.set_host_data.un.data,
7670                  LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7671                  "Linux %s v"LPFC_DRIVER_VERSION,
7672                  (phba->hba_flag & HBA_FCOE_MODE) ? "FCoE" : "FC");
7673 }
7674
7675 int
7676 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7677                     struct lpfc_queue *drq, int count, int idx)
7678 {
7679         int rc, i;
7680         struct lpfc_rqe hrqe;
7681         struct lpfc_rqe drqe;
7682         struct lpfc_rqb *rqbp;
7683         unsigned long flags;
7684         struct rqb_dmabuf *rqb_buffer;
7685         LIST_HEAD(rqb_buf_list);
7686
7687         rqbp = hrq->rqbp;
7688         for (i = 0; i < count; i++) {
7689                 spin_lock_irqsave(&phba->hbalock, flags);
7690                 /* IF RQ is already full, don't bother */
7691                 if (rqbp->buffer_count + i >= rqbp->entry_count - 1) {
7692                         spin_unlock_irqrestore(&phba->hbalock, flags);
7693                         break;
7694                 }
7695                 spin_unlock_irqrestore(&phba->hbalock, flags);
7696
7697                 rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7698                 if (!rqb_buffer)
7699                         break;
7700                 rqb_buffer->hrq = hrq;
7701                 rqb_buffer->drq = drq;
7702                 rqb_buffer->idx = idx;
7703                 list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7704         }
7705
7706         spin_lock_irqsave(&phba->hbalock, flags);
7707         while (!list_empty(&rqb_buf_list)) {
7708                 list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7709                                  hbuf.list);
7710
7711                 hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7712                 hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7713                 drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7714                 drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7715                 rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7716                 if (rc < 0) {
7717                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7718                                         "6421 Cannot post to HRQ %d: %x %x %x "
7719                                         "DRQ %x %x\n",
7720                                         hrq->queue_id,
7721                                         hrq->host_index,
7722                                         hrq->hba_index,
7723                                         hrq->entry_count,
7724                                         drq->host_index,
7725                                         drq->hba_index);
7726                         rqbp->rqb_free_buffer(phba, rqb_buffer);
7727                 } else {
7728                         list_add_tail(&rqb_buffer->hbuf.list,
7729                                       &rqbp->rqb_buffer_list);
7730                         rqbp->buffer_count++;
7731                 }
7732         }
7733         spin_unlock_irqrestore(&phba->hbalock, flags);
7734         return 1;
7735 }
7736
7737 static void
7738 lpfc_mbx_cmpl_cgn_set_ftrs(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7739 {
7740         struct lpfc_vport *vport = pmb->vport;
7741         union lpfc_sli4_cfg_shdr *shdr;
7742         u32 shdr_status, shdr_add_status;
7743         u32 sig, acqe;
7744
7745         /* Two outcomes. (1) Set featurs was successul and EDC negotiation
7746          * is done. (2) Mailbox failed and send FPIN support only.
7747          */
7748         shdr = (union lpfc_sli4_cfg_shdr *)
7749                 &pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7750         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7751         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7752         if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7753                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
7754                                 "2516 CGN SET_FEATURE mbox failed with "
7755                                 "status x%x add_status x%x, mbx status x%x "
7756                                 "Reset Congestion to FPINs only\n",
7757                                 shdr_status, shdr_add_status,
7758                                 pmb->u.mb.mbxStatus);
7759                 /* If there is a mbox error, move on to RDF */
7760                 phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7761                 phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7762                 goto out;
7763         }
7764
7765         /* Zero out Congestion Signal ACQE counter */
7766         phba->cgn_acqe_cnt = 0;
7767
7768         acqe = bf_get(lpfc_mbx_set_feature_CGN_acqe_freq,
7769                       &pmb->u.mqe.un.set_feature);
7770         sig = bf_get(lpfc_mbx_set_feature_CGN_warn_freq,
7771                      &pmb->u.mqe.un.set_feature);
7772         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7773                         "4620 SET_FEATURES Success: Freq: %ds %dms "
7774                         " Reg: x%x x%x\n", acqe, sig,
7775                         phba->cgn_reg_signal, phba->cgn_reg_fpin);
7776 out:
7777         mempool_free(pmb, phba->mbox_mem_pool);
7778
7779         /* Register for FPIN events from the fabric now that the
7780          * EDC common_set_features has completed.
7781          */
7782         lpfc_issue_els_rdf(vport, 0);
7783 }
7784
7785 int
7786 lpfc_config_cgn_signal(struct lpfc_hba *phba)
7787 {
7788         LPFC_MBOXQ_t *mboxq;
7789         u32 rc;
7790
7791         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7792         if (!mboxq)
7793                 goto out_rdf;
7794
7795         lpfc_set_features(phba, mboxq, LPFC_SET_CGN_SIGNAL);
7796         mboxq->vport = phba->pport;
7797         mboxq->mbox_cmpl = lpfc_mbx_cmpl_cgn_set_ftrs;
7798
7799         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7800                         "4621 SET_FEATURES: FREQ sig x%x acqe x%x: "
7801                         "Reg: x%x x%x\n",
7802                         phba->cgn_sig_freq, lpfc_acqe_cgn_frequency,
7803                         phba->cgn_reg_signal, phba->cgn_reg_fpin);
7804
7805         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7806         if (rc == MBX_NOT_FINISHED)
7807                 goto out;
7808         return 0;
7809
7810 out:
7811         mempool_free(mboxq, phba->mbox_mem_pool);
7812 out_rdf:
7813         /* If there is a mbox error, move on to RDF */
7814         phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7815         phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7816         lpfc_issue_els_rdf(phba->pport, 0);
7817         return -EIO;
7818 }
7819
7820 /**
7821  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7822  * @phba: pointer to lpfc hba data structure.
7823  *
7824  * This routine initializes the per-cq idle_stat to dynamically dictate
7825  * polling decisions.
7826  *
7827  * Return codes:
7828  *   None
7829  **/
7830 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
7831 {
7832         int i;
7833         struct lpfc_sli4_hdw_queue *hdwq;
7834         struct lpfc_queue *cq;
7835         struct lpfc_idle_stat *idle_stat;
7836         u64 wall;
7837
7838         for_each_present_cpu(i) {
7839                 hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
7840                 cq = hdwq->io_cq;
7841
7842                 /* Skip if we've already handled this cq's primary CPU */
7843                 if (cq->chann != i)
7844                         continue;
7845
7846                 idle_stat = &phba->sli4_hba.idle_stat[i];
7847
7848                 idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
7849                 idle_stat->prev_wall = wall;
7850
7851                 if (phba->nvmet_support ||
7852                     phba->cmf_active_mode != LPFC_CFG_OFF)
7853                         cq->poll_mode = LPFC_QUEUE_WORK;
7854                 else
7855                         cq->poll_mode = LPFC_IRQ_POLL;
7856         }
7857
7858         if (!phba->nvmet_support)
7859                 schedule_delayed_work(&phba->idle_stat_delay_work,
7860                                       msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
7861 }
7862
7863 static void lpfc_sli4_dip(struct lpfc_hba *phba)
7864 {
7865         uint32_t if_type;
7866
7867         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
7868         if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
7869             if_type == LPFC_SLI_INTF_IF_TYPE_6) {
7870                 struct lpfc_register reg_data;
7871
7872                 if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
7873                                &reg_data.word0))
7874                         return;
7875
7876                 if (bf_get(lpfc_sliport_status_dip, &reg_data))
7877                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
7878                                         "2904 Firmware Dump Image Present"
7879                                         " on Adapter");
7880         }
7881 }
7882
7883 /**
7884  * lpfc_cmf_setup - Initialize idle_stat tracking
7885  * @phba: Pointer to HBA context object.
7886  *
7887  * This is called from HBA setup during driver load or when the HBA
7888  * comes online. this does all the initialization to support CMF and MI.
7889  **/
7890 static int
7891 lpfc_cmf_setup(struct lpfc_hba *phba)
7892 {
7893         LPFC_MBOXQ_t *mboxq;
7894         struct lpfc_dmabuf *mp;
7895         struct lpfc_pc_sli4_params *sli4_params;
7896         int rc, cmf, mi_ver;
7897
7898         rc = lpfc_sli4_refresh_params(phba);
7899         if (unlikely(rc))
7900                 return rc;
7901
7902         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7903         if (!mboxq)
7904                 return -ENOMEM;
7905
7906         sli4_params = &phba->sli4_hba.pc_sli4_params;
7907
7908         /* Are we forcing MI off via module parameter? */
7909         if (!phba->cfg_enable_mi)
7910                 sli4_params->mi_ver = 0;
7911
7912         /* Always try to enable MI feature if we can */
7913         if (sli4_params->mi_ver) {
7914                 lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_MI);
7915                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7916                 mi_ver = bf_get(lpfc_mbx_set_feature_mi,
7917                                  &mboxq->u.mqe.un.set_feature);
7918
7919                 if (rc == MBX_SUCCESS) {
7920                         if (mi_ver) {
7921                                 lpfc_printf_log(phba,
7922                                                 KERN_WARNING, LOG_CGN_MGMT,
7923                                                 "6215 MI is enabled\n");
7924                                 sli4_params->mi_ver = mi_ver;
7925                         } else {
7926                                 lpfc_printf_log(phba,
7927                                                 KERN_WARNING, LOG_CGN_MGMT,
7928                                                 "6338 MI is disabled\n");
7929                                 sli4_params->mi_ver = 0;
7930                         }
7931                 } else {
7932                         /* mi_ver is already set from GET_SLI4_PARAMETERS */
7933                         lpfc_printf_log(phba, KERN_INFO,
7934                                         LOG_CGN_MGMT | LOG_INIT,
7935                                         "6245 Enable MI Mailbox x%x (x%x/x%x) "
7936                                         "failed, rc:x%x mi:x%x\n",
7937                                         bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7938                                         lpfc_sli_config_mbox_subsys_get
7939                                                 (phba, mboxq),
7940                                         lpfc_sli_config_mbox_opcode_get
7941                                                 (phba, mboxq),
7942                                         rc, sli4_params->mi_ver);
7943                 }
7944         } else {
7945                 lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
7946                                 "6217 MI is disabled\n");
7947         }
7948
7949         /* Ensure FDMI is enabled for MI if enable_mi is set */
7950         if (sli4_params->mi_ver)
7951                 phba->cfg_fdmi_on = LPFC_FDMI_SUPPORT;
7952
7953         /* Always try to enable CMF feature if we can */
7954         if (sli4_params->cmf) {
7955                 lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_CMF);
7956                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
7957                 cmf = bf_get(lpfc_mbx_set_feature_cmf,
7958                              &mboxq->u.mqe.un.set_feature);
7959                 if (rc == MBX_SUCCESS && cmf) {
7960                         lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
7961                                         "6218 CMF is enabled: mode %d\n",
7962                                         phba->cmf_active_mode);
7963                 } else {
7964                         lpfc_printf_log(phba, KERN_WARNING,
7965                                         LOG_CGN_MGMT | LOG_INIT,
7966                                         "6219 Enable CMF Mailbox x%x (x%x/x%x) "
7967                                         "failed, rc:x%x dd:x%x\n",
7968                                         bf_get(lpfc_mqe_command, &mboxq->u.mqe),
7969                                         lpfc_sli_config_mbox_subsys_get
7970                                                 (phba, mboxq),
7971                                         lpfc_sli_config_mbox_opcode_get
7972                                                 (phba, mboxq),
7973                                         rc, cmf);
7974                         sli4_params->cmf = 0;
7975                         phba->cmf_active_mode = LPFC_CFG_OFF;
7976                         goto no_cmf;
7977                 }
7978
7979                 /* Allocate Congestion Information Buffer */
7980                 if (!phba->cgn_i) {
7981                         mp = kmalloc(sizeof(*mp), GFP_KERNEL);
7982                         if (mp)
7983                                 mp->virt = dma_alloc_coherent
7984                                                 (&phba->pcidev->dev,
7985                                                 sizeof(struct lpfc_cgn_info),
7986                                                 &mp->phys, GFP_KERNEL);
7987                         if (!mp || !mp->virt) {
7988                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
7989                                                 "2640 Failed to alloc memory "
7990                                                 "for Congestion Info\n");
7991                                 kfree(mp);
7992                                 sli4_params->cmf = 0;
7993                                 phba->cmf_active_mode = LPFC_CFG_OFF;
7994                                 goto no_cmf;
7995                         }
7996                         phba->cgn_i = mp;
7997
7998                         /* initialize congestion buffer info */
7999                         lpfc_init_congestion_buf(phba);
8000                         lpfc_init_congestion_stat(phba);
8001
8002                         /* Zero out Congestion Signal counters */
8003                         atomic64_set(&phba->cgn_acqe_stat.alarm, 0);
8004                         atomic64_set(&phba->cgn_acqe_stat.warn, 0);
8005                 }
8006
8007                 rc = lpfc_sli4_cgn_params_read(phba);
8008                 if (rc < 0) {
8009                         lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8010                                         "6242 Error reading Cgn Params (%d)\n",
8011                                         rc);
8012                         /* Ensure CGN Mode is off */
8013                         sli4_params->cmf = 0;
8014                 } else if (!rc) {
8015                         lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8016                                         "6243 CGN Event empty object.\n");
8017                         /* Ensure CGN Mode is off */
8018                         sli4_params->cmf = 0;
8019                 }
8020         } else {
8021 no_cmf:
8022                 lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8023                                 "6220 CMF is disabled\n");
8024         }
8025
8026         /* Only register congestion buffer with firmware if BOTH
8027          * CMF and E2E are enabled.
8028          */
8029         if (sli4_params->cmf && sli4_params->mi_ver) {
8030                 rc = lpfc_reg_congestion_buf(phba);
8031                 if (rc) {
8032                         dma_free_coherent(&phba->pcidev->dev,
8033                                           sizeof(struct lpfc_cgn_info),
8034                                           phba->cgn_i->virt, phba->cgn_i->phys);
8035                         kfree(phba->cgn_i);
8036                         phba->cgn_i = NULL;
8037                         /* Ensure CGN Mode is off */
8038                         phba->cmf_active_mode = LPFC_CFG_OFF;
8039                         return 0;
8040                 }
8041         }
8042         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8043                         "6470 Setup MI version %d CMF %d mode %d\n",
8044                         sli4_params->mi_ver, sli4_params->cmf,
8045                         phba->cmf_active_mode);
8046
8047         mempool_free(mboxq, phba->mbox_mem_pool);
8048
8049         /* Initialize atomic counters */
8050         atomic_set(&phba->cgn_fabric_warn_cnt, 0);
8051         atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
8052         atomic_set(&phba->cgn_sync_alarm_cnt, 0);
8053         atomic_set(&phba->cgn_sync_warn_cnt, 0);
8054         atomic_set(&phba->cgn_driver_evt_cnt, 0);
8055         atomic_set(&phba->cgn_latency_evt_cnt, 0);
8056         atomic64_set(&phba->cgn_latency_evt, 0);
8057
8058         phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
8059
8060         /* Allocate RX Monitor Buffer */
8061         if (!phba->rxtable) {
8062                 phba->rxtable = kmalloc_array(LPFC_MAX_RXMONITOR_ENTRY,
8063                                               sizeof(struct rxtable_entry),
8064                                               GFP_KERNEL);
8065                 if (!phba->rxtable) {
8066                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8067                                         "2644 Failed to alloc memory "
8068                                         "for RX Monitor Buffer\n");
8069                         return -ENOMEM;
8070                 }
8071         }
8072         atomic_set(&phba->rxtable_idx_head, 0);
8073         atomic_set(&phba->rxtable_idx_tail, 0);
8074         return 0;
8075 }
8076
8077 static int
8078 lpfc_set_host_tm(struct lpfc_hba *phba)
8079 {
8080         LPFC_MBOXQ_t *mboxq;
8081         uint32_t len, rc;
8082         struct timespec64 cur_time;
8083         struct tm broken;
8084         uint32_t month, day, year;
8085         uint32_t hour, minute, second;
8086         struct lpfc_mbx_set_host_date_time *tm;
8087
8088         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8089         if (!mboxq)
8090                 return -ENOMEM;
8091
8092         len = sizeof(struct lpfc_mbx_set_host_data) -
8093                 sizeof(struct lpfc_sli4_cfg_mhdr);
8094         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
8095                          LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
8096                          LPFC_SLI4_MBX_EMBED);
8097
8098         mboxq->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_DATE_TIME;
8099         mboxq->u.mqe.un.set_host_data.param_len =
8100                         sizeof(struct lpfc_mbx_set_host_date_time);
8101         tm = &mboxq->u.mqe.un.set_host_data.un.tm;
8102         ktime_get_real_ts64(&cur_time);
8103         time64_to_tm(cur_time.tv_sec, 0, &broken);
8104         month = broken.tm_mon + 1;
8105         day = broken.tm_mday;
8106         year = broken.tm_year - 100;
8107         hour = broken.tm_hour;
8108         minute = broken.tm_min;
8109         second = broken.tm_sec;
8110         bf_set(lpfc_mbx_set_host_month, tm, month);
8111         bf_set(lpfc_mbx_set_host_day, tm, day);
8112         bf_set(lpfc_mbx_set_host_year, tm, year);
8113         bf_set(lpfc_mbx_set_host_hour, tm, hour);
8114         bf_set(lpfc_mbx_set_host_min, tm, minute);
8115         bf_set(lpfc_mbx_set_host_sec, tm, second);
8116
8117         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8118         mempool_free(mboxq, phba->mbox_mem_pool);
8119         return rc;
8120 }
8121
8122 /**
8123  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
8124  * @phba: Pointer to HBA context object.
8125  *
8126  * This function is the main SLI4 device initialization PCI function. This
8127  * function is called by the HBA initialization code, HBA reset code and
8128  * HBA error attention handler code. Caller is not required to hold any
8129  * locks.
8130  **/
8131 int
8132 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
8133 {
8134         int rc, i, cnt, len, dd;
8135         LPFC_MBOXQ_t *mboxq;
8136         struct lpfc_mqe *mqe;
8137         uint8_t *vpd;
8138         uint32_t vpd_size;
8139         uint32_t ftr_rsp = 0;
8140         struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
8141         struct lpfc_vport *vport = phba->pport;
8142         struct lpfc_dmabuf *mp;
8143         struct lpfc_rqb *rqbp;
8144         u32 flg;
8145
8146         /* Perform a PCI function reset to start from clean */
8147         rc = lpfc_pci_function_reset(phba);
8148         if (unlikely(rc))
8149                 return -ENODEV;
8150
8151         /* Check the HBA Host Status Register for readyness */
8152         rc = lpfc_sli4_post_status_check(phba);
8153         if (unlikely(rc))
8154                 return -ENODEV;
8155         else {
8156                 spin_lock_irq(&phba->hbalock);
8157                 phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
8158                 flg = phba->sli.sli_flag;
8159                 spin_unlock_irq(&phba->hbalock);
8160                 /* Allow a little time after setting SLI_ACTIVE for any polled
8161                  * MBX commands to complete via BSG.
8162                  */
8163                 for (i = 0; i < 50 && (flg & LPFC_SLI_MBOX_ACTIVE); i++) {
8164                         msleep(20);
8165                         spin_lock_irq(&phba->hbalock);
8166                         flg = phba->sli.sli_flag;
8167                         spin_unlock_irq(&phba->hbalock);
8168                 }
8169         }
8170
8171         lpfc_sli4_dip(phba);
8172
8173         /*
8174          * Allocate a single mailbox container for initializing the
8175          * port.
8176          */
8177         mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8178         if (!mboxq)
8179                 return -ENOMEM;
8180
8181         /* Issue READ_REV to collect vpd and FW information. */
8182         vpd_size = SLI4_PAGE_SIZE;
8183         vpd = kzalloc(vpd_size, GFP_KERNEL);
8184         if (!vpd) {
8185                 rc = -ENOMEM;
8186                 goto out_free_mbox;
8187         }
8188
8189         rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
8190         if (unlikely(rc)) {
8191                 kfree(vpd);
8192                 goto out_free_mbox;
8193         }
8194
8195         mqe = &mboxq->u.mqe;
8196         phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
8197         if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
8198                 phba->hba_flag |= HBA_FCOE_MODE;
8199                 phba->fcp_embed_io = 0; /* SLI4 FC support only */
8200         } else {
8201                 phba->hba_flag &= ~HBA_FCOE_MODE;
8202         }
8203
8204         if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
8205                 LPFC_DCBX_CEE_MODE)
8206                 phba->hba_flag |= HBA_FIP_SUPPORT;
8207         else
8208                 phba->hba_flag &= ~HBA_FIP_SUPPORT;
8209
8210         phba->hba_flag &= ~HBA_IOQ_FLUSH;
8211
8212         if (phba->sli_rev != LPFC_SLI_REV4) {
8213                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8214                         "0376 READ_REV Error. SLI Level %d "
8215                         "FCoE enabled %d\n",
8216                         phba->sli_rev, phba->hba_flag & HBA_FCOE_MODE);
8217                 rc = -EIO;
8218                 kfree(vpd);
8219                 goto out_free_mbox;
8220         }
8221
8222         rc = lpfc_set_host_tm(phba);
8223         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
8224                         "6468 Set host date / time: Status x%x:\n", rc);
8225
8226         /*
8227          * Continue initialization with default values even if driver failed
8228          * to read FCoE param config regions, only read parameters if the
8229          * board is FCoE
8230          */
8231         if (phba->hba_flag & HBA_FCOE_MODE &&
8232             lpfc_sli4_read_fcoe_params(phba))
8233                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
8234                         "2570 Failed to read FCoE parameters\n");
8235
8236         /*
8237          * Retrieve sli4 device physical port name, failure of doing it
8238          * is considered as non-fatal.
8239          */
8240         rc = lpfc_sli4_retrieve_pport_name(phba);
8241         if (!rc)
8242                 lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8243                                 "3080 Successful retrieving SLI4 device "
8244                                 "physical port name: %s.\n", phba->Port);
8245
8246         rc = lpfc_sli4_get_ctl_attr(phba);
8247         if (!rc)
8248                 lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8249                                 "8351 Successful retrieving SLI4 device "
8250                                 "CTL ATTR\n");
8251
8252         /*
8253          * Evaluate the read rev and vpd data. Populate the driver
8254          * state with the results. If this routine fails, the failure
8255          * is not fatal as the driver will use generic values.
8256          */
8257         rc = lpfc_parse_vpd(phba, vpd, vpd_size);
8258         if (unlikely(!rc)) {
8259                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8260                                 "0377 Error %d parsing vpd. "
8261                                 "Using defaults.\n", rc);
8262                 rc = 0;
8263         }
8264         kfree(vpd);
8265
8266         /* Save information as VPD data */
8267         phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
8268         phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
8269
8270         /*
8271          * This is because first G7 ASIC doesn't support the standard
8272          * 0x5a NVME cmd descriptor type/subtype
8273          */
8274         if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8275                         LPFC_SLI_INTF_IF_TYPE_6) &&
8276             (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
8277             (phba->vpd.rev.smRev == 0) &&
8278             (phba->cfg_nvme_embed_cmd == 1))
8279                 phba->cfg_nvme_embed_cmd = 0;
8280
8281         phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
8282         phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
8283                                          &mqe->un.read_rev);
8284         phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
8285                                        &mqe->un.read_rev);
8286         phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
8287                                             &mqe->un.read_rev);
8288         phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
8289                                            &mqe->un.read_rev);
8290         phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
8291         memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
8292         phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
8293         memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
8294         phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
8295         memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
8296         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8297                         "(%d):0380 READ_REV Status x%x "
8298                         "fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
8299                         mboxq->vport ? mboxq->vport->vpi : 0,
8300                         bf_get(lpfc_mqe_status, mqe),
8301                         phba->vpd.rev.opFwName,
8302                         phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
8303                         phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
8304
8305         if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8306             LPFC_SLI_INTF_IF_TYPE_0) {
8307                 lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
8308                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8309                 if (rc == MBX_SUCCESS) {
8310                         phba->hba_flag |= HBA_RECOVERABLE_UE;
8311                         /* Set 1Sec interval to detect UE */
8312                         phba->eratt_poll_interval = 1;
8313                         phba->sli4_hba.ue_to_sr = bf_get(
8314                                         lpfc_mbx_set_feature_UESR,
8315                                         &mboxq->u.mqe.un.set_feature);
8316                         phba->sli4_hba.ue_to_rp = bf_get(
8317                                         lpfc_mbx_set_feature_UERP,
8318                                         &mboxq->u.mqe.un.set_feature);
8319                 }
8320         }
8321
8322         if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
8323                 /* Enable MDS Diagnostics only if the SLI Port supports it */
8324                 lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
8325                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8326                 if (rc != MBX_SUCCESS)
8327                         phba->mds_diags_support = 0;
8328         }
8329
8330         /*
8331          * Discover the port's supported feature set and match it against the
8332          * hosts requests.
8333          */
8334         lpfc_request_features(phba, mboxq);
8335         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8336         if (unlikely(rc)) {
8337                 rc = -EIO;
8338                 goto out_free_mbox;
8339         }
8340
8341         /* Disable VMID if app header is not supported */
8342         if (phba->cfg_vmid_app_header && !(bf_get(lpfc_mbx_rq_ftr_rsp_ashdr,
8343                                                   &mqe->un.req_ftrs))) {
8344                 bf_set(lpfc_ftr_ashdr, &phba->sli4_hba.sli4_flags, 0);
8345                 phba->cfg_vmid_app_header = 0;
8346                 lpfc_printf_log(phba, KERN_DEBUG, LOG_SLI,
8347                                 "1242 vmid feature not supported\n");
8348         }
8349
8350         /*
8351          * The port must support FCP initiator mode as this is the
8352          * only mode running in the host.
8353          */
8354         if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
8355                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8356                                 "0378 No support for fcpi mode.\n");
8357                 ftr_rsp++;
8358         }
8359
8360         /* Performance Hints are ONLY for FCoE */
8361         if (phba->hba_flag & HBA_FCOE_MODE) {
8362                 if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
8363                         phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
8364                 else
8365                         phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
8366         }
8367
8368         /*
8369          * If the port cannot support the host's requested features
8370          * then turn off the global config parameters to disable the
8371          * feature in the driver.  This is not a fatal error.
8372          */
8373         if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8374                 if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
8375                         phba->cfg_enable_bg = 0;
8376                         phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
8377                         ftr_rsp++;
8378                 }
8379         }
8380
8381         if (phba->max_vpi && phba->cfg_enable_npiv &&
8382             !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8383                 ftr_rsp++;
8384
8385         if (ftr_rsp) {
8386                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8387                                 "0379 Feature Mismatch Data: x%08x %08x "
8388                                 "x%x x%x x%x\n", mqe->un.req_ftrs.word2,
8389                                 mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
8390                                 phba->cfg_enable_npiv, phba->max_vpi);
8391                 if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
8392                         phba->cfg_enable_bg = 0;
8393                 if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8394                         phba->cfg_enable_npiv = 0;
8395         }
8396
8397         /* These SLI3 features are assumed in SLI4 */
8398         spin_lock_irq(&phba->hbalock);
8399         phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
8400         spin_unlock_irq(&phba->hbalock);
8401
8402         /* Always try to enable dual dump feature if we can */
8403         lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
8404         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8405         dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
8406         if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
8407                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8408                                 "6448 Dual Dump is enabled\n");
8409         else
8410                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
8411                                 "6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
8412                                 "rc:x%x dd:x%x\n",
8413                                 bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8414                                 lpfc_sli_config_mbox_subsys_get(
8415                                         phba, mboxq),
8416                                 lpfc_sli_config_mbox_opcode_get(
8417                                         phba, mboxq),
8418                                 rc, dd);
8419         /*
8420          * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
8421          * calls depends on these resources to complete port setup.
8422          */
8423         rc = lpfc_sli4_alloc_resource_identifiers(phba);
8424         if (rc) {
8425                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8426                                 "2920 Failed to alloc Resource IDs "
8427                                 "rc = x%x\n", rc);
8428                 goto out_free_mbox;
8429         }
8430
8431         lpfc_set_host_data(phba, mboxq);
8432
8433         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8434         if (rc) {
8435                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8436                                 "2134 Failed to set host os driver version %x",
8437                                 rc);
8438         }
8439
8440         /* Read the port's service parameters. */
8441         rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
8442         if (rc) {
8443                 phba->link_state = LPFC_HBA_ERROR;
8444                 rc = -ENOMEM;
8445                 goto out_free_mbox;
8446         }
8447
8448         mboxq->vport = vport;
8449         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8450         mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
8451         if (rc == MBX_SUCCESS) {
8452                 memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
8453                 rc = 0;
8454         }
8455
8456         /*
8457          * This memory was allocated by the lpfc_read_sparam routine. Release
8458          * it to the mbuf pool.
8459          */
8460         lpfc_mbuf_free(phba, mp->virt, mp->phys);
8461         kfree(mp);
8462         mboxq->ctx_buf = NULL;
8463         if (unlikely(rc)) {
8464                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8465                                 "0382 READ_SPARAM command failed "
8466                                 "status %d, mbxStatus x%x\n",
8467                                 rc, bf_get(lpfc_mqe_status, mqe));
8468                 phba->link_state = LPFC_HBA_ERROR;
8469                 rc = -EIO;
8470                 goto out_free_mbox;
8471         }
8472
8473         lpfc_update_vport_wwn(vport);
8474
8475         /* Update the fc_host data structures with new wwn. */
8476         fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
8477         fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
8478
8479         /* Create all the SLI4 queues */
8480         rc = lpfc_sli4_queue_create(phba);
8481         if (rc) {
8482                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8483                                 "3089 Failed to allocate queues\n");
8484                 rc = -ENODEV;
8485                 goto out_free_mbox;
8486         }
8487         /* Set up all the queues to the device */
8488         rc = lpfc_sli4_queue_setup(phba);
8489         if (unlikely(rc)) {
8490                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8491                                 "0381 Error %d during queue setup.\n ", rc);
8492                 goto out_stop_timers;
8493         }
8494         /* Initialize the driver internal SLI layer lists. */
8495         lpfc_sli4_setup(phba);
8496         lpfc_sli4_queue_init(phba);
8497
8498         /* update host els xri-sgl sizes and mappings */
8499         rc = lpfc_sli4_els_sgl_update(phba);
8500         if (unlikely(rc)) {
8501                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8502                                 "1400 Failed to update xri-sgl size and "
8503                                 "mapping: %d\n", rc);
8504                 goto out_destroy_queue;
8505         }
8506
8507         /* register the els sgl pool to the port */
8508         rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
8509                                        phba->sli4_hba.els_xri_cnt);
8510         if (unlikely(rc < 0)) {
8511                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8512                                 "0582 Error %d during els sgl post "
8513                                 "operation\n", rc);
8514                 rc = -ENODEV;
8515                 goto out_destroy_queue;
8516         }
8517         phba->sli4_hba.els_xri_cnt = rc;
8518
8519         if (phba->nvmet_support) {
8520                 /* update host nvmet xri-sgl sizes and mappings */
8521                 rc = lpfc_sli4_nvmet_sgl_update(phba);
8522                 if (unlikely(rc)) {
8523                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8524                                         "6308 Failed to update nvmet-sgl size "
8525                                         "and mapping: %d\n", rc);
8526                         goto out_destroy_queue;
8527                 }
8528
8529                 /* register the nvmet sgl pool to the port */
8530                 rc = lpfc_sli4_repost_sgl_list(
8531                         phba,
8532                         &phba->sli4_hba.lpfc_nvmet_sgl_list,
8533                         phba->sli4_hba.nvmet_xri_cnt);
8534                 if (unlikely(rc < 0)) {
8535                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8536                                         "3117 Error %d during nvmet "
8537                                         "sgl post\n", rc);
8538                         rc = -ENODEV;
8539                         goto out_destroy_queue;
8540                 }
8541                 phba->sli4_hba.nvmet_xri_cnt = rc;
8542
8543                 /* We allocate an iocbq for every receive context SGL.
8544                  * The additional allocation is for abort and ls handling.
8545                  */
8546                 cnt = phba->sli4_hba.nvmet_xri_cnt +
8547                         phba->sli4_hba.max_cfg_param.max_xri;
8548         } else {
8549                 /* update host common xri-sgl sizes and mappings */
8550                 rc = lpfc_sli4_io_sgl_update(phba);
8551                 if (unlikely(rc)) {
8552                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8553                                         "6082 Failed to update nvme-sgl size "
8554                                         "and mapping: %d\n", rc);
8555                         goto out_destroy_queue;
8556                 }
8557
8558                 /* register the allocated common sgl pool to the port */
8559                 rc = lpfc_sli4_repost_io_sgl_list(phba);
8560                 if (unlikely(rc)) {
8561                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8562                                         "6116 Error %d during nvme sgl post "
8563                                         "operation\n", rc);
8564                         /* Some NVME buffers were moved to abort nvme list */
8565                         /* A pci function reset will repost them */
8566                         rc = -ENODEV;
8567                         goto out_destroy_queue;
8568                 }
8569                 /* Each lpfc_io_buf job structure has an iocbq element.
8570                  * This cnt provides for abort, els, ct and ls requests.
8571                  */
8572                 cnt = phba->sli4_hba.max_cfg_param.max_xri;
8573         }
8574
8575         if (!phba->sli.iocbq_lookup) {
8576                 /* Initialize and populate the iocb list per host */
8577                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8578                                 "2821 initialize iocb list with %d entries\n",
8579                                 cnt);
8580                 rc = lpfc_init_iocb_list(phba, cnt);
8581                 if (rc) {
8582                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8583                                         "1413 Failed to init iocb list.\n");
8584                         goto out_destroy_queue;
8585                 }
8586         }
8587
8588         if (phba->nvmet_support)
8589                 lpfc_nvmet_create_targetport(phba);
8590
8591         if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
8592                 /* Post initial buffers to all RQs created */
8593                 for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
8594                         rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
8595                         INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
8596                         rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
8597                         rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
8598                         rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
8599                         rqbp->buffer_count = 0;
8600
8601                         lpfc_post_rq_buffer(
8602                                 phba, phba->sli4_hba.nvmet_mrq_hdr[i],
8603                                 phba->sli4_hba.nvmet_mrq_data[i],
8604                                 phba->cfg_nvmet_mrq_post, i);
8605                 }
8606         }
8607
8608         /* Post the rpi header region to the device. */
8609         rc = lpfc_sli4_post_all_rpi_hdrs(phba);
8610         if (unlikely(rc)) {
8611                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8612                                 "0393 Error %d during rpi post operation\n",
8613                                 rc);
8614                 rc = -ENODEV;
8615                 goto out_free_iocblist;
8616         }
8617         lpfc_sli4_node_prep(phba);
8618
8619         if (!(phba->hba_flag & HBA_FCOE_MODE)) {
8620                 if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
8621                         /*
8622                          * The FC Port needs to register FCFI (index 0)
8623                          */
8624                         lpfc_reg_fcfi(phba, mboxq);
8625                         mboxq->vport = phba->pport;
8626                         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8627                         if (rc != MBX_SUCCESS)
8628                                 goto out_unset_queue;
8629                         rc = 0;
8630                         phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
8631                                                 &mboxq->u.mqe.un.reg_fcfi);
8632                 } else {
8633                         /* We are a NVME Target mode with MRQ > 1 */
8634
8635                         /* First register the FCFI */
8636                         lpfc_reg_fcfi_mrq(phba, mboxq, 0);
8637                         mboxq->vport = phba->pport;
8638                         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8639                         if (rc != MBX_SUCCESS)
8640                                 goto out_unset_queue;
8641                         rc = 0;
8642                         phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
8643                                                 &mboxq->u.mqe.un.reg_fcfi_mrq);
8644
8645                         /* Next register the MRQs */
8646                         lpfc_reg_fcfi_mrq(phba, mboxq, 1);
8647                         mboxq->vport = phba->pport;
8648                         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8649                         if (rc != MBX_SUCCESS)
8650                                 goto out_unset_queue;
8651                         rc = 0;
8652                 }
8653                 /* Check if the port is configured to be disabled */
8654                 lpfc_sli_read_link_ste(phba);
8655         }
8656
8657         /* Don't post more new bufs if repost already recovered
8658          * the nvme sgls.
8659          */
8660         if (phba->nvmet_support == 0) {
8661                 if (phba->sli4_hba.io_xri_cnt == 0) {
8662                         len = lpfc_new_io_buf(
8663                                               phba, phba->sli4_hba.io_xri_max);
8664                         if (len == 0) {
8665                                 rc = -ENOMEM;
8666                                 goto out_unset_queue;
8667                         }
8668
8669                         if (phba->cfg_xri_rebalancing)
8670                                 lpfc_create_multixri_pools(phba);
8671                 }
8672         } else {
8673                 phba->cfg_xri_rebalancing = 0;
8674         }
8675
8676         /* Allow asynchronous mailbox command to go through */
8677         spin_lock_irq(&phba->hbalock);
8678         phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
8679         spin_unlock_irq(&phba->hbalock);
8680
8681         /* Post receive buffers to the device */
8682         lpfc_sli4_rb_setup(phba);
8683
8684         /* Reset HBA FCF states after HBA reset */
8685         phba->fcf.fcf_flag = 0;
8686         phba->fcf.current_rec.flag = 0;
8687
8688         /* Start the ELS watchdog timer */
8689         mod_timer(&vport->els_tmofunc,
8690                   jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
8691
8692         /* Start heart beat timer */
8693         mod_timer(&phba->hb_tmofunc,
8694                   jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
8695         phba->hba_flag &= ~(HBA_HBEAT_INP | HBA_HBEAT_TMO);
8696         phba->last_completion_time = jiffies;
8697
8698         /* start eq_delay heartbeat */
8699         if (phba->cfg_auto_imax)
8700                 queue_delayed_work(phba->wq, &phba->eq_delay_work,
8701                                    msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
8702
8703         /* start per phba idle_stat_delay heartbeat */
8704         lpfc_init_idle_stat_hb(phba);
8705
8706         /* Start error attention (ERATT) polling timer */
8707         mod_timer(&phba->eratt_poll,
8708                   jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
8709
8710         /* Enable PCIe device Advanced Error Reporting (AER) if configured */
8711         if (phba->cfg_aer_support == 1 && !(phba->hba_flag & HBA_AER_ENABLED)) {
8712                 rc = pci_enable_pcie_error_reporting(phba->pcidev);
8713                 if (!rc) {
8714                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8715                                         "2829 This device supports "
8716                                         "Advanced Error Reporting (AER)\n");
8717                         spin_lock_irq(&phba->hbalock);
8718                         phba->hba_flag |= HBA_AER_ENABLED;
8719                         spin_unlock_irq(&phba->hbalock);
8720                 } else {
8721                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8722                                         "2830 This device does not support "
8723                                         "Advanced Error Reporting (AER)\n");
8724                         phba->cfg_aer_support = 0;
8725                 }
8726                 rc = 0;
8727         }
8728
8729         /*
8730          * The port is ready, set the host's link state to LINK_DOWN
8731          * in preparation for link interrupts.
8732          */
8733         spin_lock_irq(&phba->hbalock);
8734         phba->link_state = LPFC_LINK_DOWN;
8735
8736         /* Check if physical ports are trunked */
8737         if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
8738                 phba->trunk_link.link0.state = LPFC_LINK_DOWN;
8739         if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
8740                 phba->trunk_link.link1.state = LPFC_LINK_DOWN;
8741         if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
8742                 phba->trunk_link.link2.state = LPFC_LINK_DOWN;
8743         if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
8744                 phba->trunk_link.link3.state = LPFC_LINK_DOWN;
8745         spin_unlock_irq(&phba->hbalock);
8746
8747         /* Arm the CQs and then EQs on device */
8748         lpfc_sli4_arm_cqeq_intr(phba);
8749
8750         /* Indicate device interrupt mode */
8751         phba->sli4_hba.intr_enable = 1;
8752
8753         /* Setup CMF after HBA is initialized */
8754         lpfc_cmf_setup(phba);
8755
8756         if (!(phba->hba_flag & HBA_FCOE_MODE) &&
8757             (phba->hba_flag & LINK_DISABLED)) {
8758                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8759                                 "3103 Adapter Link is disabled.\n");
8760                 lpfc_down_link(phba, mboxq);
8761                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8762                 if (rc != MBX_SUCCESS) {
8763                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8764                                         "3104 Adapter failed to issue "
8765                                         "DOWN_LINK mbox cmd, rc:x%x\n", rc);
8766                         goto out_io_buff_free;
8767                 }
8768         } else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
8769                 /* don't perform init_link on SLI4 FC port loopback test */
8770                 if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
8771                         rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
8772                         if (rc)
8773                                 goto out_io_buff_free;
8774                 }
8775         }
8776         mempool_free(mboxq, phba->mbox_mem_pool);
8777
8778         phba->hba_flag |= HBA_SETUP;
8779         return rc;
8780
8781 out_io_buff_free:
8782         /* Free allocated IO Buffers */
8783         lpfc_io_free(phba);
8784 out_unset_queue:
8785         /* Unset all the queues set up in this routine when error out */
8786         lpfc_sli4_queue_unset(phba);
8787 out_free_iocblist:
8788         lpfc_free_iocb_list(phba);
8789 out_destroy_queue:
8790         lpfc_sli4_queue_destroy(phba);
8791 out_stop_timers:
8792         lpfc_stop_hba_timers(phba);
8793 out_free_mbox:
8794         mempool_free(mboxq, phba->mbox_mem_pool);
8795         return rc;
8796 }
8797
8798 /**
8799  * lpfc_mbox_timeout - Timeout call back function for mbox timer
8800  * @t: Context to fetch pointer to hba structure from.
8801  *
8802  * This is the callback function for mailbox timer. The mailbox
8803  * timer is armed when a new mailbox command is issued and the timer
8804  * is deleted when the mailbox complete. The function is called by
8805  * the kernel timer code when a mailbox does not complete within
8806  * expected time. This function wakes up the worker thread to
8807  * process the mailbox timeout and returns. All the processing is
8808  * done by the worker thread function lpfc_mbox_timeout_handler.
8809  **/
8810 void
8811 lpfc_mbox_timeout(struct timer_list *t)
8812 {
8813         struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
8814         unsigned long iflag;
8815         uint32_t tmo_posted;
8816
8817         spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
8818         tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
8819         if (!tmo_posted)
8820                 phba->pport->work_port_events |= WORKER_MBOX_TMO;
8821         spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
8822
8823         if (!tmo_posted)
8824                 lpfc_worker_wake_up(phba);
8825         return;
8826 }
8827
8828 /**
8829  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
8830  *                                    are pending
8831  * @phba: Pointer to HBA context object.
8832  *
8833  * This function checks if any mailbox completions are present on the mailbox
8834  * completion queue.
8835  **/
8836 static bool
8837 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
8838 {
8839
8840         uint32_t idx;
8841         struct lpfc_queue *mcq;
8842         struct lpfc_mcqe *mcqe;
8843         bool pending_completions = false;
8844         uint8_t qe_valid;
8845
8846         if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8847                 return false;
8848
8849         /* Check for completions on mailbox completion queue */
8850
8851         mcq = phba->sli4_hba.mbx_cq;
8852         idx = mcq->hba_index;
8853         qe_valid = mcq->qe_valid;
8854         while (bf_get_le32(lpfc_cqe_valid,
8855                (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
8856                 mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
8857                 if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
8858                     (!bf_get_le32(lpfc_trailer_async, mcqe))) {
8859                         pending_completions = true;
8860                         break;
8861                 }
8862                 idx = (idx + 1) % mcq->entry_count;
8863                 if (mcq->hba_index == idx)
8864                         break;
8865
8866                 /* if the index wrapped around, toggle the valid bit */
8867                 if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
8868                         qe_valid = (qe_valid) ? 0 : 1;
8869         }
8870         return pending_completions;
8871
8872 }
8873
8874 /**
8875  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
8876  *                                            that were missed.
8877  * @phba: Pointer to HBA context object.
8878  *
8879  * For sli4, it is possible to miss an interrupt. As such mbox completions
8880  * maybe missed causing erroneous mailbox timeouts to occur. This function
8881  * checks to see if mbox completions are on the mailbox completion queue
8882  * and will process all the completions associated with the eq for the
8883  * mailbox completion queue.
8884  **/
8885 static bool
8886 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
8887 {
8888         struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
8889         uint32_t eqidx;
8890         struct lpfc_queue *fpeq = NULL;
8891         struct lpfc_queue *eq;
8892         bool mbox_pending;
8893
8894         if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
8895                 return false;
8896
8897         /* Find the EQ associated with the mbox CQ */
8898         if (sli4_hba->hdwq) {
8899                 for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
8900                         eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
8901                         if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
8902                                 fpeq = eq;
8903                                 break;
8904                         }
8905                 }
8906         }
8907         if (!fpeq)
8908                 return false;
8909
8910         /* Turn off interrupts from this EQ */
8911
8912         sli4_hba->sli4_eq_clr_intr(fpeq);
8913
8914         /* Check to see if a mbox completion is pending */
8915
8916         mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
8917
8918         /*
8919          * If a mbox completion is pending, process all the events on EQ
8920          * associated with the mbox completion queue (this could include
8921          * mailbox commands, async events, els commands, receive queue data
8922          * and fcp commands)
8923          */
8924
8925         if (mbox_pending)
8926                 /* process and rearm the EQ */
8927                 lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
8928         else
8929                 /* Always clear and re-arm the EQ */
8930                 sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
8931
8932         return mbox_pending;
8933
8934 }
8935
8936 /**
8937  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
8938  * @phba: Pointer to HBA context object.
8939  *
8940  * This function is called from worker thread when a mailbox command times out.
8941  * The caller is not required to hold any locks. This function will reset the
8942  * HBA and recover all the pending commands.
8943  **/
8944 void
8945 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
8946 {
8947         LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
8948         MAILBOX_t *mb = NULL;
8949
8950         struct lpfc_sli *psli = &phba->sli;
8951
8952         /* If the mailbox completed, process the completion */
8953         lpfc_sli4_process_missed_mbox_completions(phba);
8954
8955         if (!(psli->sli_flag & LPFC_SLI_ACTIVE))
8956                 return;
8957
8958         if (pmbox != NULL)
8959                 mb = &pmbox->u.mb;
8960         /* Check the pmbox pointer first.  There is a race condition
8961          * between the mbox timeout handler getting executed in the
8962          * worklist and the mailbox actually completing. When this
8963          * race condition occurs, the mbox_active will be NULL.
8964          */
8965         spin_lock_irq(&phba->hbalock);
8966         if (pmbox == NULL) {
8967                 lpfc_printf_log(phba, KERN_WARNING,
8968                                 LOG_MBOX | LOG_SLI,
8969                                 "0353 Active Mailbox cleared - mailbox timeout "
8970                                 "exiting\n");
8971                 spin_unlock_irq(&phba->hbalock);
8972                 return;
8973         }
8974
8975         /* Mbox cmd <mbxCommand> timeout */
8976         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8977                         "0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
8978                         mb->mbxCommand,
8979                         phba->pport->port_state,
8980                         phba->sli.sli_flag,
8981                         phba->sli.mbox_active);
8982         spin_unlock_irq(&phba->hbalock);
8983
8984         /* Setting state unknown so lpfc_sli_abort_iocb_ring
8985          * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
8986          * it to fail all outstanding SCSI IO.
8987          */
8988         spin_lock_irq(&phba->pport->work_port_lock);
8989         phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
8990         spin_unlock_irq(&phba->pport->work_port_lock);
8991         spin_lock_irq(&phba->hbalock);
8992         phba->link_state = LPFC_LINK_UNKNOWN;
8993         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
8994         spin_unlock_irq(&phba->hbalock);
8995
8996         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8997                         "0345 Resetting board due to mailbox timeout\n");
8998
8999         /* Reset the HBA device */
9000         lpfc_reset_hba(phba);
9001 }
9002
9003 /**
9004  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
9005  * @phba: Pointer to HBA context object.
9006  * @pmbox: Pointer to mailbox object.
9007  * @flag: Flag indicating how the mailbox need to be processed.
9008  *
9009  * This function is called by discovery code and HBA management code
9010  * to submit a mailbox command to firmware with SLI-3 interface spec. This
9011  * function gets the hbalock to protect the data structures.
9012  * The mailbox command can be submitted in polling mode, in which case
9013  * this function will wait in a polling loop for the completion of the
9014  * mailbox.
9015  * If the mailbox is submitted in no_wait mode (not polling) the
9016  * function will submit the command and returns immediately without waiting
9017  * for the mailbox completion. The no_wait is supported only when HBA
9018  * is in SLI2/SLI3 mode - interrupts are enabled.
9019  * The SLI interface allows only one mailbox pending at a time. If the
9020  * mailbox is issued in polling mode and there is already a mailbox
9021  * pending, then the function will return an error. If the mailbox is issued
9022  * in NO_WAIT mode and there is a mailbox pending already, the function
9023  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
9024  * The sli layer owns the mailbox object until the completion of mailbox
9025  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
9026  * return codes the caller owns the mailbox command after the return of
9027  * the function.
9028  **/
9029 static int
9030 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
9031                        uint32_t flag)
9032 {
9033         MAILBOX_t *mbx;
9034         struct lpfc_sli *psli = &phba->sli;
9035         uint32_t status, evtctr;
9036         uint32_t ha_copy, hc_copy;
9037         int i;
9038         unsigned long timeout;
9039         unsigned long drvr_flag = 0;
9040         uint32_t word0, ldata;
9041         void __iomem *to_slim;
9042         int processing_queue = 0;
9043
9044         spin_lock_irqsave(&phba->hbalock, drvr_flag);
9045         if (!pmbox) {
9046                 phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9047                 /* processing mbox queue from intr_handler */
9048                 if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9049                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9050                         return MBX_SUCCESS;
9051                 }
9052                 processing_queue = 1;
9053                 pmbox = lpfc_mbox_get(phba);
9054                 if (!pmbox) {
9055                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9056                         return MBX_SUCCESS;
9057                 }
9058         }
9059
9060         if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
9061                 pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
9062                 if(!pmbox->vport) {
9063                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9064                         lpfc_printf_log(phba, KERN_ERR,
9065                                         LOG_MBOX | LOG_VPORT,
9066                                         "1806 Mbox x%x failed. No vport\n",
9067                                         pmbox->u.mb.mbxCommand);
9068                         dump_stack();
9069                         goto out_not_finished;
9070                 }
9071         }
9072
9073         /* If the PCI channel is in offline state, do not post mbox. */
9074         if (unlikely(pci_channel_offline(phba->pcidev))) {
9075                 spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9076                 goto out_not_finished;
9077         }
9078
9079         /* If HBA has a deferred error attention, fail the iocb. */
9080         if (unlikely(phba->hba_flag & DEFER_ERATT)) {
9081                 spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9082                 goto out_not_finished;
9083         }
9084
9085         psli = &phba->sli;
9086
9087         mbx = &pmbox->u.mb;
9088         status = MBX_SUCCESS;
9089
9090         if (phba->link_state == LPFC_HBA_ERROR) {
9091                 spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9092
9093                 /* Mbox command <mbxCommand> cannot issue */
9094                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9095                                 "(%d):0311 Mailbox command x%x cannot "
9096                                 "issue Data: x%x x%x\n",
9097                                 pmbox->vport ? pmbox->vport->vpi : 0,
9098                                 pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9099                 goto out_not_finished;
9100         }
9101
9102         if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
9103                 if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
9104                         !(hc_copy & HC_MBINT_ENA)) {
9105                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9106                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9107                                 "(%d):2528 Mailbox command x%x cannot "
9108                                 "issue Data: x%x x%x\n",
9109                                 pmbox->vport ? pmbox->vport->vpi : 0,
9110                                 pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9111                         goto out_not_finished;
9112                 }
9113         }
9114
9115         if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9116                 /* Polling for a mbox command when another one is already active
9117                  * is not allowed in SLI. Also, the driver must have established
9118                  * SLI2 mode to queue and process multiple mbox commands.
9119                  */
9120
9121                 if (flag & MBX_POLL) {
9122                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9123
9124                         /* Mbox command <mbxCommand> cannot issue */
9125                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9126                                         "(%d):2529 Mailbox command x%x "
9127                                         "cannot issue Data: x%x x%x\n",
9128                                         pmbox->vport ? pmbox->vport->vpi : 0,
9129                                         pmbox->u.mb.mbxCommand,
9130                                         psli->sli_flag, flag);
9131                         goto out_not_finished;
9132                 }
9133
9134                 if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
9135                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9136                         /* Mbox command <mbxCommand> cannot issue */
9137                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9138                                         "(%d):2530 Mailbox command x%x "
9139                                         "cannot issue Data: x%x x%x\n",
9140                                         pmbox->vport ? pmbox->vport->vpi : 0,
9141                                         pmbox->u.mb.mbxCommand,
9142                                         psli->sli_flag, flag);
9143                         goto out_not_finished;
9144                 }
9145
9146                 /* Another mailbox command is still being processed, queue this
9147                  * command to be processed later.
9148                  */
9149                 lpfc_mbox_put(phba, pmbox);
9150
9151                 /* Mbox cmd issue - BUSY */
9152                 lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9153                                 "(%d):0308 Mbox cmd issue - BUSY Data: "
9154                                 "x%x x%x x%x x%x\n",
9155                                 pmbox->vport ? pmbox->vport->vpi : 0xffffff,
9156                                 mbx->mbxCommand,
9157                                 phba->pport ? phba->pport->port_state : 0xff,
9158                                 psli->sli_flag, flag);
9159
9160                 psli->slistat.mbox_busy++;
9161                 spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9162
9163                 if (pmbox->vport) {
9164                         lpfc_debugfs_disc_trc(pmbox->vport,
9165                                 LPFC_DISC_TRC_MBOX_VPORT,
9166                                 "MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
9167                                 (uint32_t)mbx->mbxCommand,
9168                                 mbx->un.varWords[0], mbx->un.varWords[1]);
9169                 }
9170                 else {
9171                         lpfc_debugfs_disc_trc(phba->pport,
9172                                 LPFC_DISC_TRC_MBOX,
9173                                 "MBOX Bsy:        cmd:x%x mb:x%x x%x",
9174                                 (uint32_t)mbx->mbxCommand,
9175                                 mbx->un.varWords[0], mbx->un.varWords[1]);
9176                 }
9177
9178                 return MBX_BUSY;
9179         }
9180
9181         psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9182
9183         /* If we are not polling, we MUST be in SLI2 mode */
9184         if (flag != MBX_POLL) {
9185                 if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
9186                     (mbx->mbxCommand != MBX_KILL_BOARD)) {
9187                         psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9188                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9189                         /* Mbox command <mbxCommand> cannot issue */
9190                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9191                                         "(%d):2531 Mailbox command x%x "
9192                                         "cannot issue Data: x%x x%x\n",
9193                                         pmbox->vport ? pmbox->vport->vpi : 0,
9194                                         pmbox->u.mb.mbxCommand,
9195                                         psli->sli_flag, flag);
9196                         goto out_not_finished;
9197                 }
9198                 /* timeout active mbox command */
9199                 timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9200                                            1000);
9201                 mod_timer(&psli->mbox_tmo, jiffies + timeout);
9202         }
9203
9204         /* Mailbox cmd <cmd> issue */
9205         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9206                         "(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
9207                         "x%x\n",
9208                         pmbox->vport ? pmbox->vport->vpi : 0,
9209                         mbx->mbxCommand,
9210                         phba->pport ? phba->pport->port_state : 0xff,
9211                         psli->sli_flag, flag);
9212
9213         if (mbx->mbxCommand != MBX_HEARTBEAT) {
9214                 if (pmbox->vport) {
9215                         lpfc_debugfs_disc_trc(pmbox->vport,
9216                                 LPFC_DISC_TRC_MBOX_VPORT,
9217                                 "MBOX Send vport: cmd:x%x mb:x%x x%x",
9218                                 (uint32_t)mbx->mbxCommand,
9219                                 mbx->un.varWords[0], mbx->un.varWords[1]);
9220                 }
9221                 else {
9222                         lpfc_debugfs_disc_trc(phba->pport,
9223                                 LPFC_DISC_TRC_MBOX,
9224                                 "MBOX Send:       cmd:x%x mb:x%x x%x",
9225                                 (uint32_t)mbx->mbxCommand,
9226                                 mbx->un.varWords[0], mbx->un.varWords[1]);
9227                 }
9228         }
9229
9230         psli->slistat.mbox_cmd++;
9231         evtctr = psli->slistat.mbox_event;
9232
9233         /* next set own bit for the adapter and copy over command word */
9234         mbx->mbxOwner = OWN_CHIP;
9235
9236         if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9237                 /* Populate mbox extension offset word. */
9238                 if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
9239                         *(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9240                                 = (uint8_t *)phba->mbox_ext
9241                                   - (uint8_t *)phba->mbox;
9242                 }
9243
9244                 /* Copy the mailbox extension data */
9245                 if (pmbox->in_ext_byte_len && pmbox->ctx_buf) {
9246                         lpfc_sli_pcimem_bcopy(pmbox->ctx_buf,
9247                                               (uint8_t *)phba->mbox_ext,
9248                                               pmbox->in_ext_byte_len);
9249                 }
9250                 /* Copy command data to host SLIM area */
9251                 lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
9252         } else {
9253                 /* Populate mbox extension offset word. */
9254                 if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
9255                         *(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9256                                 = MAILBOX_HBA_EXT_OFFSET;
9257
9258                 /* Copy the mailbox extension data */
9259                 if (pmbox->in_ext_byte_len && pmbox->ctx_buf)
9260                         lpfc_memcpy_to_slim(phba->MBslimaddr +
9261                                 MAILBOX_HBA_EXT_OFFSET,
9262                                 pmbox->ctx_buf, pmbox->in_ext_byte_len);
9263
9264                 if (mbx->mbxCommand == MBX_CONFIG_PORT)
9265                         /* copy command data into host mbox for cmpl */
9266                         lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
9267                                               MAILBOX_CMD_SIZE);
9268
9269                 /* First copy mbox command data to HBA SLIM, skip past first
9270                    word */
9271                 to_slim = phba->MBslimaddr + sizeof (uint32_t);
9272                 lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
9273                             MAILBOX_CMD_SIZE - sizeof (uint32_t));
9274
9275                 /* Next copy over first word, with mbxOwner set */
9276                 ldata = *((uint32_t *)mbx);
9277                 to_slim = phba->MBslimaddr;
9278                 writel(ldata, to_slim);
9279                 readl(to_slim); /* flush */
9280
9281                 if (mbx->mbxCommand == MBX_CONFIG_PORT)
9282                         /* switch over to host mailbox */
9283                         psli->sli_flag |= LPFC_SLI_ACTIVE;
9284         }
9285
9286         wmb();
9287
9288         switch (flag) {
9289         case MBX_NOWAIT:
9290                 /* Set up reference to mailbox command */
9291                 psli->mbox_active = pmbox;
9292                 /* Interrupt board to do it */
9293                 writel(CA_MBATT, phba->CAregaddr);
9294                 readl(phba->CAregaddr); /* flush */
9295                 /* Don't wait for it to finish, just return */
9296                 break;
9297
9298         case MBX_POLL:
9299                 /* Set up null reference to mailbox command */
9300                 psli->mbox_active = NULL;
9301                 /* Interrupt board to do it */
9302                 writel(CA_MBATT, phba->CAregaddr);
9303                 readl(phba->CAregaddr); /* flush */
9304
9305                 if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9306                         /* First read mbox status word */
9307                         word0 = *((uint32_t *)phba->mbox);
9308                         word0 = le32_to_cpu(word0);
9309                 } else {
9310                         /* First read mbox status word */
9311                         if (lpfc_readl(phba->MBslimaddr, &word0)) {
9312                                 spin_unlock_irqrestore(&phba->hbalock,
9313                                                        drvr_flag);
9314                                 goto out_not_finished;
9315                         }
9316                 }
9317
9318                 /* Read the HBA Host Attention Register */
9319                 if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9320                         spin_unlock_irqrestore(&phba->hbalock,
9321                                                        drvr_flag);
9322                         goto out_not_finished;
9323                 }
9324                 timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9325                                                         1000) + jiffies;
9326                 i = 0;
9327                 /* Wait for command to complete */
9328                 while (((word0 & OWN_CHIP) == OWN_CHIP) ||
9329                        (!(ha_copy & HA_MBATT) &&
9330                         (phba->link_state > LPFC_WARM_START))) {
9331                         if (time_after(jiffies, timeout)) {
9332                                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9333                                 spin_unlock_irqrestore(&phba->hbalock,
9334                                                        drvr_flag);
9335                                 goto out_not_finished;
9336                         }
9337
9338                         /* Check if we took a mbox interrupt while we were
9339                            polling */
9340                         if (((word0 & OWN_CHIP) != OWN_CHIP)
9341                             && (evtctr != psli->slistat.mbox_event))
9342                                 break;
9343
9344                         if (i++ > 10) {
9345                                 spin_unlock_irqrestore(&phba->hbalock,
9346                                                        drvr_flag);
9347                                 msleep(1);
9348                                 spin_lock_irqsave(&phba->hbalock, drvr_flag);
9349                         }
9350
9351                         if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9352                                 /* First copy command data */
9353                                 word0 = *((uint32_t *)phba->mbox);
9354                                 word0 = le32_to_cpu(word0);
9355                                 if (mbx->mbxCommand == MBX_CONFIG_PORT) {
9356                                         MAILBOX_t *slimmb;
9357                                         uint32_t slimword0;
9358                                         /* Check real SLIM for any errors */
9359                                         slimword0 = readl(phba->MBslimaddr);
9360                                         slimmb = (MAILBOX_t *) & slimword0;
9361                                         if (((slimword0 & OWN_CHIP) != OWN_CHIP)
9362                                             && slimmb->mbxStatus) {
9363                                                 psli->sli_flag &=
9364                                                     ~LPFC_SLI_ACTIVE;
9365                                                 word0 = slimword0;
9366                                         }
9367                                 }
9368                         } else {
9369                                 /* First copy command data */
9370                                 word0 = readl(phba->MBslimaddr);
9371                         }
9372                         /* Read the HBA Host Attention Register */
9373                         if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9374                                 spin_unlock_irqrestore(&phba->hbalock,
9375                                                        drvr_flag);
9376                                 goto out_not_finished;
9377                         }
9378                 }
9379
9380                 if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9381                         /* copy results back to user */
9382                         lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
9383                                                 MAILBOX_CMD_SIZE);
9384                         /* Copy the mailbox extension data */
9385                         if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
9386                                 lpfc_sli_pcimem_bcopy(phba->mbox_ext,
9387                                                       pmbox->ctx_buf,
9388                                                       pmbox->out_ext_byte_len);
9389                         }
9390                 } else {
9391                         /* First copy command data */
9392                         lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
9393                                                 MAILBOX_CMD_SIZE);
9394                         /* Copy the mailbox extension data */
9395                         if (pmbox->out_ext_byte_len && pmbox->ctx_buf) {
9396                                 lpfc_memcpy_from_slim(
9397                                         pmbox->ctx_buf,
9398                                         phba->MBslimaddr +
9399                                         MAILBOX_HBA_EXT_OFFSET,
9400                                         pmbox->out_ext_byte_len);
9401                         }
9402                 }
9403
9404                 writel(HA_MBATT, phba->HAregaddr);
9405                 readl(phba->HAregaddr); /* flush */
9406
9407                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9408                 status = mbx->mbxStatus;
9409         }
9410
9411         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9412         return status;
9413
9414 out_not_finished:
9415         if (processing_queue) {
9416                 pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
9417                 lpfc_mbox_cmpl_put(phba, pmbox);
9418         }
9419         return MBX_NOT_FINISHED;
9420 }
9421
9422 /**
9423  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
9424  * @phba: Pointer to HBA context object.
9425  *
9426  * The function blocks the posting of SLI4 asynchronous mailbox commands from
9427  * the driver internal pending mailbox queue. It will then try to wait out the
9428  * possible outstanding mailbox command before return.
9429  *
9430  * Returns:
9431  *      0 - the outstanding mailbox command completed; otherwise, the wait for
9432  *      the outstanding mailbox command timed out.
9433  **/
9434 static int
9435 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
9436 {
9437         struct lpfc_sli *psli = &phba->sli;
9438         LPFC_MBOXQ_t *mboxq;
9439         int rc = 0;
9440         unsigned long timeout = 0;
9441         u32 sli_flag;
9442         u8 cmd, subsys, opcode;
9443
9444         /* Mark the asynchronous mailbox command posting as blocked */
9445         spin_lock_irq(&phba->hbalock);
9446         psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
9447         /* Determine how long we might wait for the active mailbox
9448          * command to be gracefully completed by firmware.
9449          */
9450         if (phba->sli.mbox_active)
9451                 timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
9452                                                 phba->sli.mbox_active) *
9453                                                 1000) + jiffies;
9454         spin_unlock_irq(&phba->hbalock);
9455
9456         /* Make sure the mailbox is really active */
9457         if (timeout)
9458                 lpfc_sli4_process_missed_mbox_completions(phba);
9459
9460         /* Wait for the outstanding mailbox command to complete */
9461         while (phba->sli.mbox_active) {
9462                 /* Check active mailbox complete status every 2ms */
9463                 msleep(2);
9464                 if (time_after(jiffies, timeout)) {
9465                         /* Timeout, mark the outstanding cmd not complete */
9466
9467                         /* Sanity check sli.mbox_active has not completed or
9468                          * cancelled from another context during last 2ms sleep,
9469                          * so take hbalock to be sure before logging.
9470                          */
9471                         spin_lock_irq(&phba->hbalock);
9472                         if (phba->sli.mbox_active) {
9473                                 mboxq = phba->sli.mbox_active;
9474                                 cmd = mboxq->u.mb.mbxCommand;
9475                                 subsys = lpfc_sli_config_mbox_subsys_get(phba,
9476                                                                          mboxq);
9477                                 opcode = lpfc_sli_config_mbox_opcode_get(phba,
9478                                                                          mboxq);
9479                                 sli_flag = psli->sli_flag;
9480                                 spin_unlock_irq(&phba->hbalock);
9481                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9482                                                 "2352 Mailbox command x%x "
9483                                                 "(x%x/x%x) sli_flag x%x could "
9484                                                 "not complete\n",
9485                                                 cmd, subsys, opcode,
9486                                                 sli_flag);
9487                         } else {
9488                                 spin_unlock_irq(&phba->hbalock);
9489                         }
9490
9491                         rc = 1;
9492                         break;
9493                 }
9494         }
9495
9496         /* Can not cleanly block async mailbox command, fails it */
9497         if (rc) {
9498                 spin_lock_irq(&phba->hbalock);
9499                 psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9500                 spin_unlock_irq(&phba->hbalock);
9501         }
9502         return rc;
9503 }
9504
9505 /**
9506  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
9507  * @phba: Pointer to HBA context object.
9508  *
9509  * The function unblocks and resume posting of SLI4 asynchronous mailbox
9510  * commands from the driver internal pending mailbox queue. It makes sure
9511  * that there is no outstanding mailbox command before resuming posting
9512  * asynchronous mailbox commands. If, for any reason, there is outstanding
9513  * mailbox command, it will try to wait it out before resuming asynchronous
9514  * mailbox command posting.
9515  **/
9516 static void
9517 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
9518 {
9519         struct lpfc_sli *psli = &phba->sli;
9520
9521         spin_lock_irq(&phba->hbalock);
9522         if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9523                 /* Asynchronous mailbox posting is not blocked, do nothing */
9524                 spin_unlock_irq(&phba->hbalock);
9525                 return;
9526         }
9527
9528         /* Outstanding synchronous mailbox command is guaranteed to be done,
9529          * successful or timeout, after timing-out the outstanding mailbox
9530          * command shall always be removed, so just unblock posting async
9531          * mailbox command and resume
9532          */
9533         psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9534         spin_unlock_irq(&phba->hbalock);
9535
9536         /* wake up worker thread to post asynchronous mailbox command */
9537         lpfc_worker_wake_up(phba);
9538 }
9539
9540 /**
9541  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
9542  * @phba: Pointer to HBA context object.
9543  * @mboxq: Pointer to mailbox object.
9544  *
9545  * The function waits for the bootstrap mailbox register ready bit from
9546  * port for twice the regular mailbox command timeout value.
9547  *
9548  *      0 - no timeout on waiting for bootstrap mailbox register ready.
9549  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out.
9550  **/
9551 static int
9552 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9553 {
9554         uint32_t db_ready;
9555         unsigned long timeout;
9556         struct lpfc_register bmbx_reg;
9557
9558         timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
9559                                    * 1000) + jiffies;
9560
9561         do {
9562                 bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
9563                 db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
9564                 if (!db_ready)
9565                         mdelay(2);
9566
9567                 if (time_after(jiffies, timeout))
9568                         return MBXERR_ERROR;
9569         } while (!db_ready);
9570
9571         return 0;
9572 }
9573
9574 /**
9575  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
9576  * @phba: Pointer to HBA context object.
9577  * @mboxq: Pointer to mailbox object.
9578  *
9579  * The function posts a mailbox to the port.  The mailbox is expected
9580  * to be comletely filled in and ready for the port to operate on it.
9581  * This routine executes a synchronous completion operation on the
9582  * mailbox by polling for its completion.
9583  *
9584  * The caller must not be holding any locks when calling this routine.
9585  *
9586  * Returns:
9587  *      MBX_SUCCESS - mailbox posted successfully
9588  *      Any of the MBX error values.
9589  **/
9590 static int
9591 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9592 {
9593         int rc = MBX_SUCCESS;
9594         unsigned long iflag;
9595         uint32_t mcqe_status;
9596         uint32_t mbx_cmnd;
9597         struct lpfc_sli *psli = &phba->sli;
9598         struct lpfc_mqe *mb = &mboxq->u.mqe;
9599         struct lpfc_bmbx_create *mbox_rgn;
9600         struct dma_address *dma_address;
9601
9602         /*
9603          * Only one mailbox can be active to the bootstrap mailbox region
9604          * at a time and there is no queueing provided.
9605          */
9606         spin_lock_irqsave(&phba->hbalock, iflag);
9607         if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9608                 spin_unlock_irqrestore(&phba->hbalock, iflag);
9609                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9610                                 "(%d):2532 Mailbox command x%x (x%x/x%x) "
9611                                 "cannot issue Data: x%x x%x\n",
9612                                 mboxq->vport ? mboxq->vport->vpi : 0,
9613                                 mboxq->u.mb.mbxCommand,
9614                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9615                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9616                                 psli->sli_flag, MBX_POLL);
9617                 return MBXERR_ERROR;
9618         }
9619         /* The server grabs the token and owns it until release */
9620         psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9621         phba->sli.mbox_active = mboxq;
9622         spin_unlock_irqrestore(&phba->hbalock, iflag);
9623
9624         /* wait for bootstrap mbox register for readyness */
9625         rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9626         if (rc)
9627                 goto exit;
9628         /*
9629          * Initialize the bootstrap memory region to avoid stale data areas
9630          * in the mailbox post.  Then copy the caller's mailbox contents to
9631          * the bmbx mailbox region.
9632          */
9633         mbx_cmnd = bf_get(lpfc_mqe_command, mb);
9634         memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
9635         lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
9636                                sizeof(struct lpfc_mqe));
9637
9638         /* Post the high mailbox dma address to the port and wait for ready. */
9639         dma_address = &phba->sli4_hba.bmbx.dma_address;
9640         writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
9641
9642         /* wait for bootstrap mbox register for hi-address write done */
9643         rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9644         if (rc)
9645                 goto exit;
9646
9647         /* Post the low mailbox dma address to the port. */
9648         writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
9649
9650         /* wait for bootstrap mbox register for low address write done */
9651         rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9652         if (rc)
9653                 goto exit;
9654
9655         /*
9656          * Read the CQ to ensure the mailbox has completed.
9657          * If so, update the mailbox status so that the upper layers
9658          * can complete the request normally.
9659          */
9660         lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
9661                                sizeof(struct lpfc_mqe));
9662         mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
9663         lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
9664                                sizeof(struct lpfc_mcqe));
9665         mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
9666         /*
9667          * When the CQE status indicates a failure and the mailbox status
9668          * indicates success then copy the CQE status into the mailbox status
9669          * (and prefix it with x4000).
9670          */
9671         if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
9672                 if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
9673                         bf_set(lpfc_mqe_status, mb,
9674                                (LPFC_MBX_ERROR_RANGE | mcqe_status));
9675                 rc = MBXERR_ERROR;
9676         } else
9677                 lpfc_sli4_swap_str(phba, mboxq);
9678
9679         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9680                         "(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
9681                         "Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
9682                         " x%x x%x CQ: x%x x%x x%x x%x\n",
9683                         mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
9684                         lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9685                         lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9686                         bf_get(lpfc_mqe_status, mb),
9687                         mb->un.mb_words[0], mb->un.mb_words[1],
9688                         mb->un.mb_words[2], mb->un.mb_words[3],
9689                         mb->un.mb_words[4], mb->un.mb_words[5],
9690                         mb->un.mb_words[6], mb->un.mb_words[7],
9691                         mb->un.mb_words[8], mb->un.mb_words[9],
9692                         mb->un.mb_words[10], mb->un.mb_words[11],
9693                         mb->un.mb_words[12], mboxq->mcqe.word0,
9694                         mboxq->mcqe.mcqe_tag0,  mboxq->mcqe.mcqe_tag1,
9695                         mboxq->mcqe.trailer);
9696 exit:
9697         /* We are holding the token, no needed for lock when release */
9698         spin_lock_irqsave(&phba->hbalock, iflag);
9699         psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9700         phba->sli.mbox_active = NULL;
9701         spin_unlock_irqrestore(&phba->hbalock, iflag);
9702         return rc;
9703 }
9704
9705 /**
9706  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
9707  * @phba: Pointer to HBA context object.
9708  * @mboxq: Pointer to mailbox object.
9709  * @flag: Flag indicating how the mailbox need to be processed.
9710  *
9711  * This function is called by discovery code and HBA management code to submit
9712  * a mailbox command to firmware with SLI-4 interface spec.
9713  *
9714  * Return codes the caller owns the mailbox command after the return of the
9715  * function.
9716  **/
9717 static int
9718 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
9719                        uint32_t flag)
9720 {
9721         struct lpfc_sli *psli = &phba->sli;
9722         unsigned long iflags;
9723         int rc;
9724
9725         /* dump from issue mailbox command if setup */
9726         lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
9727
9728         rc = lpfc_mbox_dev_check(phba);
9729         if (unlikely(rc)) {
9730                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9731                                 "(%d):2544 Mailbox command x%x (x%x/x%x) "
9732                                 "cannot issue Data: x%x x%x\n",
9733                                 mboxq->vport ? mboxq->vport->vpi : 0,
9734                                 mboxq->u.mb.mbxCommand,
9735                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9736                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9737                                 psli->sli_flag, flag);
9738                 goto out_not_finished;
9739         }
9740
9741         /* Detect polling mode and jump to a handler */
9742         if (!phba->sli4_hba.intr_enable) {
9743                 if (flag == MBX_POLL)
9744                         rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
9745                 else
9746                         rc = -EIO;
9747                 if (rc != MBX_SUCCESS)
9748                         lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
9749                                         "(%d):2541 Mailbox command x%x "
9750                                         "(x%x/x%x) failure: "
9751                                         "mqe_sta: x%x mcqe_sta: x%x/x%x "
9752                                         "Data: x%x x%x\n",
9753                                         mboxq->vport ? mboxq->vport->vpi : 0,
9754                                         mboxq->u.mb.mbxCommand,
9755                                         lpfc_sli_config_mbox_subsys_get(phba,
9756                                                                         mboxq),
9757                                         lpfc_sli_config_mbox_opcode_get(phba,
9758                                                                         mboxq),
9759                                         bf_get(lpfc_mqe_status, &mboxq->u.mqe),
9760                                         bf_get(lpfc_mcqe_status, &mboxq->mcqe),
9761                                         bf_get(lpfc_mcqe_ext_status,
9762                                                &mboxq->mcqe),
9763                                         psli->sli_flag, flag);
9764                 return rc;
9765         } else if (flag == MBX_POLL) {
9766                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
9767                                 "(%d):2542 Try to issue mailbox command "
9768                                 "x%x (x%x/x%x) synchronously ahead of async "
9769                                 "mailbox command queue: x%x x%x\n",
9770                                 mboxq->vport ? mboxq->vport->vpi : 0,
9771                                 mboxq->u.mb.mbxCommand,
9772                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9773                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9774                                 psli->sli_flag, flag);
9775                 /* Try to block the asynchronous mailbox posting */
9776                 rc = lpfc_sli4_async_mbox_block(phba);
9777                 if (!rc) {
9778                         /* Successfully blocked, now issue sync mbox cmd */
9779                         rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
9780                         if (rc != MBX_SUCCESS)
9781                                 lpfc_printf_log(phba, KERN_WARNING,
9782                                         LOG_MBOX | LOG_SLI,
9783                                         "(%d):2597 Sync Mailbox command "
9784                                         "x%x (x%x/x%x) failure: "
9785                                         "mqe_sta: x%x mcqe_sta: x%x/x%x "
9786                                         "Data: x%x x%x\n",
9787                                         mboxq->vport ? mboxq->vport->vpi : 0,
9788                                         mboxq->u.mb.mbxCommand,
9789                                         lpfc_sli_config_mbox_subsys_get(phba,
9790                                                                         mboxq),
9791                                         lpfc_sli_config_mbox_opcode_get(phba,
9792                                                                         mboxq),
9793                                         bf_get(lpfc_mqe_status, &mboxq->u.mqe),
9794                                         bf_get(lpfc_mcqe_status, &mboxq->mcqe),
9795                                         bf_get(lpfc_mcqe_ext_status,
9796                                                &mboxq->mcqe),
9797                                         psli->sli_flag, flag);
9798                         /* Unblock the async mailbox posting afterward */
9799                         lpfc_sli4_async_mbox_unblock(phba);
9800                 }
9801                 return rc;
9802         }
9803
9804         /* Now, interrupt mode asynchronous mailbox command */
9805         rc = lpfc_mbox_cmd_check(phba, mboxq);
9806         if (rc) {
9807                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9808                                 "(%d):2543 Mailbox command x%x (x%x/x%x) "
9809                                 "cannot issue Data: x%x x%x\n",
9810                                 mboxq->vport ? mboxq->vport->vpi : 0,
9811                                 mboxq->u.mb.mbxCommand,
9812                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9813                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9814                                 psli->sli_flag, flag);
9815                 goto out_not_finished;
9816         }
9817
9818         /* Put the mailbox command to the driver internal FIFO */
9819         psli->slistat.mbox_busy++;
9820         spin_lock_irqsave(&phba->hbalock, iflags);
9821         lpfc_mbox_put(phba, mboxq);
9822         spin_unlock_irqrestore(&phba->hbalock, iflags);
9823         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9824                         "(%d):0354 Mbox cmd issue - Enqueue Data: "
9825                         "x%x (x%x/x%x) x%x x%x x%x\n",
9826                         mboxq->vport ? mboxq->vport->vpi : 0xffffff,
9827                         bf_get(lpfc_mqe_command, &mboxq->u.mqe),
9828                         lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9829                         lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9830                         phba->pport->port_state,
9831                         psli->sli_flag, MBX_NOWAIT);
9832         /* Wake up worker thread to transport mailbox command from head */
9833         lpfc_worker_wake_up(phba);
9834
9835         return MBX_BUSY;
9836
9837 out_not_finished:
9838         return MBX_NOT_FINISHED;
9839 }
9840
9841 /**
9842  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
9843  * @phba: Pointer to HBA context object.
9844  *
9845  * This function is called by worker thread to send a mailbox command to
9846  * SLI4 HBA firmware.
9847  *
9848  **/
9849 int
9850 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
9851 {
9852         struct lpfc_sli *psli = &phba->sli;
9853         LPFC_MBOXQ_t *mboxq;
9854         int rc = MBX_SUCCESS;
9855         unsigned long iflags;
9856         struct lpfc_mqe *mqe;
9857         uint32_t mbx_cmnd;
9858
9859         /* Check interrupt mode before post async mailbox command */
9860         if (unlikely(!phba->sli4_hba.intr_enable))
9861                 return MBX_NOT_FINISHED;
9862
9863         /* Check for mailbox command service token */
9864         spin_lock_irqsave(&phba->hbalock, iflags);
9865         if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9866                 spin_unlock_irqrestore(&phba->hbalock, iflags);
9867                 return MBX_NOT_FINISHED;
9868         }
9869         if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9870                 spin_unlock_irqrestore(&phba->hbalock, iflags);
9871                 return MBX_NOT_FINISHED;
9872         }
9873         if (unlikely(phba->sli.mbox_active)) {
9874                 spin_unlock_irqrestore(&phba->hbalock, iflags);
9875                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9876                                 "0384 There is pending active mailbox cmd\n");
9877                 return MBX_NOT_FINISHED;
9878         }
9879         /* Take the mailbox command service token */
9880         psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9881
9882         /* Get the next mailbox command from head of queue */
9883         mboxq = lpfc_mbox_get(phba);
9884
9885         /* If no more mailbox command waiting for post, we're done */
9886         if (!mboxq) {
9887                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9888                 spin_unlock_irqrestore(&phba->hbalock, iflags);
9889                 return MBX_SUCCESS;
9890         }
9891         phba->sli.mbox_active = mboxq;
9892         spin_unlock_irqrestore(&phba->hbalock, iflags);
9893
9894         /* Check device readiness for posting mailbox command */
9895         rc = lpfc_mbox_dev_check(phba);
9896         if (unlikely(rc))
9897                 /* Driver clean routine will clean up pending mailbox */
9898                 goto out_not_finished;
9899
9900         /* Prepare the mbox command to be posted */
9901         mqe = &mboxq->u.mqe;
9902         mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
9903
9904         /* Start timer for the mbox_tmo and log some mailbox post messages */
9905         mod_timer(&psli->mbox_tmo, (jiffies +
9906                   msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
9907
9908         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9909                         "(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
9910                         "x%x x%x\n",
9911                         mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
9912                         lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9913                         lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9914                         phba->pport->port_state, psli->sli_flag);
9915
9916         if (mbx_cmnd != MBX_HEARTBEAT) {
9917                 if (mboxq->vport) {
9918                         lpfc_debugfs_disc_trc(mboxq->vport,
9919                                 LPFC_DISC_TRC_MBOX_VPORT,
9920                                 "MBOX Send vport: cmd:x%x mb:x%x x%x",
9921                                 mbx_cmnd, mqe->un.mb_words[0],
9922                                 mqe->un.mb_words[1]);
9923                 } else {
9924                         lpfc_debugfs_disc_trc(phba->pport,
9925                                 LPFC_DISC_TRC_MBOX,
9926                                 "MBOX Send: cmd:x%x mb:x%x x%x",
9927                                 mbx_cmnd, mqe->un.mb_words[0],
9928                                 mqe->un.mb_words[1]);
9929                 }
9930         }
9931         psli->slistat.mbox_cmd++;
9932
9933         /* Post the mailbox command to the port */
9934         rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
9935         if (rc != MBX_SUCCESS) {
9936                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9937                                 "(%d):2533 Mailbox command x%x (x%x/x%x) "
9938                                 "cannot issue Data: x%x x%x\n",
9939                                 mboxq->vport ? mboxq->vport->vpi : 0,
9940                                 mboxq->u.mb.mbxCommand,
9941                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9942                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9943                                 psli->sli_flag, MBX_NOWAIT);
9944                 goto out_not_finished;
9945         }
9946
9947         return rc;
9948
9949 out_not_finished:
9950         spin_lock_irqsave(&phba->hbalock, iflags);
9951         if (phba->sli.mbox_active) {
9952                 mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
9953                 __lpfc_mbox_cmpl_put(phba, mboxq);
9954                 /* Release the token */
9955                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9956                 phba->sli.mbox_active = NULL;
9957         }
9958         spin_unlock_irqrestore(&phba->hbalock, iflags);
9959
9960         return MBX_NOT_FINISHED;
9961 }
9962
9963 /**
9964  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
9965  * @phba: Pointer to HBA context object.
9966  * @pmbox: Pointer to mailbox object.
9967  * @flag: Flag indicating how the mailbox need to be processed.
9968  *
9969  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
9970  * the API jump table function pointer from the lpfc_hba struct.
9971  *
9972  * Return codes the caller owns the mailbox command after the return of the
9973  * function.
9974  **/
9975 int
9976 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
9977 {
9978         return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
9979 }
9980
9981 /**
9982  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
9983  * @phba: The hba struct for which this call is being executed.
9984  * @dev_grp: The HBA PCI-Device group number.
9985  *
9986  * This routine sets up the mbox interface API function jump table in @phba
9987  * struct.
9988  * Returns: 0 - success, -ENODEV - failure.
9989  **/
9990 int
9991 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
9992 {
9993
9994         switch (dev_grp) {
9995         case LPFC_PCI_DEV_LP:
9996                 phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
9997                 phba->lpfc_sli_handle_slow_ring_event =
9998                                 lpfc_sli_handle_slow_ring_event_s3;
9999                 phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
10000                 phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
10001                 phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
10002                 break;
10003         case LPFC_PCI_DEV_OC:
10004                 phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
10005                 phba->lpfc_sli_handle_slow_ring_event =
10006                                 lpfc_sli_handle_slow_ring_event_s4;
10007                 phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
10008                 phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
10009                 phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
10010                 break;
10011         default:
10012                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10013                                 "1420 Invalid HBA PCI-device group: 0x%x\n",
10014                                 dev_grp);
10015                 return -ENODEV;
10016         }
10017         return 0;
10018 }
10019
10020 /**
10021  * __lpfc_sli_ringtx_put - Add an iocb to the txq
10022  * @phba: Pointer to HBA context object.
10023  * @pring: Pointer to driver SLI ring object.
10024  * @piocb: Pointer to address of newly added command iocb.
10025  *
10026  * This function is called with hbalock held for SLI3 ports or
10027  * the ring lock held for SLI4 ports to add a command
10028  * iocb to the txq when SLI layer cannot submit the command iocb
10029  * to the ring.
10030  **/
10031 void
10032 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10033                     struct lpfc_iocbq *piocb)
10034 {
10035         if (phba->sli_rev == LPFC_SLI_REV4)
10036                 lockdep_assert_held(&pring->ring_lock);
10037         else
10038                 lockdep_assert_held(&phba->hbalock);
10039         /* Insert the caller's iocb in the txq tail for later processing. */
10040         list_add_tail(&piocb->list, &pring->txq);
10041 }
10042
10043 /**
10044  * lpfc_sli_next_iocb - Get the next iocb in the txq
10045  * @phba: Pointer to HBA context object.
10046  * @pring: Pointer to driver SLI ring object.
10047  * @piocb: Pointer to address of newly added command iocb.
10048  *
10049  * This function is called with hbalock held before a new
10050  * iocb is submitted to the firmware. This function checks
10051  * txq to flush the iocbs in txq to Firmware before
10052  * submitting new iocbs to the Firmware.
10053  * If there are iocbs in the txq which need to be submitted
10054  * to firmware, lpfc_sli_next_iocb returns the first element
10055  * of the txq after dequeuing it from txq.
10056  * If there is no iocb in the txq then the function will return
10057  * *piocb and *piocb is set to NULL. Caller needs to check
10058  * *piocb to find if there are more commands in the txq.
10059  **/
10060 static struct lpfc_iocbq *
10061 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10062                    struct lpfc_iocbq **piocb)
10063 {
10064         struct lpfc_iocbq * nextiocb;
10065
10066         lockdep_assert_held(&phba->hbalock);
10067
10068         nextiocb = lpfc_sli_ringtx_get(phba, pring);
10069         if (!nextiocb) {
10070                 nextiocb = *piocb;
10071                 *piocb = NULL;
10072         }
10073
10074         return nextiocb;
10075 }
10076
10077 /**
10078  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
10079  * @phba: Pointer to HBA context object.
10080  * @ring_number: SLI ring number to issue iocb on.
10081  * @piocb: Pointer to command iocb.
10082  * @flag: Flag indicating if this command can be put into txq.
10083  *
10084  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
10085  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
10086  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
10087  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
10088  * this function allows only iocbs for posting buffers. This function finds
10089  * next available slot in the command ring and posts the command to the
10090  * available slot and writes the port attention register to request HBA start
10091  * processing new iocb. If there is no slot available in the ring and
10092  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
10093  * the function returns IOCB_BUSY.
10094  *
10095  * This function is called with hbalock held. The function will return success
10096  * after it successfully submit the iocb to firmware or after adding to the
10097  * txq.
10098  **/
10099 static int
10100 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
10101                     struct lpfc_iocbq *piocb, uint32_t flag)
10102 {
10103         struct lpfc_iocbq *nextiocb;
10104         IOCB_t *iocb;
10105         struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
10106
10107         lockdep_assert_held(&phba->hbalock);
10108
10109         if (piocb->iocb_cmpl && (!piocb->vport) &&
10110            (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
10111            (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
10112                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10113                                 "1807 IOCB x%x failed. No vport\n",
10114                                 piocb->iocb.ulpCommand);
10115                 dump_stack();
10116                 return IOCB_ERROR;
10117         }
10118
10119
10120         /* If the PCI channel is in offline state, do not post iocbs. */
10121         if (unlikely(pci_channel_offline(phba->pcidev)))
10122                 return IOCB_ERROR;
10123
10124         /* If HBA has a deferred error attention, fail the iocb. */
10125         if (unlikely(phba->hba_flag & DEFER_ERATT))
10126                 return IOCB_ERROR;
10127
10128         /*
10129          * We should never get an IOCB if we are in a < LINK_DOWN state
10130          */
10131         if (unlikely(phba->link_state < LPFC_LINK_DOWN))
10132                 return IOCB_ERROR;
10133
10134         /*
10135          * Check to see if we are blocking IOCB processing because of a
10136          * outstanding event.
10137          */
10138         if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
10139                 goto iocb_busy;
10140
10141         if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
10142                 /*
10143                  * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
10144                  * can be issued if the link is not up.
10145                  */
10146                 switch (piocb->iocb.ulpCommand) {
10147                 case CMD_GEN_REQUEST64_CR:
10148                 case CMD_GEN_REQUEST64_CX:
10149                         if (!(phba->sli.sli_flag & LPFC_MENLO_MAINT) ||
10150                                 (piocb->iocb.un.genreq64.w5.hcsw.Rctl !=
10151                                         FC_RCTL_DD_UNSOL_CMD) ||
10152                                 (piocb->iocb.un.genreq64.w5.hcsw.Type !=
10153                                         MENLO_TRANSPORT_TYPE))
10154
10155                                 goto iocb_busy;
10156                         break;
10157                 case CMD_QUE_RING_BUF_CN:
10158                 case CMD_QUE_RING_BUF64_CN:
10159                         /*
10160                          * For IOCBs, like QUE_RING_BUF, that have no rsp ring
10161                          * completion, iocb_cmpl MUST be 0.
10162                          */
10163                         if (piocb->iocb_cmpl)
10164                                 piocb->iocb_cmpl = NULL;
10165                         fallthrough;
10166                 case CMD_CREATE_XRI_CR:
10167                 case CMD_CLOSE_XRI_CN:
10168                 case CMD_CLOSE_XRI_CX:
10169                         break;
10170                 default:
10171                         goto iocb_busy;
10172                 }
10173
10174         /*
10175          * For FCP commands, we must be in a state where we can process link
10176          * attention events.
10177          */
10178         } else if (unlikely(pring->ringno == LPFC_FCP_RING &&
10179                             !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
10180                 goto iocb_busy;
10181         }
10182
10183         while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
10184                (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
10185                 lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
10186
10187         if (iocb)
10188                 lpfc_sli_update_ring(phba, pring);
10189         else
10190                 lpfc_sli_update_full_ring(phba, pring);
10191
10192         if (!piocb)
10193                 return IOCB_SUCCESS;
10194
10195         goto out_busy;
10196
10197  iocb_busy:
10198         pring->stats.iocb_cmd_delay++;
10199
10200  out_busy:
10201
10202         if (!(flag & SLI_IOCB_RET_IOCB)) {
10203                 __lpfc_sli_ringtx_put(phba, pring, piocb);
10204                 return IOCB_SUCCESS;
10205         }
10206
10207         return IOCB_BUSY;
10208 }
10209
10210 /**
10211  * lpfc_sli4_bpl2sgl - Convert the bpl/bde to a sgl.
10212  * @phba: Pointer to HBA context object.
10213  * @piocbq: Pointer to command iocb.
10214  * @sglq: Pointer to the scatter gather queue object.
10215  *
10216  * This routine converts the bpl or bde that is in the IOCB
10217  * to a sgl list for the sli4 hardware. The physical address
10218  * of the bpl/bde is converted back to a virtual address.
10219  * If the IOCB contains a BPL then the list of BDE's is
10220  * converted to sli4_sge's. If the IOCB contains a single
10221  * BDE then it is converted to a single sli_sge.
10222  * The IOCB is still in cpu endianess so the contents of
10223  * the bpl can be used without byte swapping.
10224  *
10225  * Returns valid XRI = Success, NO_XRI = Failure.
10226 **/
10227 static uint16_t
10228 lpfc_sli4_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq,
10229                 struct lpfc_sglq *sglq)
10230 {
10231         uint16_t xritag = NO_XRI;
10232         struct ulp_bde64 *bpl = NULL;
10233         struct ulp_bde64 bde;
10234         struct sli4_sge *sgl  = NULL;
10235         struct lpfc_dmabuf *dmabuf;
10236         IOCB_t *icmd;
10237         int numBdes = 0;
10238         int i = 0;
10239         uint32_t offset = 0; /* accumulated offset in the sg request list */
10240         int inbound = 0; /* number of sg reply entries inbound from firmware */
10241
10242         if (!piocbq || !sglq)
10243                 return xritag;
10244
10245         sgl  = (struct sli4_sge *)sglq->sgl;
10246         icmd = &piocbq->iocb;
10247         if (icmd->ulpCommand == CMD_XMIT_BLS_RSP64_CX)
10248                 return sglq->sli4_xritag;
10249         if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
10250                 numBdes = icmd->un.genreq64.bdl.bdeSize /
10251                                 sizeof(struct ulp_bde64);
10252                 /* The addrHigh and addrLow fields within the IOCB
10253                  * have not been byteswapped yet so there is no
10254                  * need to swap them back.
10255                  */
10256                 if (piocbq->context3)
10257                         dmabuf = (struct lpfc_dmabuf *)piocbq->context3;
10258                 else
10259                         return xritag;
10260
10261                 bpl  = (struct ulp_bde64 *)dmabuf->virt;
10262                 if (!bpl)
10263                         return xritag;
10264
10265                 for (i = 0; i < numBdes; i++) {
10266                         /* Should already be byte swapped. */
10267                         sgl->addr_hi = bpl->addrHigh;
10268                         sgl->addr_lo = bpl->addrLow;
10269
10270                         sgl->word2 = le32_to_cpu(sgl->word2);
10271                         if ((i+1) == numBdes)
10272                                 bf_set(lpfc_sli4_sge_last, sgl, 1);
10273                         else
10274                                 bf_set(lpfc_sli4_sge_last, sgl, 0);
10275                         /* swap the size field back to the cpu so we
10276                          * can assign it to the sgl.
10277                          */
10278                         bde.tus.w = le32_to_cpu(bpl->tus.w);
10279                         sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
10280                         /* The offsets in the sgl need to be accumulated
10281                          * separately for the request and reply lists.
10282                          * The request is always first, the reply follows.
10283                          */
10284                         if (piocbq->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
10285                                 /* add up the reply sg entries */
10286                                 if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
10287                                         inbound++;
10288                                 /* first inbound? reset the offset */
10289                                 if (inbound == 1)
10290                                         offset = 0;
10291                                 bf_set(lpfc_sli4_sge_offset, sgl, offset);
10292                                 bf_set(lpfc_sli4_sge_type, sgl,
10293                                         LPFC_SGE_TYPE_DATA);
10294                                 offset += bde.tus.f.bdeSize;
10295                         }
10296                         sgl->word2 = cpu_to_le32(sgl->word2);
10297                         bpl++;
10298                         sgl++;
10299                 }
10300         } else if (icmd->un.genreq64.bdl.bdeFlags == BUFF_TYPE_BDE_64) {
10301                         /* The addrHigh and addrLow fields of the BDE have not
10302                          * been byteswapped yet so they need to be swapped
10303                          * before putting them in the sgl.
10304                          */
10305                         sgl->addr_hi =
10306                                 cpu_to_le32(icmd->un.genreq64.bdl.addrHigh);
10307                         sgl->addr_lo =
10308                                 cpu_to_le32(icmd->un.genreq64.bdl.addrLow);
10309                         sgl->word2 = le32_to_cpu(sgl->word2);
10310                         bf_set(lpfc_sli4_sge_last, sgl, 1);
10311                         sgl->word2 = cpu_to_le32(sgl->word2);
10312                         sgl->sge_len =
10313                                 cpu_to_le32(icmd->un.genreq64.bdl.bdeSize);
10314         }
10315         return sglq->sli4_xritag;
10316 }
10317
10318 /**
10319  * lpfc_sli4_iocb2wqe - Convert the IOCB to a work queue entry.
10320  * @phba: Pointer to HBA context object.
10321  * @iocbq: Pointer to command iocb.
10322  * @wqe: Pointer to the work queue entry.
10323  *
10324  * This routine converts the iocb command to its Work Queue Entry
10325  * equivalent. The wqe pointer should not have any fields set when
10326  * this routine is called because it will memcpy over them.
10327  * This routine does not set the CQ_ID or the WQEC bits in the
10328  * wqe.
10329  *
10330  * Returns: 0 = Success, IOCB_ERROR = Failure.
10331  **/
10332 static int
10333 lpfc_sli4_iocb2wqe(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq,
10334                 union lpfc_wqe128 *wqe)
10335 {
10336         uint32_t xmit_len = 0, total_len = 0;
10337         uint8_t ct = 0;
10338         uint32_t fip;
10339         uint32_t abort_tag;
10340         uint8_t command_type = ELS_COMMAND_NON_FIP;
10341         uint8_t cmnd;
10342         uint16_t xritag;
10343         uint16_t abrt_iotag;
10344         struct lpfc_iocbq *abrtiocbq;
10345         struct ulp_bde64 *bpl = NULL;
10346         uint32_t els_id = LPFC_ELS_ID_DEFAULT;
10347         int numBdes, i;
10348         struct ulp_bde64 bde;
10349         struct lpfc_nodelist *ndlp;
10350         uint32_t *pcmd;
10351         uint32_t if_type;
10352
10353         fip = phba->hba_flag & HBA_FIP_SUPPORT;
10354         /* The fcp commands will set command type */
10355         if (iocbq->iocb_flag &  LPFC_IO_FCP)
10356                 command_type = FCP_COMMAND;
10357         else if (fip && (iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK))
10358                 command_type = ELS_COMMAND_FIP;
10359         else
10360                 command_type = ELS_COMMAND_NON_FIP;
10361
10362         if (phba->fcp_embed_io)
10363                 memset(wqe, 0, sizeof(union lpfc_wqe128));
10364         /* Some of the fields are in the right position already */
10365         memcpy(wqe, &iocbq->iocb, sizeof(union lpfc_wqe));
10366         /* The ct field has moved so reset */
10367         wqe->generic.wqe_com.word7 = 0;
10368         wqe->generic.wqe_com.word10 = 0;
10369
10370         abort_tag = (uint32_t) iocbq->iotag;
10371         xritag = iocbq->sli4_xritag;
10372         /* words0-2 bpl convert bde */
10373         if (iocbq->iocb.un.genreq64.bdl.bdeFlags == BUFF_TYPE_BLP_64) {
10374                 numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
10375                                 sizeof(struct ulp_bde64);
10376                 bpl  = (struct ulp_bde64 *)
10377                         ((struct lpfc_dmabuf *)iocbq->context3)->virt;
10378                 if (!bpl)
10379                         return IOCB_ERROR;
10380
10381                 /* Should already be byte swapped. */
10382                 wqe->generic.bde.addrHigh =  le32_to_cpu(bpl->addrHigh);
10383                 wqe->generic.bde.addrLow =  le32_to_cpu(bpl->addrLow);
10384                 /* swap the size field back to the cpu so we
10385                  * can assign it to the sgl.
10386                  */
10387                 wqe->generic.bde.tus.w  = le32_to_cpu(bpl->tus.w);
10388                 xmit_len = wqe->generic.bde.tus.f.bdeSize;
10389                 total_len = 0;
10390                 for (i = 0; i < numBdes; i++) {
10391                         bde.tus.w  = le32_to_cpu(bpl[i].tus.w);
10392                         total_len += bde.tus.f.bdeSize;
10393                 }
10394         } else
10395                 xmit_len = iocbq->iocb.un.fcpi64.bdl.bdeSize;
10396
10397         iocbq->iocb.ulpIoTag = iocbq->iotag;
10398         cmnd = iocbq->iocb.ulpCommand;
10399
10400         switch (iocbq->iocb.ulpCommand) {
10401         case CMD_ELS_REQUEST64_CR:
10402                 if (iocbq->iocb_flag & LPFC_IO_LIBDFC)
10403                         ndlp = iocbq->context_un.ndlp;
10404                 else
10405                         ndlp = (struct lpfc_nodelist *)iocbq->context1;
10406                 if (!iocbq->iocb.ulpLe) {
10407                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10408                                 "2007 Only Limited Edition cmd Format"
10409                                 " supported 0x%x\n",
10410                                 iocbq->iocb.ulpCommand);
10411                         return IOCB_ERROR;
10412                 }
10413
10414                 wqe->els_req.payload_len = xmit_len;
10415                 /* Els_reguest64 has a TMO */
10416                 bf_set(wqe_tmo, &wqe->els_req.wqe_com,
10417                         iocbq->iocb.ulpTimeout);
10418                 /* Need a VF for word 4 set the vf bit*/
10419                 bf_set(els_req64_vf, &wqe->els_req, 0);
10420                 /* And a VFID for word 12 */
10421                 bf_set(els_req64_vfid, &wqe->els_req, 0);
10422                 ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
10423                 bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10424                        iocbq->iocb.ulpContext);
10425                 bf_set(wqe_ct, &wqe->els_req.wqe_com, ct);
10426                 bf_set(wqe_pu, &wqe->els_req.wqe_com, 0);
10427                 /* CCP CCPE PV PRI in word10 were set in the memcpy */
10428                 if (command_type == ELS_COMMAND_FIP)
10429                         els_id = ((iocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK)
10430                                         >> LPFC_FIP_ELS_ID_SHIFT);
10431                 pcmd = (uint32_t *) (((struct lpfc_dmabuf *)
10432                                         iocbq->context2)->virt);
10433                 if_type = bf_get(lpfc_sli_intf_if_type,
10434                                         &phba->sli4_hba.sli_intf);
10435                 if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10436                         if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
10437                                 *pcmd == ELS_CMD_SCR ||
10438                                 *pcmd == ELS_CMD_RDF ||
10439                                 *pcmd == ELS_CMD_EDC ||
10440                                 *pcmd == ELS_CMD_RSCN_XMT ||
10441                                 *pcmd == ELS_CMD_FDISC ||
10442                                 *pcmd == ELS_CMD_LOGO ||
10443                                 *pcmd == ELS_CMD_QFPA ||
10444                                 *pcmd == ELS_CMD_UVEM ||
10445                                 *pcmd == ELS_CMD_PLOGI)) {
10446                                 bf_set(els_req64_sp, &wqe->els_req, 1);
10447                                 bf_set(els_req64_sid, &wqe->els_req,
10448                                         iocbq->vport->fc_myDID);
10449                                 if ((*pcmd == ELS_CMD_FLOGI) &&
10450                                         !(phba->fc_topology ==
10451                                                 LPFC_TOPOLOGY_LOOP))
10452                                         bf_set(els_req64_sid, &wqe->els_req, 0);
10453                                 bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
10454                                 bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10455                                         phba->vpi_ids[iocbq->vport->vpi]);
10456                         } else if (pcmd && iocbq->context1) {
10457                                 bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
10458                                 bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10459                                         phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
10460                         }
10461                 }
10462                 bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
10463                        phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
10464                 bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
10465                 bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
10466                 bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
10467                 bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
10468                 bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
10469                 bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
10470                 wqe->els_req.max_response_payload_len = total_len - xmit_len;
10471                 break;
10472         case CMD_XMIT_SEQUENCE64_CX:
10473                 bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com,
10474                        iocbq->iocb.un.ulpWord[3]);
10475                 bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com,
10476                        iocbq->iocb.unsli3.rcvsli3.ox_id);
10477                 /* The entire sequence is transmitted for this IOCB */
10478                 xmit_len = total_len;
10479                 cmnd = CMD_XMIT_SEQUENCE64_CR;
10480                 if (phba->link_flag & LS_LOOPBACK_MODE)
10481                         bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
10482                 fallthrough;
10483         case CMD_XMIT_SEQUENCE64_CR:
10484                 /* word3 iocb=io_tag32 wqe=reserved */
10485                 wqe->xmit_sequence.rsvd3 = 0;
10486                 /* word4 relative_offset memcpy */
10487                 /* word5 r_ctl/df_ctl memcpy */
10488                 bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
10489                 bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
10490                 bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
10491                        LPFC_WQE_IOD_WRITE);
10492                 bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
10493                        LPFC_WQE_LENLOC_WORD12);
10494                 bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
10495                 wqe->xmit_sequence.xmit_len = xmit_len;
10496                 command_type = OTHER_COMMAND;
10497                 break;
10498         case CMD_XMIT_BCAST64_CN:
10499                 /* word3 iocb=iotag32 wqe=seq_payload_len */
10500                 wqe->xmit_bcast64.seq_payload_len = xmit_len;
10501                 /* word4 iocb=rsvd wqe=rsvd */
10502                 /* word5 iocb=rctl/type/df_ctl wqe=rctl/type/df_ctl memcpy */
10503                 /* word6 iocb=ctxt_tag/io_tag wqe=ctxt_tag/xri */
10504                 bf_set(wqe_ct, &wqe->xmit_bcast64.wqe_com,
10505                         ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
10506                 bf_set(wqe_dbde, &wqe->xmit_bcast64.wqe_com, 1);
10507                 bf_set(wqe_iod, &wqe->xmit_bcast64.wqe_com, LPFC_WQE_IOD_WRITE);
10508                 bf_set(wqe_lenloc, &wqe->xmit_bcast64.wqe_com,
10509                        LPFC_WQE_LENLOC_WORD3);
10510                 bf_set(wqe_ebde_cnt, &wqe->xmit_bcast64.wqe_com, 0);
10511                 break;
10512         case CMD_FCP_IWRITE64_CR:
10513                 command_type = FCP_COMMAND_DATA_OUT;
10514                 /* word3 iocb=iotag wqe=payload_offset_len */
10515                 /* Add the FCP_CMD and FCP_RSP sizes to get the offset */
10516                 bf_set(payload_offset_len, &wqe->fcp_iwrite,
10517                        xmit_len + sizeof(struct fcp_rsp));
10518                 bf_set(cmd_buff_len, &wqe->fcp_iwrite,
10519                        0);
10520                 /* word4 iocb=parameter wqe=total_xfer_length memcpy */
10521                 /* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
10522                 bf_set(wqe_erp, &wqe->fcp_iwrite.wqe_com,
10523                        iocbq->iocb.ulpFCP2Rcvy);
10524                 bf_set(wqe_lnk, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpXS);
10525                 /* Always open the exchange */
10526                 bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
10527                 bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com,
10528                        LPFC_WQE_LENLOC_WORD4);
10529                 bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, iocbq->iocb.ulpPU);
10530                 bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 1);
10531                 if (iocbq->iocb_flag & LPFC_IO_OAS) {
10532                         bf_set(wqe_oas, &wqe->fcp_iwrite.wqe_com, 1);
10533                         bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
10534                         if (iocbq->priority) {
10535                                 bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
10536                                        (iocbq->priority << 1));
10537                         } else {
10538                                 bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
10539                                        (phba->cfg_XLanePriority << 1));
10540                         }
10541                 }
10542                 /* Note, word 10 is already initialized to 0 */
10543
10544                 /* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
10545                 if (phba->cfg_enable_pbde)
10546                         bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 1);
10547                 else
10548                         bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
10549
10550                 if (phba->fcp_embed_io) {
10551                         struct lpfc_io_buf *lpfc_cmd;
10552                         struct sli4_sge *sgl;
10553                         struct fcp_cmnd *fcp_cmnd;
10554                         uint32_t *ptr;
10555
10556                         /* 128 byte wqe support here */
10557
10558                         lpfc_cmd = iocbq->context1;
10559                         sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10560                         fcp_cmnd = lpfc_cmd->fcp_cmnd;
10561
10562                         /* Word 0-2 - FCP_CMND */
10563                         wqe->generic.bde.tus.f.bdeFlags =
10564                                 BUFF_TYPE_BDE_IMMED;
10565                         wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10566                         wqe->generic.bde.addrHigh = 0;
10567                         wqe->generic.bde.addrLow =  88;  /* Word 22 */
10568
10569                         bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10570                         bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10571
10572                         /* Word 22-29  FCP CMND Payload */
10573                         ptr = &wqe->words[22];
10574                         memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10575                 }
10576                 break;
10577         case CMD_FCP_IREAD64_CR:
10578                 /* word3 iocb=iotag wqe=payload_offset_len */
10579                 /* Add the FCP_CMD and FCP_RSP sizes to get the offset */
10580                 bf_set(payload_offset_len, &wqe->fcp_iread,
10581                        xmit_len + sizeof(struct fcp_rsp));
10582                 bf_set(cmd_buff_len, &wqe->fcp_iread,
10583                        0);
10584                 /* word4 iocb=parameter wqe=total_xfer_length memcpy */
10585                 /* word5 iocb=initial_xfer_len wqe=initial_xfer_len memcpy */
10586                 bf_set(wqe_erp, &wqe->fcp_iread.wqe_com,
10587                        iocbq->iocb.ulpFCP2Rcvy);
10588                 bf_set(wqe_lnk, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpXS);
10589                 /* Always open the exchange */
10590                 bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
10591                 bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com,
10592                        LPFC_WQE_LENLOC_WORD4);
10593                 bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, iocbq->iocb.ulpPU);
10594                 bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 1);
10595                 if (iocbq->iocb_flag & LPFC_IO_OAS) {
10596                         bf_set(wqe_oas, &wqe->fcp_iread.wqe_com, 1);
10597                         bf_set(wqe_ccpe, &wqe->fcp_iread.wqe_com, 1);
10598                         if (iocbq->priority) {
10599                                 bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
10600                                        (iocbq->priority << 1));
10601                         } else {
10602                                 bf_set(wqe_ccp, &wqe->fcp_iread.wqe_com,
10603                                        (phba->cfg_XLanePriority << 1));
10604                         }
10605                 }
10606                 /* Note, word 10 is already initialized to 0 */
10607
10608                 /* Don't set PBDE for Perf hints, just lpfc_enable_pbde */
10609                 if (phba->cfg_enable_pbde)
10610                         bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 1);
10611                 else
10612                         bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
10613
10614                 if (phba->fcp_embed_io) {
10615                         struct lpfc_io_buf *lpfc_cmd;
10616                         struct sli4_sge *sgl;
10617                         struct fcp_cmnd *fcp_cmnd;
10618                         uint32_t *ptr;
10619
10620                         /* 128 byte wqe support here */
10621
10622                         lpfc_cmd = iocbq->context1;
10623                         sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10624                         fcp_cmnd = lpfc_cmd->fcp_cmnd;
10625
10626                         /* Word 0-2 - FCP_CMND */
10627                         wqe->generic.bde.tus.f.bdeFlags =
10628                                 BUFF_TYPE_BDE_IMMED;
10629                         wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10630                         wqe->generic.bde.addrHigh = 0;
10631                         wqe->generic.bde.addrLow =  88;  /* Word 22 */
10632
10633                         bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
10634                         bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
10635
10636                         /* Word 22-29  FCP CMND Payload */
10637                         ptr = &wqe->words[22];
10638                         memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10639                 }
10640                 break;
10641         case CMD_FCP_ICMND64_CR:
10642                 /* word3 iocb=iotag wqe=payload_offset_len */
10643                 /* Add the FCP_CMD and FCP_RSP sizes to get the offset */
10644                 bf_set(payload_offset_len, &wqe->fcp_icmd,
10645                        xmit_len + sizeof(struct fcp_rsp));
10646                 bf_set(cmd_buff_len, &wqe->fcp_icmd,
10647                        0);
10648                 /* word3 iocb=IO_TAG wqe=reserved */
10649                 bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
10650                 /* Always open the exchange */
10651                 bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 1);
10652                 bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_WRITE);
10653                 bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
10654                 bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com,
10655                        LPFC_WQE_LENLOC_NONE);
10656                 bf_set(wqe_erp, &wqe->fcp_icmd.wqe_com,
10657                        iocbq->iocb.ulpFCP2Rcvy);
10658                 if (iocbq->iocb_flag & LPFC_IO_OAS) {
10659                         bf_set(wqe_oas, &wqe->fcp_icmd.wqe_com, 1);
10660                         bf_set(wqe_ccpe, &wqe->fcp_icmd.wqe_com, 1);
10661                         if (iocbq->priority) {
10662                                 bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
10663                                        (iocbq->priority << 1));
10664                         } else {
10665                                 bf_set(wqe_ccp, &wqe->fcp_icmd.wqe_com,
10666                                        (phba->cfg_XLanePriority << 1));
10667                         }
10668                 }
10669                 /* Note, word 10 is already initialized to 0 */
10670
10671                 if (phba->fcp_embed_io) {
10672                         struct lpfc_io_buf *lpfc_cmd;
10673                         struct sli4_sge *sgl;
10674                         struct fcp_cmnd *fcp_cmnd;
10675                         uint32_t *ptr;
10676
10677                         /* 128 byte wqe support here */
10678
10679                         lpfc_cmd = iocbq->context1;
10680                         sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10681                         fcp_cmnd = lpfc_cmd->fcp_cmnd;
10682
10683                         /* Word 0-2 - FCP_CMND */
10684                         wqe->generic.bde.tus.f.bdeFlags =
10685                                 BUFF_TYPE_BDE_IMMED;
10686                         wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10687                         wqe->generic.bde.addrHigh = 0;
10688                         wqe->generic.bde.addrLow =  88;  /* Word 22 */
10689
10690                         bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
10691                         bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
10692
10693                         /* Word 22-29  FCP CMND Payload */
10694                         ptr = &wqe->words[22];
10695                         memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10696                 }
10697                 break;
10698         case CMD_GEN_REQUEST64_CR:
10699                 /* For this command calculate the xmit length of the
10700                  * request bde.
10701                  */
10702                 xmit_len = 0;
10703                 numBdes = iocbq->iocb.un.genreq64.bdl.bdeSize /
10704                         sizeof(struct ulp_bde64);
10705                 for (i = 0; i < numBdes; i++) {
10706                         bde.tus.w = le32_to_cpu(bpl[i].tus.w);
10707                         if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
10708                                 break;
10709                         xmit_len += bde.tus.f.bdeSize;
10710                 }
10711                 /* word3 iocb=IO_TAG wqe=request_payload_len */
10712                 wqe->gen_req.request_payload_len = xmit_len;
10713                 /* word4 iocb=parameter wqe=relative_offset memcpy */
10714                 /* word5 [rctl, type, df_ctl, la] copied in memcpy */
10715                 /* word6 context tag copied in memcpy */
10716                 if (iocbq->iocb.ulpCt_h  || iocbq->iocb.ulpCt_l) {
10717                         ct = ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l);
10718                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10719                                 "2015 Invalid CT %x command 0x%x\n",
10720                                 ct, iocbq->iocb.ulpCommand);
10721                         return IOCB_ERROR;
10722                 }
10723                 bf_set(wqe_ct, &wqe->gen_req.wqe_com, 0);
10724                 bf_set(wqe_tmo, &wqe->gen_req.wqe_com, iocbq->iocb.ulpTimeout);
10725                 bf_set(wqe_pu, &wqe->gen_req.wqe_com, iocbq->iocb.ulpPU);
10726                 bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
10727                 bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
10728                 bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
10729                 bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
10730                 bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
10731                 wqe->gen_req.max_response_payload_len = total_len - xmit_len;
10732                 command_type = OTHER_COMMAND;
10733                 break;
10734         case CMD_XMIT_ELS_RSP64_CX:
10735                 ndlp = (struct lpfc_nodelist *)iocbq->context1;
10736                 /* words0-2 BDE memcpy */
10737                 /* word3 iocb=iotag32 wqe=response_payload_len */
10738                 wqe->xmit_els_rsp.response_payload_len = xmit_len;
10739                 /* word4 */
10740                 wqe->xmit_els_rsp.word4 = 0;
10741                 /* word5 iocb=rsvd wge=did */
10742                 bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
10743                          iocbq->iocb.un.xseq64.xmit_els_remoteID);
10744
10745                 if_type = bf_get(lpfc_sli_intf_if_type,
10746                                         &phba->sli4_hba.sli_intf);
10747                 if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
10748                         if (iocbq->vport->fc_flag & FC_PT2PT) {
10749                                 bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
10750                                 bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
10751                                         iocbq->vport->fc_myDID);
10752                                 if (iocbq->vport->fc_myDID == Fabric_DID) {
10753                                         bf_set(wqe_els_did,
10754                                                 &wqe->xmit_els_rsp.wqe_dest, 0);
10755                                 }
10756                         }
10757                 }
10758                 bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com,
10759                        ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
10760                 bf_set(wqe_pu, &wqe->xmit_els_rsp.wqe_com, iocbq->iocb.ulpPU);
10761                 bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
10762                        iocbq->iocb.unsli3.rcvsli3.ox_id);
10763                 if (!iocbq->iocb.ulpCt_h && iocbq->iocb.ulpCt_l)
10764                         bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
10765                                phba->vpi_ids[iocbq->vport->vpi]);
10766                 bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
10767                 bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
10768                 bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
10769                 bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
10770                        LPFC_WQE_LENLOC_WORD3);
10771                 bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
10772                 bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
10773                        phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
10774                 if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
10775                                 bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
10776                                 bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
10777                                         iocbq->vport->fc_myDID);
10778                                 bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
10779                                 bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
10780                                         phba->vpi_ids[phba->pport->vpi]);
10781                 }
10782                 command_type = OTHER_COMMAND;
10783                 break;
10784         case CMD_CLOSE_XRI_CN:
10785         case CMD_ABORT_XRI_CN:
10786         case CMD_ABORT_XRI_CX:
10787                 /* words 0-2 memcpy should be 0 rserved */
10788                 /* port will send abts */
10789                 abrt_iotag = iocbq->iocb.un.acxri.abortContextTag;
10790                 if (abrt_iotag != 0 && abrt_iotag <= phba->sli.last_iotag) {
10791                         abrtiocbq = phba->sli.iocbq_lookup[abrt_iotag];
10792                         fip = abrtiocbq->iocb_flag & LPFC_FIP_ELS_ID_MASK;
10793                 } else
10794                         fip = 0;
10795
10796                 if ((iocbq->iocb.ulpCommand == CMD_CLOSE_XRI_CN) || fip)
10797                         /*
10798                          * The link is down, or the command was ELS_FIP
10799                          * so the fw does not need to send abts
10800                          * on the wire.
10801                          */
10802                         bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
10803                 else
10804                         bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
10805                 bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
10806                 /* word5 iocb=CONTEXT_TAG|IO_TAG wqe=reserved */
10807                 wqe->abort_cmd.rsrvd5 = 0;
10808                 bf_set(wqe_ct, &wqe->abort_cmd.wqe_com,
10809                         ((iocbq->iocb.ulpCt_h << 1) | iocbq->iocb.ulpCt_l));
10810                 abort_tag = iocbq->iocb.un.acxri.abortIoTag;
10811                 /*
10812                  * The abort handler will send us CMD_ABORT_XRI_CN or
10813                  * CMD_CLOSE_XRI_CN and the fw only accepts CMD_ABORT_XRI_CX
10814                  */
10815                 bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
10816                 bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
10817                 bf_set(wqe_lenloc, &wqe->abort_cmd.wqe_com,
10818                        LPFC_WQE_LENLOC_NONE);
10819                 cmnd = CMD_ABORT_XRI_CX;
10820                 command_type = OTHER_COMMAND;
10821                 xritag = 0;
10822                 break;
10823         case CMD_XMIT_BLS_RSP64_CX:
10824                 ndlp = (struct lpfc_nodelist *)iocbq->context1;
10825                 /* As BLS ABTS RSP WQE is very different from other WQEs,
10826                  * we re-construct this WQE here based on information in
10827                  * iocbq from scratch.
10828                  */
10829                 memset(wqe, 0, sizeof(*wqe));
10830                 /* OX_ID is invariable to who sent ABTS to CT exchange */
10831                 bf_set(xmit_bls_rsp64_oxid, &wqe->xmit_bls_rsp,
10832                        bf_get(lpfc_abts_oxid, &iocbq->iocb.un.bls_rsp));
10833                 if (bf_get(lpfc_abts_orig, &iocbq->iocb.un.bls_rsp) ==
10834                     LPFC_ABTS_UNSOL_INT) {
10835                         /* ABTS sent by initiator to CT exchange, the
10836                          * RX_ID field will be filled with the newly
10837                          * allocated responder XRI.
10838                          */
10839                         bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10840                                iocbq->sli4_xritag);
10841                 } else {
10842                         /* ABTS sent by responder to CT exchange, the
10843                          * RX_ID field will be filled with the responder
10844                          * RX_ID from ABTS.
10845                          */
10846                         bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10847                                bf_get(lpfc_abts_rxid, &iocbq->iocb.un.bls_rsp));
10848                 }
10849                 bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
10850                 bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
10851
10852                 /* Use CT=VPI */
10853                 bf_set(wqe_els_did, &wqe->xmit_bls_rsp.wqe_dest,
10854                         ndlp->nlp_DID);
10855                 bf_set(xmit_bls_rsp64_temprpi, &wqe->xmit_bls_rsp,
10856                         iocbq->iocb.ulpContext);
10857                 bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
10858                 bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
10859                         phba->vpi_ids[phba->pport->vpi]);
10860                 bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
10861                 bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
10862                        LPFC_WQE_LENLOC_NONE);
10863                 /* Overwrite the pre-set comnd type with OTHER_COMMAND */
10864                 command_type = OTHER_COMMAND;
10865                 if (iocbq->iocb.un.xseq64.w5.hcsw.Rctl == FC_RCTL_BA_RJT) {
10866                         bf_set(xmit_bls_rsp64_rjt_vspec, &wqe->xmit_bls_rsp,
10867                                bf_get(lpfc_vndr_code, &iocbq->iocb.un.bls_rsp));
10868                         bf_set(xmit_bls_rsp64_rjt_expc, &wqe->xmit_bls_rsp,
10869                                bf_get(lpfc_rsn_expln, &iocbq->iocb.un.bls_rsp));
10870                         bf_set(xmit_bls_rsp64_rjt_rsnc, &wqe->xmit_bls_rsp,
10871                                bf_get(lpfc_rsn_code, &iocbq->iocb.un.bls_rsp));
10872                 }
10873
10874                 break;
10875         case CMD_SEND_FRAME:
10876                 bf_set(wqe_cmnd, &wqe->generic.wqe_com, CMD_SEND_FRAME);
10877                 bf_set(wqe_sof, &wqe->generic.wqe_com, 0x2E); /* SOF byte */
10878                 bf_set(wqe_eof, &wqe->generic.wqe_com, 0x41); /* EOF byte */
10879                 bf_set(wqe_lenloc, &wqe->generic.wqe_com, 1);
10880                 bf_set(wqe_xbl, &wqe->generic.wqe_com, 1);
10881                 bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10882                 bf_set(wqe_xc, &wqe->generic.wqe_com, 1);
10883                 bf_set(wqe_cmd_type, &wqe->generic.wqe_com, 0xA);
10884                 bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10885                 bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
10886                 bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
10887                 return 0;
10888         case CMD_XRI_ABORTED_CX:
10889         case CMD_CREATE_XRI_CR: /* Do we expect to use this? */
10890         case CMD_IOCB_FCP_IBIDIR64_CR: /* bidirectional xfer */
10891         case CMD_FCP_TSEND64_CX: /* Target mode send xfer-ready */
10892         case CMD_FCP_TRSP64_CX: /* Target mode rcv */
10893         case CMD_FCP_AUTO_TRSP_CX: /* Auto target rsp */
10894         default:
10895                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10896                                 "2014 Invalid command 0x%x\n",
10897                                 iocbq->iocb.ulpCommand);
10898                 return IOCB_ERROR;
10899         }
10900
10901         if (iocbq->iocb_flag & LPFC_IO_DIF_PASS)
10902                 bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_PASSTHRU);
10903         else if (iocbq->iocb_flag & LPFC_IO_DIF_STRIP)
10904                 bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_STRIP);
10905         else if (iocbq->iocb_flag & LPFC_IO_DIF_INSERT)
10906                 bf_set(wqe_dif, &wqe->generic.wqe_com, LPFC_WQE_DIF_INSERT);
10907         iocbq->iocb_flag &= ~(LPFC_IO_DIF_PASS | LPFC_IO_DIF_STRIP |
10908                               LPFC_IO_DIF_INSERT);
10909         bf_set(wqe_xri_tag, &wqe->generic.wqe_com, xritag);
10910         bf_set(wqe_reqtag, &wqe->generic.wqe_com, iocbq->iotag);
10911         wqe->generic.wqe_com.abort_tag = abort_tag;
10912         bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
10913         bf_set(wqe_cmnd, &wqe->generic.wqe_com, cmnd);
10914         bf_set(wqe_class, &wqe->generic.wqe_com, iocbq->iocb.ulpClass);
10915         bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
10916         return 0;
10917 }
10918
10919 /**
10920  * __lpfc_sli_issue_fcp_io_s3 - SLI3 device for sending fcp io iocb
10921  * @phba: Pointer to HBA context object.
10922  * @ring_number: SLI ring number to issue wqe on.
10923  * @piocb: Pointer to command iocb.
10924  * @flag: Flag indicating if this command can be put into txq.
10925  *
10926  * __lpfc_sli_issue_fcp_io_s3 is wrapper function to invoke lockless func to
10927  * send  an iocb command to an HBA with SLI-4 interface spec.
10928  *
10929  * This function takes the hbalock before invoking the lockless version.
10930  * The function will return success after it successfully submit the wqe to
10931  * firmware or after adding to the txq.
10932  **/
10933 static int
10934 __lpfc_sli_issue_fcp_io_s3(struct lpfc_hba *phba, uint32_t ring_number,
10935                            struct lpfc_iocbq *piocb, uint32_t flag)
10936 {
10937         unsigned long iflags;
10938         int rc;
10939
10940         spin_lock_irqsave(&phba->hbalock, iflags);
10941         rc = __lpfc_sli_issue_iocb_s3(phba, ring_number, piocb, flag);
10942         spin_unlock_irqrestore(&phba->hbalock, iflags);
10943
10944         return rc;
10945 }
10946
10947 /**
10948  * __lpfc_sli_issue_fcp_io_s4 - SLI4 device for sending fcp io wqe
10949  * @phba: Pointer to HBA context object.
10950  * @ring_number: SLI ring number to issue wqe on.
10951  * @piocb: Pointer to command iocb.
10952  * @flag: Flag indicating if this command can be put into txq.
10953  *
10954  * __lpfc_sli_issue_fcp_io_s4 is used by other functions in the driver to issue
10955  * an wqe command to an HBA with SLI-4 interface spec.
10956  *
10957  * This function is a lockless version. The function will return success
10958  * after it successfully submit the wqe to firmware or after adding to the
10959  * txq.
10960  **/
10961 static int
10962 __lpfc_sli_issue_fcp_io_s4(struct lpfc_hba *phba, uint32_t ring_number,
10963                            struct lpfc_iocbq *piocb, uint32_t flag)
10964 {
10965         int rc;
10966         struct lpfc_io_buf *lpfc_cmd =
10967                 (struct lpfc_io_buf *)piocb->context1;
10968         union lpfc_wqe128 *wqe = &piocb->wqe;
10969         struct sli4_sge *sgl;
10970
10971         /* 128 byte wqe support here */
10972         sgl = (struct sli4_sge *)lpfc_cmd->dma_sgl;
10973
10974         if (phba->fcp_embed_io) {
10975                 struct fcp_cmnd *fcp_cmnd;
10976                 u32 *ptr;
10977
10978                 fcp_cmnd = lpfc_cmd->fcp_cmnd;
10979
10980                 /* Word 0-2 - FCP_CMND */
10981                 wqe->generic.bde.tus.f.bdeFlags =
10982                         BUFF_TYPE_BDE_IMMED;
10983                 wqe->generic.bde.tus.f.bdeSize = sgl->sge_len;
10984                 wqe->generic.bde.addrHigh = 0;
10985                 wqe->generic.bde.addrLow =  88;  /* Word 22 */
10986
10987                 bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10988                 bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10989
10990                 /* Word 22-29  FCP CMND Payload */
10991                 ptr = &wqe->words[22];
10992                 memcpy(ptr, fcp_cmnd, sizeof(struct fcp_cmnd));
10993         } else {
10994                 /* Word 0-2 - Inline BDE */
10995                 wqe->generic.bde.tus.f.bdeFlags =  BUFF_TYPE_BDE_64;
10996                 wqe->generic.bde.tus.f.bdeSize = sizeof(struct fcp_cmnd);
10997                 wqe->generic.bde.addrHigh = sgl->addr_hi;
10998                 wqe->generic.bde.addrLow =  sgl->addr_lo;
10999
11000                 /* Word 10 */
11001                 bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
11002                 bf_set(wqe_wqes, &wqe->generic.wqe_com, 0);
11003         }
11004
11005         /* add the VMID tags as per switch response */
11006         if (unlikely(piocb->iocb_flag & LPFC_IO_VMID)) {
11007                 if (phba->pport->vmid_priority_tagging) {
11008                         bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
11009                         bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
11010                                         (piocb->vmid_tag.cs_ctl_vmid));
11011                 } else {
11012                         bf_set(wqe_appid, &wqe->fcp_iwrite.wqe_com, 1);
11013                         bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
11014                         wqe->words[31] = piocb->vmid_tag.app_id;
11015                 }
11016         }
11017         rc = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, piocb);
11018         return rc;
11019 }
11020
11021 /**
11022  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
11023  * @phba: Pointer to HBA context object.
11024  * @ring_number: SLI ring number to issue iocb on.
11025  * @piocb: Pointer to command iocb.
11026  * @flag: Flag indicating if this command can be put into txq.
11027  *
11028  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
11029  * an iocb command to an HBA with SLI-4 interface spec.
11030  *
11031  * This function is called with ringlock held. The function will return success
11032  * after it successfully submit the iocb to firmware or after adding to the
11033  * txq.
11034  **/
11035 static int
11036 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
11037                          struct lpfc_iocbq *piocb, uint32_t flag)
11038 {
11039         struct lpfc_sglq *sglq;
11040         union lpfc_wqe128 wqe;
11041         struct lpfc_queue *wq;
11042         struct lpfc_sli_ring *pring;
11043
11044         /* Get the WQ */
11045         if ((piocb->iocb_flag & LPFC_IO_FCP) ||
11046             (piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
11047                 wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
11048         } else {
11049                 wq = phba->sli4_hba.els_wq;
11050         }
11051
11052         /* Get corresponding ring */
11053         pring = wq->pring;
11054
11055         /*
11056          * The WQE can be either 64 or 128 bytes,
11057          */
11058
11059         lockdep_assert_held(&pring->ring_lock);
11060
11061         if (piocb->sli4_xritag == NO_XRI) {
11062                 if (piocb->iocb.ulpCommand == CMD_ABORT_XRI_CN ||
11063                     piocb->iocb.ulpCommand == CMD_CLOSE_XRI_CN)
11064                         sglq = NULL;
11065                 else {
11066                         if (!list_empty(&pring->txq)) {
11067                                 if (!(flag & SLI_IOCB_RET_IOCB)) {
11068                                         __lpfc_sli_ringtx_put(phba,
11069                                                 pring, piocb);
11070                                         return IOCB_SUCCESS;
11071                                 } else {
11072                                         return IOCB_BUSY;
11073                                 }
11074                         } else {
11075                                 sglq = __lpfc_sli_get_els_sglq(phba, piocb);
11076                                 if (!sglq) {
11077                                         if (!(flag & SLI_IOCB_RET_IOCB)) {
11078                                                 __lpfc_sli_ringtx_put(phba,
11079                                                                 pring,
11080                                                                 piocb);
11081                                                 return IOCB_SUCCESS;
11082                                         } else
11083                                                 return IOCB_BUSY;
11084                                 }
11085                         }
11086                 }
11087         } else if (piocb->iocb_flag &  LPFC_IO_FCP) {
11088                 /* These IO's already have an XRI and a mapped sgl. */
11089                 sglq = NULL;
11090         }
11091         else {
11092                 /*
11093                  * This is a continuation of a commandi,(CX) so this
11094                  * sglq is on the active list
11095                  */
11096                 sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
11097                 if (!sglq)
11098                         return IOCB_ERROR;
11099         }
11100
11101         if (sglq) {
11102                 piocb->sli4_lxritag = sglq->sli4_lxritag;
11103                 piocb->sli4_xritag = sglq->sli4_xritag;
11104                 if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocb, sglq))
11105                         return IOCB_ERROR;
11106         }
11107
11108         if (lpfc_sli4_iocb2wqe(phba, piocb, &wqe))
11109                 return IOCB_ERROR;
11110
11111         if (lpfc_sli4_wq_put(wq, &wqe))
11112                 return IOCB_ERROR;
11113         lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
11114
11115         return 0;
11116 }
11117
11118 /*
11119  * lpfc_sli_issue_fcp_io - Wrapper func for issuing fcp i/o
11120  *
11121  * This routine wraps the actual fcp i/o function for issusing WQE for sli-4
11122  * or IOCB for sli-3  function.
11123  * pointer from the lpfc_hba struct.
11124  *
11125  * Return codes:
11126  * IOCB_ERROR - Error
11127  * IOCB_SUCCESS - Success
11128  * IOCB_BUSY - Busy
11129  **/
11130 int
11131 lpfc_sli_issue_fcp_io(struct lpfc_hba *phba, uint32_t ring_number,
11132                       struct lpfc_iocbq *piocb, uint32_t flag)
11133 {
11134         return phba->__lpfc_sli_issue_fcp_io(phba, ring_number, piocb, flag);
11135 }
11136
11137 /*
11138  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
11139  *
11140  * This routine wraps the actual lockless version for issusing IOCB function
11141  * pointer from the lpfc_hba struct.
11142  *
11143  * Return codes:
11144  * IOCB_ERROR - Error
11145  * IOCB_SUCCESS - Success
11146  * IOCB_BUSY - Busy
11147  **/
11148 int
11149 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
11150                 struct lpfc_iocbq *piocb, uint32_t flag)
11151 {
11152         return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11153 }
11154
11155 /**
11156  * lpfc_sli_api_table_setup - Set up sli api function jump table
11157  * @phba: The hba struct for which this call is being executed.
11158  * @dev_grp: The HBA PCI-Device group number.
11159  *
11160  * This routine sets up the SLI interface API function jump table in @phba
11161  * struct.
11162  * Returns: 0 - success, -ENODEV - failure.
11163  **/
11164 int
11165 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
11166 {
11167
11168         switch (dev_grp) {
11169         case LPFC_PCI_DEV_LP:
11170                 phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
11171                 phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
11172                 phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s3;
11173                 break;
11174         case LPFC_PCI_DEV_OC:
11175                 phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
11176                 phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
11177                 phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s4;
11178                 break;
11179         default:
11180                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11181                                 "1419 Invalid HBA PCI-device group: 0x%x\n",
11182                                 dev_grp);
11183                 return -ENODEV;
11184         }
11185         phba->lpfc_get_iocb_from_iocbq = lpfc_get_iocb_from_iocbq;
11186         return 0;
11187 }
11188
11189 /**
11190  * lpfc_sli4_calc_ring - Calculates which ring to use
11191  * @phba: Pointer to HBA context object.
11192  * @piocb: Pointer to command iocb.
11193  *
11194  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
11195  * hba_wqidx, thus we need to calculate the corresponding ring.
11196  * Since ABORTS must go on the same WQ of the command they are
11197  * aborting, we use command's hba_wqidx.
11198  */
11199 struct lpfc_sli_ring *
11200 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
11201 {
11202         struct lpfc_io_buf *lpfc_cmd;
11203
11204         if (piocb->iocb_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
11205                 if (unlikely(!phba->sli4_hba.hdwq))
11206                         return NULL;
11207                 /*
11208                  * for abort iocb hba_wqidx should already
11209                  * be setup based on what work queue we used.
11210                  */
11211                 if (!(piocb->iocb_flag & LPFC_USE_FCPWQIDX)) {
11212                         lpfc_cmd = (struct lpfc_io_buf *)piocb->context1;
11213                         piocb->hba_wqidx = lpfc_cmd->hdwq_no;
11214                 }
11215                 return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
11216         } else {
11217                 if (unlikely(!phba->sli4_hba.els_wq))
11218                         return NULL;
11219                 piocb->hba_wqidx = 0;
11220                 return phba->sli4_hba.els_wq->pring;
11221         }
11222 }
11223
11224 /**
11225  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
11226  * @phba: Pointer to HBA context object.
11227  * @ring_number: Ring number
11228  * @piocb: Pointer to command iocb.
11229  * @flag: Flag indicating if this command can be put into txq.
11230  *
11231  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
11232  * function. This function gets the hbalock and calls
11233  * __lpfc_sli_issue_iocb function and will return the error returned
11234  * by __lpfc_sli_issue_iocb function. This wrapper is used by
11235  * functions which do not hold hbalock.
11236  **/
11237 int
11238 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
11239                     struct lpfc_iocbq *piocb, uint32_t flag)
11240 {
11241         struct lpfc_sli_ring *pring;
11242         struct lpfc_queue *eq;
11243         unsigned long iflags;
11244         int rc;
11245
11246         if (phba->sli_rev == LPFC_SLI_REV4) {
11247                 eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
11248
11249                 pring = lpfc_sli4_calc_ring(phba, piocb);
11250                 if (unlikely(pring == NULL))
11251                         return IOCB_ERROR;
11252
11253                 spin_lock_irqsave(&pring->ring_lock, iflags);
11254                 rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11255                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
11256
11257                 lpfc_sli4_poll_eq(eq, LPFC_POLL_FASTPATH);
11258         } else {
11259                 /* For now, SLI2/3 will still use hbalock */
11260                 spin_lock_irqsave(&phba->hbalock, iflags);
11261                 rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11262                 spin_unlock_irqrestore(&phba->hbalock, iflags);
11263         }
11264         return rc;
11265 }
11266
11267 /**
11268  * lpfc_extra_ring_setup - Extra ring setup function
11269  * @phba: Pointer to HBA context object.
11270  *
11271  * This function is called while driver attaches with the
11272  * HBA to setup the extra ring. The extra ring is used
11273  * only when driver needs to support target mode functionality
11274  * or IP over FC functionalities.
11275  *
11276  * This function is called with no lock held. SLI3 only.
11277  **/
11278 static int
11279 lpfc_extra_ring_setup( struct lpfc_hba *phba)
11280 {
11281         struct lpfc_sli *psli;
11282         struct lpfc_sli_ring *pring;
11283
11284         psli = &phba->sli;
11285
11286         /* Adjust cmd/rsp ring iocb entries more evenly */
11287
11288         /* Take some away from the FCP ring */
11289         pring = &psli->sli3_ring[LPFC_FCP_RING];
11290         pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11291         pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11292         pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11293         pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11294
11295         /* and give them to the extra ring */
11296         pring = &psli->sli3_ring[LPFC_EXTRA_RING];
11297
11298         pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11299         pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11300         pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11301         pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11302
11303         /* Setup default profile for this ring */
11304         pring->iotag_max = 4096;
11305         pring->num_mask = 1;
11306         pring->prt[0].profile = 0;      /* Mask 0 */
11307         pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
11308         pring->prt[0].type = phba->cfg_multi_ring_type;
11309         pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
11310         return 0;
11311 }
11312
11313 static void
11314 lpfc_sli_post_recovery_event(struct lpfc_hba *phba,
11315                              struct lpfc_nodelist *ndlp)
11316 {
11317         unsigned long iflags;
11318         struct lpfc_work_evt  *evtp = &ndlp->recovery_evt;
11319
11320         spin_lock_irqsave(&phba->hbalock, iflags);
11321         if (!list_empty(&evtp->evt_listp)) {
11322                 spin_unlock_irqrestore(&phba->hbalock, iflags);
11323                 return;
11324         }
11325
11326         /* Incrementing the reference count until the queued work is done. */
11327         evtp->evt_arg1  = lpfc_nlp_get(ndlp);
11328         if (!evtp->evt_arg1) {
11329                 spin_unlock_irqrestore(&phba->hbalock, iflags);
11330                 return;
11331         }
11332         evtp->evt = LPFC_EVT_RECOVER_PORT;
11333         list_add_tail(&evtp->evt_listp, &phba->work_list);
11334         spin_unlock_irqrestore(&phba->hbalock, iflags);
11335
11336         lpfc_worker_wake_up(phba);
11337 }
11338
11339 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
11340  * @phba: Pointer to HBA context object.
11341  * @iocbq: Pointer to iocb object.
11342  *
11343  * The async_event handler calls this routine when it receives
11344  * an ASYNC_STATUS_CN event from the port.  The port generates
11345  * this event when an Abort Sequence request to an rport fails
11346  * twice in succession.  The abort could be originated by the
11347  * driver or by the port.  The ABTS could have been for an ELS
11348  * or FCP IO.  The port only generates this event when an ABTS
11349  * fails to complete after one retry.
11350  */
11351 static void
11352 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
11353                           struct lpfc_iocbq *iocbq)
11354 {
11355         struct lpfc_nodelist *ndlp = NULL;
11356         uint16_t rpi = 0, vpi = 0;
11357         struct lpfc_vport *vport = NULL;
11358
11359         /* The rpi in the ulpContext is vport-sensitive. */
11360         vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
11361         rpi = iocbq->iocb.ulpContext;
11362
11363         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11364                         "3092 Port generated ABTS async event "
11365                         "on vpi %d rpi %d status 0x%x\n",
11366                         vpi, rpi, iocbq->iocb.ulpStatus);
11367
11368         vport = lpfc_find_vport_by_vpid(phba, vpi);
11369         if (!vport)
11370                 goto err_exit;
11371         ndlp = lpfc_findnode_rpi(vport, rpi);
11372         if (!ndlp)
11373                 goto err_exit;
11374
11375         if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
11376                 lpfc_sli_abts_recover_port(vport, ndlp);
11377         return;
11378
11379  err_exit:
11380         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11381                         "3095 Event Context not found, no "
11382                         "action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
11383                         iocbq->iocb.ulpContext, iocbq->iocb.ulpStatus,
11384                         vpi, rpi);
11385 }
11386
11387 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
11388  * @phba: pointer to HBA context object.
11389  * @ndlp: nodelist pointer for the impacted rport.
11390  * @axri: pointer to the wcqe containing the failed exchange.
11391  *
11392  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
11393  * port.  The port generates this event when an abort exchange request to an
11394  * rport fails twice in succession with no reply.  The abort could be originated
11395  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
11396  */
11397 void
11398 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
11399                            struct lpfc_nodelist *ndlp,
11400                            struct sli4_wcqe_xri_aborted *axri)
11401 {
11402         uint32_t ext_status = 0;
11403
11404         if (!ndlp) {
11405                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11406                                 "3115 Node Context not found, driver "
11407                                 "ignoring abts err event\n");
11408                 return;
11409         }
11410
11411         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11412                         "3116 Port generated FCP XRI ABORT event on "
11413                         "vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
11414                         ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
11415                         bf_get(lpfc_wcqe_xa_xri, axri),
11416                         bf_get(lpfc_wcqe_xa_status, axri),
11417                         axri->parameter);
11418
11419         /*
11420          * Catch the ABTS protocol failure case.  Older OCe FW releases returned
11421          * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
11422          * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
11423          */
11424         ext_status = axri->parameter & IOERR_PARAM_MASK;
11425         if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
11426             ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
11427                 lpfc_sli_post_recovery_event(phba, ndlp);
11428 }
11429
11430 /**
11431  * lpfc_sli_async_event_handler - ASYNC iocb handler function
11432  * @phba: Pointer to HBA context object.
11433  * @pring: Pointer to driver SLI ring object.
11434  * @iocbq: Pointer to iocb object.
11435  *
11436  * This function is called by the slow ring event handler
11437  * function when there is an ASYNC event iocb in the ring.
11438  * This function is called with no lock held.
11439  * Currently this function handles only temperature related
11440  * ASYNC events. The function decodes the temperature sensor
11441  * event message and posts events for the management applications.
11442  **/
11443 static void
11444 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
11445         struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
11446 {
11447         IOCB_t *icmd;
11448         uint16_t evt_code;
11449         struct temp_event temp_event_data;
11450         struct Scsi_Host *shost;
11451         uint32_t *iocb_w;
11452
11453         icmd = &iocbq->iocb;
11454         evt_code = icmd->un.asyncstat.evt_code;
11455
11456         switch (evt_code) {
11457         case ASYNC_TEMP_WARN:
11458         case ASYNC_TEMP_SAFE:
11459                 temp_event_data.data = (uint32_t) icmd->ulpContext;
11460                 temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
11461                 if (evt_code == ASYNC_TEMP_WARN) {
11462                         temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
11463                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11464                                 "0347 Adapter is very hot, please take "
11465                                 "corrective action. temperature : %d Celsius\n",
11466                                 (uint32_t) icmd->ulpContext);
11467                 } else {
11468                         temp_event_data.event_code = LPFC_NORMAL_TEMP;
11469                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11470                                 "0340 Adapter temperature is OK now. "
11471                                 "temperature : %d Celsius\n",
11472                                 (uint32_t) icmd->ulpContext);
11473                 }
11474
11475                 /* Send temperature change event to applications */
11476                 shost = lpfc_shost_from_vport(phba->pport);
11477                 fc_host_post_vendor_event(shost, fc_get_event_number(),
11478                         sizeof(temp_event_data), (char *) &temp_event_data,
11479                         LPFC_NL_VENDOR_ID);
11480                 break;
11481         case ASYNC_STATUS_CN:
11482                 lpfc_sli_abts_err_handler(phba, iocbq);
11483                 break;
11484         default:
11485                 iocb_w = (uint32_t *) icmd;
11486                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11487                         "0346 Ring %d handler: unexpected ASYNC_STATUS"
11488                         " evt_code 0x%x\n"
11489                         "W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
11490                         "W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
11491                         "W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
11492                         "W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
11493                         pring->ringno, icmd->un.asyncstat.evt_code,
11494                         iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
11495                         iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
11496                         iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
11497                         iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
11498
11499                 break;
11500         }
11501 }
11502
11503
11504 /**
11505  * lpfc_sli4_setup - SLI ring setup function
11506  * @phba: Pointer to HBA context object.
11507  *
11508  * lpfc_sli_setup sets up rings of the SLI interface with
11509  * number of iocbs per ring and iotags. This function is
11510  * called while driver attach to the HBA and before the
11511  * interrupts are enabled. So there is no need for locking.
11512  *
11513  * This function always returns 0.
11514  **/
11515 int
11516 lpfc_sli4_setup(struct lpfc_hba *phba)
11517 {
11518         struct lpfc_sli_ring *pring;
11519
11520         pring = phba->sli4_hba.els_wq->pring;
11521         pring->num_mask = LPFC_MAX_RING_MASK;
11522         pring->prt[0].profile = 0;      /* Mask 0 */
11523         pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11524         pring->prt[0].type = FC_TYPE_ELS;
11525         pring->prt[0].lpfc_sli_rcv_unsol_event =
11526             lpfc_els_unsol_event;
11527         pring->prt[1].profile = 0;      /* Mask 1 */
11528         pring->prt[1].rctl = FC_RCTL_ELS_REP;
11529         pring->prt[1].type = FC_TYPE_ELS;
11530         pring->prt[1].lpfc_sli_rcv_unsol_event =
11531             lpfc_els_unsol_event;
11532         pring->prt[2].profile = 0;      /* Mask 2 */
11533         /* NameServer Inquiry */
11534         pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11535         /* NameServer */
11536         pring->prt[2].type = FC_TYPE_CT;
11537         pring->prt[2].lpfc_sli_rcv_unsol_event =
11538             lpfc_ct_unsol_event;
11539         pring->prt[3].profile = 0;      /* Mask 3 */
11540         /* NameServer response */
11541         pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11542         /* NameServer */
11543         pring->prt[3].type = FC_TYPE_CT;
11544         pring->prt[3].lpfc_sli_rcv_unsol_event =
11545             lpfc_ct_unsol_event;
11546         return 0;
11547 }
11548
11549 /**
11550  * lpfc_sli_setup - SLI ring setup function
11551  * @phba: Pointer to HBA context object.
11552  *
11553  * lpfc_sli_setup sets up rings of the SLI interface with
11554  * number of iocbs per ring and iotags. This function is
11555  * called while driver attach to the HBA and before the
11556  * interrupts are enabled. So there is no need for locking.
11557  *
11558  * This function always returns 0. SLI3 only.
11559  **/
11560 int
11561 lpfc_sli_setup(struct lpfc_hba *phba)
11562 {
11563         int i, totiocbsize = 0;
11564         struct lpfc_sli *psli = &phba->sli;
11565         struct lpfc_sli_ring *pring;
11566
11567         psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
11568         psli->sli_flag = 0;
11569
11570         psli->iocbq_lookup = NULL;
11571         psli->iocbq_lookup_len = 0;
11572         psli->last_iotag = 0;
11573
11574         for (i = 0; i < psli->num_rings; i++) {
11575                 pring = &psli->sli3_ring[i];
11576                 switch (i) {
11577                 case LPFC_FCP_RING:     /* ring 0 - FCP */
11578                         /* numCiocb and numRiocb are used in config_port */
11579                         pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
11580                         pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
11581                         pring->sli.sli3.numCiocb +=
11582                                 SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11583                         pring->sli.sli3.numRiocb +=
11584                                 SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11585                         pring->sli.sli3.numCiocb +=
11586                                 SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11587                         pring->sli.sli3.numRiocb +=
11588                                 SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11589                         pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11590                                                         SLI3_IOCB_CMD_SIZE :
11591                                                         SLI2_IOCB_CMD_SIZE;
11592                         pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11593                                                         SLI3_IOCB_RSP_SIZE :
11594                                                         SLI2_IOCB_RSP_SIZE;
11595                         pring->iotag_ctr = 0;
11596                         pring->iotag_max =
11597                             (phba->cfg_hba_queue_depth * 2);
11598                         pring->fast_iotag = pring->iotag_max;
11599                         pring->num_mask = 0;
11600                         break;
11601                 case LPFC_EXTRA_RING:   /* ring 1 - EXTRA */
11602                         /* numCiocb and numRiocb are used in config_port */
11603                         pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
11604                         pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
11605                         pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11606                                                         SLI3_IOCB_CMD_SIZE :
11607                                                         SLI2_IOCB_CMD_SIZE;
11608                         pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11609                                                         SLI3_IOCB_RSP_SIZE :
11610                                                         SLI2_IOCB_RSP_SIZE;
11611                         pring->iotag_max = phba->cfg_hba_queue_depth;
11612                         pring->num_mask = 0;
11613                         break;
11614                 case LPFC_ELS_RING:     /* ring 2 - ELS / CT */
11615                         /* numCiocb and numRiocb are used in config_port */
11616                         pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
11617                         pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
11618                         pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11619                                                         SLI3_IOCB_CMD_SIZE :
11620                                                         SLI2_IOCB_CMD_SIZE;
11621                         pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11622                                                         SLI3_IOCB_RSP_SIZE :
11623                                                         SLI2_IOCB_RSP_SIZE;
11624                         pring->fast_iotag = 0;
11625                         pring->iotag_ctr = 0;
11626                         pring->iotag_max = 4096;
11627                         pring->lpfc_sli_rcv_async_status =
11628                                 lpfc_sli_async_event_handler;
11629                         pring->num_mask = LPFC_MAX_RING_MASK;
11630                         pring->prt[0].profile = 0;      /* Mask 0 */
11631                         pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11632                         pring->prt[0].type = FC_TYPE_ELS;
11633                         pring->prt[0].lpfc_sli_rcv_unsol_event =
11634                             lpfc_els_unsol_event;
11635                         pring->prt[1].profile = 0;      /* Mask 1 */
11636                         pring->prt[1].rctl = FC_RCTL_ELS_REP;
11637                         pring->prt[1].type = FC_TYPE_ELS;
11638                         pring->prt[1].lpfc_sli_rcv_unsol_event =
11639                             lpfc_els_unsol_event;
11640                         pring->prt[2].profile = 0;      /* Mask 2 */
11641                         /* NameServer Inquiry */
11642                         pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11643                         /* NameServer */
11644                         pring->prt[2].type = FC_TYPE_CT;
11645                         pring->prt[2].lpfc_sli_rcv_unsol_event =
11646                             lpfc_ct_unsol_event;
11647                         pring->prt[3].profile = 0;      /* Mask 3 */
11648                         /* NameServer response */
11649                         pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11650                         /* NameServer */
11651                         pring->prt[3].type = FC_TYPE_CT;
11652                         pring->prt[3].lpfc_sli_rcv_unsol_event =
11653                             lpfc_ct_unsol_event;
11654                         break;
11655                 }
11656                 totiocbsize += (pring->sli.sli3.numCiocb *
11657                         pring->sli.sli3.sizeCiocb) +
11658                         (pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
11659         }
11660         if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
11661                 /* Too many cmd / rsp ring entries in SLI2 SLIM */
11662                 printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
11663                        "SLI2 SLIM Data: x%x x%lx\n",
11664                        phba->brd_no, totiocbsize,
11665                        (unsigned long) MAX_SLIM_IOCB_SIZE);
11666         }
11667         if (phba->cfg_multi_ring_support == 2)
11668                 lpfc_extra_ring_setup(phba);
11669
11670         return 0;
11671 }
11672
11673 /**
11674  * lpfc_sli4_queue_init - Queue initialization function
11675  * @phba: Pointer to HBA context object.
11676  *
11677  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
11678  * ring. This function also initializes ring indices of each ring.
11679  * This function is called during the initialization of the SLI
11680  * interface of an HBA.
11681  * This function is called with no lock held and always returns
11682  * 1.
11683  **/
11684 void
11685 lpfc_sli4_queue_init(struct lpfc_hba *phba)
11686 {
11687         struct lpfc_sli *psli;
11688         struct lpfc_sli_ring *pring;
11689         int i;
11690
11691         psli = &phba->sli;
11692         spin_lock_irq(&phba->hbalock);
11693         INIT_LIST_HEAD(&psli->mboxq);
11694         INIT_LIST_HEAD(&psli->mboxq_cmpl);
11695         /* Initialize list headers for txq and txcmplq as double linked lists */
11696         for (i = 0; i < phba->cfg_hdw_queue; i++) {
11697                 pring = phba->sli4_hba.hdwq[i].io_wq->pring;
11698                 pring->flag = 0;
11699                 pring->ringno = LPFC_FCP_RING;
11700                 pring->txcmplq_cnt = 0;
11701                 INIT_LIST_HEAD(&pring->txq);
11702                 INIT_LIST_HEAD(&pring->txcmplq);
11703                 INIT_LIST_HEAD(&pring->iocb_continueq);
11704                 spin_lock_init(&pring->ring_lock);
11705         }
11706         pring = phba->sli4_hba.els_wq->pring;
11707         pring->flag = 0;
11708         pring->ringno = LPFC_ELS_RING;
11709         pring->txcmplq_cnt = 0;
11710         INIT_LIST_HEAD(&pring->txq);
11711         INIT_LIST_HEAD(&pring->txcmplq);
11712         INIT_LIST_HEAD(&pring->iocb_continueq);
11713         spin_lock_init(&pring->ring_lock);
11714
11715         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11716                 pring = phba->sli4_hba.nvmels_wq->pring;
11717                 pring->flag = 0;
11718                 pring->ringno = LPFC_ELS_RING;
11719                 pring->txcmplq_cnt = 0;
11720                 INIT_LIST_HEAD(&pring->txq);
11721                 INIT_LIST_HEAD(&pring->txcmplq);
11722                 INIT_LIST_HEAD(&pring->iocb_continueq);
11723                 spin_lock_init(&pring->ring_lock);
11724         }
11725
11726         spin_unlock_irq(&phba->hbalock);
11727 }
11728
11729 /**
11730  * lpfc_sli_queue_init - Queue initialization function
11731  * @phba: Pointer to HBA context object.
11732  *
11733  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
11734  * ring. This function also initializes ring indices of each ring.
11735  * This function is called during the initialization of the SLI
11736  * interface of an HBA.
11737  * This function is called with no lock held and always returns
11738  * 1.
11739  **/
11740 void
11741 lpfc_sli_queue_init(struct lpfc_hba *phba)
11742 {
11743         struct lpfc_sli *psli;
11744         struct lpfc_sli_ring *pring;
11745         int i;
11746
11747         psli = &phba->sli;
11748         spin_lock_irq(&phba->hbalock);
11749         INIT_LIST_HEAD(&psli->mboxq);
11750         INIT_LIST_HEAD(&psli->mboxq_cmpl);
11751         /* Initialize list headers for txq and txcmplq as double linked lists */
11752         for (i = 0; i < psli->num_rings; i++) {
11753                 pring = &psli->sli3_ring[i];
11754                 pring->ringno = i;
11755                 pring->sli.sli3.next_cmdidx  = 0;
11756                 pring->sli.sli3.local_getidx = 0;
11757                 pring->sli.sli3.cmdidx = 0;
11758                 INIT_LIST_HEAD(&pring->iocb_continueq);
11759                 INIT_LIST_HEAD(&pring->iocb_continue_saveq);
11760                 INIT_LIST_HEAD(&pring->postbufq);
11761                 pring->flag = 0;
11762                 INIT_LIST_HEAD(&pring->txq);
11763                 INIT_LIST_HEAD(&pring->txcmplq);
11764                 spin_lock_init(&pring->ring_lock);
11765         }
11766         spin_unlock_irq(&phba->hbalock);
11767 }
11768
11769 /**
11770  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
11771  * @phba: Pointer to HBA context object.
11772  *
11773  * This routine flushes the mailbox command subsystem. It will unconditionally
11774  * flush all the mailbox commands in the three possible stages in the mailbox
11775  * command sub-system: pending mailbox command queue; the outstanding mailbox
11776  * command; and completed mailbox command queue. It is caller's responsibility
11777  * to make sure that the driver is in the proper state to flush the mailbox
11778  * command sub-system. Namely, the posting of mailbox commands into the
11779  * pending mailbox command queue from the various clients must be stopped;
11780  * either the HBA is in a state that it will never works on the outstanding
11781  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
11782  * mailbox command has been completed.
11783  **/
11784 static void
11785 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
11786 {
11787         LIST_HEAD(completions);
11788         struct lpfc_sli *psli = &phba->sli;
11789         LPFC_MBOXQ_t *pmb;
11790         unsigned long iflag;
11791
11792         /* Disable softirqs, including timers from obtaining phba->hbalock */
11793         local_bh_disable();
11794
11795         /* Flush all the mailbox commands in the mbox system */
11796         spin_lock_irqsave(&phba->hbalock, iflag);
11797
11798         /* The pending mailbox command queue */
11799         list_splice_init(&phba->sli.mboxq, &completions);
11800         /* The outstanding active mailbox command */
11801         if (psli->mbox_active) {
11802                 list_add_tail(&psli->mbox_active->list, &completions);
11803                 psli->mbox_active = NULL;
11804                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11805         }
11806         /* The completed mailbox command queue */
11807         list_splice_init(&phba->sli.mboxq_cmpl, &completions);
11808         spin_unlock_irqrestore(&phba->hbalock, iflag);
11809
11810         /* Enable softirqs again, done with phba->hbalock */
11811         local_bh_enable();
11812
11813         /* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
11814         while (!list_empty(&completions)) {
11815                 list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
11816                 pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
11817                 if (pmb->mbox_cmpl)
11818                         pmb->mbox_cmpl(phba, pmb);
11819         }
11820 }
11821
11822 /**
11823  * lpfc_sli_host_down - Vport cleanup function
11824  * @vport: Pointer to virtual port object.
11825  *
11826  * lpfc_sli_host_down is called to clean up the resources
11827  * associated with a vport before destroying virtual
11828  * port data structures.
11829  * This function does following operations:
11830  * - Free discovery resources associated with this virtual
11831  *   port.
11832  * - Free iocbs associated with this virtual port in
11833  *   the txq.
11834  * - Send abort for all iocb commands associated with this
11835  *   vport in txcmplq.
11836  *
11837  * This function is called with no lock held and always returns 1.
11838  **/
11839 int
11840 lpfc_sli_host_down(struct lpfc_vport *vport)
11841 {
11842         LIST_HEAD(completions);
11843         struct lpfc_hba *phba = vport->phba;
11844         struct lpfc_sli *psli = &phba->sli;
11845         struct lpfc_queue *qp = NULL;
11846         struct lpfc_sli_ring *pring;
11847         struct lpfc_iocbq *iocb, *next_iocb;
11848         int i;
11849         unsigned long flags = 0;
11850         uint16_t prev_pring_flag;
11851
11852         lpfc_cleanup_discovery_resources(vport);
11853
11854         spin_lock_irqsave(&phba->hbalock, flags);
11855
11856         /*
11857          * Error everything on the txq since these iocbs
11858          * have not been given to the FW yet.
11859          * Also issue ABTS for everything on the txcmplq
11860          */
11861         if (phba->sli_rev != LPFC_SLI_REV4) {
11862                 for (i = 0; i < psli->num_rings; i++) {
11863                         pring = &psli->sli3_ring[i];
11864                         prev_pring_flag = pring->flag;
11865                         /* Only slow rings */
11866                         if (pring->ringno == LPFC_ELS_RING) {
11867                                 pring->flag |= LPFC_DEFERRED_RING_EVENT;
11868                                 /* Set the lpfc data pending flag */
11869                                 set_bit(LPFC_DATA_READY, &phba->data_flags);
11870                         }
11871                         list_for_each_entry_safe(iocb, next_iocb,
11872                                                  &pring->txq, list) {
11873                                 if (iocb->vport != vport)
11874                                         continue;
11875                                 list_move_tail(&iocb->list, &completions);
11876                         }
11877                         list_for_each_entry_safe(iocb, next_iocb,
11878                                                  &pring->txcmplq, list) {
11879                                 if (iocb->vport != vport)
11880                                         continue;
11881                                 lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11882                                                            NULL);
11883                         }
11884                         pring->flag = prev_pring_flag;
11885                 }
11886         } else {
11887                 list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11888                         pring = qp->pring;
11889                         if (!pring)
11890                                 continue;
11891                         if (pring == phba->sli4_hba.els_wq->pring) {
11892                                 pring->flag |= LPFC_DEFERRED_RING_EVENT;
11893                                 /* Set the lpfc data pending flag */
11894                                 set_bit(LPFC_DATA_READY, &phba->data_flags);
11895                         }
11896                         prev_pring_flag = pring->flag;
11897                         spin_lock(&pring->ring_lock);
11898                         list_for_each_entry_safe(iocb, next_iocb,
11899                                                  &pring->txq, list) {
11900                                 if (iocb->vport != vport)
11901                                         continue;
11902                                 list_move_tail(&iocb->list, &completions);
11903                         }
11904                         spin_unlock(&pring->ring_lock);
11905                         list_for_each_entry_safe(iocb, next_iocb,
11906                                                  &pring->txcmplq, list) {
11907                                 if (iocb->vport != vport)
11908                                         continue;
11909                                 lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11910                                                            NULL);
11911                         }
11912                         pring->flag = prev_pring_flag;
11913                 }
11914         }
11915         spin_unlock_irqrestore(&phba->hbalock, flags);
11916
11917         /* Make sure HBA is alive */
11918         lpfc_issue_hb_tmo(phba);
11919
11920         /* Cancel all the IOCBs from the completions list */
11921         lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11922                               IOERR_SLI_DOWN);
11923         return 1;
11924 }
11925
11926 /**
11927  * lpfc_sli_hba_down - Resource cleanup function for the HBA
11928  * @phba: Pointer to HBA context object.
11929  *
11930  * This function cleans up all iocb, buffers, mailbox commands
11931  * while shutting down the HBA. This function is called with no
11932  * lock held and always returns 1.
11933  * This function does the following to cleanup driver resources:
11934  * - Free discovery resources for each virtual port
11935  * - Cleanup any pending fabric iocbs
11936  * - Iterate through the iocb txq and free each entry
11937  *   in the list.
11938  * - Free up any buffer posted to the HBA
11939  * - Free mailbox commands in the mailbox queue.
11940  **/
11941 int
11942 lpfc_sli_hba_down(struct lpfc_hba *phba)
11943 {
11944         LIST_HEAD(completions);
11945         struct lpfc_sli *psli = &phba->sli;
11946         struct lpfc_queue *qp = NULL;
11947         struct lpfc_sli_ring *pring;
11948         struct lpfc_dmabuf *buf_ptr;
11949         unsigned long flags = 0;
11950         int i;
11951
11952         /* Shutdown the mailbox command sub-system */
11953         lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
11954
11955         lpfc_hba_down_prep(phba);
11956
11957         /* Disable softirqs, including timers from obtaining phba->hbalock */
11958         local_bh_disable();
11959
11960         lpfc_fabric_abort_hba(phba);
11961
11962         spin_lock_irqsave(&phba->hbalock, flags);
11963
11964         /*
11965          * Error everything on the txq since these iocbs
11966          * have not been given to the FW yet.
11967          */
11968         if (phba->sli_rev != LPFC_SLI_REV4) {
11969                 for (i = 0; i < psli->num_rings; i++) {
11970                         pring = &psli->sli3_ring[i];
11971                         /* Only slow rings */
11972                         if (pring->ringno == LPFC_ELS_RING) {
11973                                 pring->flag |= LPFC_DEFERRED_RING_EVENT;
11974                                 /* Set the lpfc data pending flag */
11975                                 set_bit(LPFC_DATA_READY, &phba->data_flags);
11976                         }
11977                         list_splice_init(&pring->txq, &completions);
11978                 }
11979         } else {
11980                 list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11981                         pring = qp->pring;
11982                         if (!pring)
11983                                 continue;
11984                         spin_lock(&pring->ring_lock);
11985                         list_splice_init(&pring->txq, &completions);
11986                         spin_unlock(&pring->ring_lock);
11987                         if (pring == phba->sli4_hba.els_wq->pring) {
11988                                 pring->flag |= LPFC_DEFERRED_RING_EVENT;
11989                                 /* Set the lpfc data pending flag */
11990                                 set_bit(LPFC_DATA_READY, &phba->data_flags);
11991                         }
11992                 }
11993         }
11994         spin_unlock_irqrestore(&phba->hbalock, flags);
11995
11996         /* Cancel all the IOCBs from the completions list */
11997         lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11998                               IOERR_SLI_DOWN);
11999
12000         spin_lock_irqsave(&phba->hbalock, flags);
12001         list_splice_init(&phba->elsbuf, &completions);
12002         phba->elsbuf_cnt = 0;
12003         phba->elsbuf_prev_cnt = 0;
12004         spin_unlock_irqrestore(&phba->hbalock, flags);
12005
12006         while (!list_empty(&completions)) {
12007                 list_remove_head(&completions, buf_ptr,
12008                         struct lpfc_dmabuf, list);
12009                 lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
12010                 kfree(buf_ptr);
12011         }
12012
12013         /* Enable softirqs again, done with phba->hbalock */
12014         local_bh_enable();
12015
12016         /* Return any active mbox cmds */
12017         del_timer_sync(&psli->mbox_tmo);
12018
12019         spin_lock_irqsave(&phba->pport->work_port_lock, flags);
12020         phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
12021         spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
12022
12023         return 1;
12024 }
12025
12026 /**
12027  * lpfc_sli_pcimem_bcopy - SLI memory copy function
12028  * @srcp: Source memory pointer.
12029  * @destp: Destination memory pointer.
12030  * @cnt: Number of words required to be copied.
12031  *
12032  * This function is used for copying data between driver memory
12033  * and the SLI memory. This function also changes the endianness
12034  * of each word if native endianness is different from SLI
12035  * endianness. This function can be called with or without
12036  * lock.
12037  **/
12038 void
12039 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
12040 {
12041         uint32_t *src = srcp;
12042         uint32_t *dest = destp;
12043         uint32_t ldata;
12044         int i;
12045
12046         for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
12047                 ldata = *src;
12048                 ldata = le32_to_cpu(ldata);
12049                 *dest = ldata;
12050                 src++;
12051                 dest++;
12052         }
12053 }
12054
12055
12056 /**
12057  * lpfc_sli_bemem_bcopy - SLI memory copy function
12058  * @srcp: Source memory pointer.
12059  * @destp: Destination memory pointer.
12060  * @cnt: Number of words required to be copied.
12061  *
12062  * This function is used for copying data between a data structure
12063  * with big endian representation to local endianness.
12064  * This function can be called with or without lock.
12065  **/
12066 void
12067 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
12068 {
12069         uint32_t *src = srcp;
12070         uint32_t *dest = destp;
12071         uint32_t ldata;
12072         int i;
12073
12074         for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
12075                 ldata = *src;
12076                 ldata = be32_to_cpu(ldata);
12077                 *dest = ldata;
12078                 src++;
12079                 dest++;
12080         }
12081 }
12082
12083 /**
12084  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
12085  * @phba: Pointer to HBA context object.
12086  * @pring: Pointer to driver SLI ring object.
12087  * @mp: Pointer to driver buffer object.
12088  *
12089  * This function is called with no lock held.
12090  * It always return zero after adding the buffer to the postbufq
12091  * buffer list.
12092  **/
12093 int
12094 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12095                          struct lpfc_dmabuf *mp)
12096 {
12097         /* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
12098            later */
12099         spin_lock_irq(&phba->hbalock);
12100         list_add_tail(&mp->list, &pring->postbufq);
12101         pring->postbufq_cnt++;
12102         spin_unlock_irq(&phba->hbalock);
12103         return 0;
12104 }
12105
12106 /**
12107  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
12108  * @phba: Pointer to HBA context object.
12109  *
12110  * When HBQ is enabled, buffers are searched based on tags. This function
12111  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
12112  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
12113  * does not conflict with tags of buffer posted for unsolicited events.
12114  * The function returns the allocated tag. The function is called with
12115  * no locks held.
12116  **/
12117 uint32_t
12118 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
12119 {
12120         spin_lock_irq(&phba->hbalock);
12121         phba->buffer_tag_count++;
12122         /*
12123          * Always set the QUE_BUFTAG_BIT to distiguish between
12124          * a tag assigned by HBQ.
12125          */
12126         phba->buffer_tag_count |= QUE_BUFTAG_BIT;
12127         spin_unlock_irq(&phba->hbalock);
12128         return phba->buffer_tag_count;
12129 }
12130
12131 /**
12132  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
12133  * @phba: Pointer to HBA context object.
12134  * @pring: Pointer to driver SLI ring object.
12135  * @tag: Buffer tag.
12136  *
12137  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
12138  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
12139  * iocb is posted to the response ring with the tag of the buffer.
12140  * This function searches the pring->postbufq list using the tag
12141  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
12142  * iocb. If the buffer is found then lpfc_dmabuf object of the
12143  * buffer is returned to the caller else NULL is returned.
12144  * This function is called with no lock held.
12145  **/
12146 struct lpfc_dmabuf *
12147 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12148                         uint32_t tag)
12149 {
12150         struct lpfc_dmabuf *mp, *next_mp;
12151         struct list_head *slp = &pring->postbufq;
12152
12153         /* Search postbufq, from the beginning, looking for a match on tag */
12154         spin_lock_irq(&phba->hbalock);
12155         list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12156                 if (mp->buffer_tag == tag) {
12157                         list_del_init(&mp->list);
12158                         pring->postbufq_cnt--;
12159                         spin_unlock_irq(&phba->hbalock);
12160                         return mp;
12161                 }
12162         }
12163
12164         spin_unlock_irq(&phba->hbalock);
12165         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12166                         "0402 Cannot find virtual addr for buffer tag on "
12167                         "ring %d Data x%lx x%px x%px x%x\n",
12168                         pring->ringno, (unsigned long) tag,
12169                         slp->next, slp->prev, pring->postbufq_cnt);
12170
12171         return NULL;
12172 }
12173
12174 /**
12175  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
12176  * @phba: Pointer to HBA context object.
12177  * @pring: Pointer to driver SLI ring object.
12178  * @phys: DMA address of the buffer.
12179  *
12180  * This function searches the buffer list using the dma_address
12181  * of unsolicited event to find the driver's lpfc_dmabuf object
12182  * corresponding to the dma_address. The function returns the
12183  * lpfc_dmabuf object if a buffer is found else it returns NULL.
12184  * This function is called by the ct and els unsolicited event
12185  * handlers to get the buffer associated with the unsolicited
12186  * event.
12187  *
12188  * This function is called with no lock held.
12189  **/
12190 struct lpfc_dmabuf *
12191 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12192                          dma_addr_t phys)
12193 {
12194         struct lpfc_dmabuf *mp, *next_mp;
12195         struct list_head *slp = &pring->postbufq;
12196
12197         /* Search postbufq, from the beginning, looking for a match on phys */
12198         spin_lock_irq(&phba->hbalock);
12199         list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12200                 if (mp->phys == phys) {
12201                         list_del_init(&mp->list);
12202                         pring->postbufq_cnt--;
12203                         spin_unlock_irq(&phba->hbalock);
12204                         return mp;
12205                 }
12206         }
12207
12208         spin_unlock_irq(&phba->hbalock);
12209         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12210                         "0410 Cannot find virtual addr for mapped buf on "
12211                         "ring %d Data x%llx x%px x%px x%x\n",
12212                         pring->ringno, (unsigned long long)phys,
12213                         slp->next, slp->prev, pring->postbufq_cnt);
12214         return NULL;
12215 }
12216
12217 /**
12218  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
12219  * @phba: Pointer to HBA context object.
12220  * @cmdiocb: Pointer to driver command iocb object.
12221  * @rspiocb: Pointer to driver response iocb object.
12222  *
12223  * This function is the completion handler for the abort iocbs for
12224  * ELS commands. This function is called from the ELS ring event
12225  * handler with no lock held. This function frees memory resources
12226  * associated with the abort iocb.
12227  **/
12228 static void
12229 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12230                         struct lpfc_iocbq *rspiocb)
12231 {
12232         IOCB_t *irsp = &rspiocb->iocb;
12233         uint16_t abort_iotag, abort_context;
12234         struct lpfc_iocbq *abort_iocb = NULL;
12235
12236         if (irsp->ulpStatus) {
12237
12238                 /*
12239                  * Assume that the port already completed and returned, or
12240                  * will return the iocb. Just Log the message.
12241                  */
12242                 abort_context = cmdiocb->iocb.un.acxri.abortContextTag;
12243                 abort_iotag = cmdiocb->iocb.un.acxri.abortIoTag;
12244
12245                 spin_lock_irq(&phba->hbalock);
12246                 if (phba->sli_rev < LPFC_SLI_REV4) {
12247                         if (irsp->ulpCommand == CMD_ABORT_XRI_CX &&
12248                             irsp->ulpStatus == IOSTAT_LOCAL_REJECT &&
12249                             irsp->un.ulpWord[4] == IOERR_ABORT_REQUESTED) {
12250                                 spin_unlock_irq(&phba->hbalock);
12251                                 goto release_iocb;
12252                         }
12253                         if (abort_iotag != 0 &&
12254                                 abort_iotag <= phba->sli.last_iotag)
12255                                 abort_iocb =
12256                                         phba->sli.iocbq_lookup[abort_iotag];
12257                 } else
12258                         /* For sli4 the abort_tag is the XRI,
12259                          * so the abort routine puts the iotag  of the iocb
12260                          * being aborted in the context field of the abort
12261                          * IOCB.
12262                          */
12263                         abort_iocb = phba->sli.iocbq_lookup[abort_context];
12264
12265                 lpfc_printf_log(phba, KERN_WARNING, LOG_ELS | LOG_SLI,
12266                                 "0327 Cannot abort els iocb x%px "
12267                                 "with tag %x context %x, abort status %x, "
12268                                 "abort code %x\n",
12269                                 abort_iocb, abort_iotag, abort_context,
12270                                 irsp->ulpStatus, irsp->un.ulpWord[4]);
12271
12272                 spin_unlock_irq(&phba->hbalock);
12273         }
12274 release_iocb:
12275         lpfc_sli_release_iocbq(phba, cmdiocb);
12276         return;
12277 }
12278
12279 /**
12280  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
12281  * @phba: Pointer to HBA context object.
12282  * @cmdiocb: Pointer to driver command iocb object.
12283  * @rspiocb: Pointer to driver response iocb object.
12284  *
12285  * The function is called from SLI ring event handler with no
12286  * lock held. This function is the completion handler for ELS commands
12287  * which are aborted. The function frees memory resources used for
12288  * the aborted ELS commands.
12289  **/
12290 void
12291 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12292                      struct lpfc_iocbq *rspiocb)
12293 {
12294         struct lpfc_nodelist *ndlp = NULL;
12295         IOCB_t *irsp = &rspiocb->iocb;
12296
12297         /* ELS cmd tag <ulpIoTag> completes */
12298         lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
12299                         "0139 Ignoring ELS cmd code x%x completion Data: "
12300                         "x%x x%x x%x\n",
12301                         irsp->ulpIoTag, irsp->ulpStatus,
12302                         irsp->un.ulpWord[4], irsp->ulpTimeout);
12303         /*
12304          * Deref the ndlp after free_iocb. sli_release_iocb will access the ndlp
12305          * if exchange is busy.
12306          */
12307         if (cmdiocb->iocb.ulpCommand == CMD_GEN_REQUEST64_CR) {
12308                 ndlp = cmdiocb->context_un.ndlp;
12309                 lpfc_ct_free_iocb(phba, cmdiocb);
12310         } else {
12311                 ndlp = (struct lpfc_nodelist *) cmdiocb->context1;
12312                 lpfc_els_free_iocb(phba, cmdiocb);
12313         }
12314
12315         lpfc_nlp_put(ndlp);
12316 }
12317
12318 /**
12319  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
12320  * @phba: Pointer to HBA context object.
12321  * @pring: Pointer to driver SLI ring object.
12322  * @cmdiocb: Pointer to driver command iocb object.
12323  * @cmpl: completion function.
12324  *
12325  * This function issues an abort iocb for the provided command iocb. In case
12326  * of unloading, the abort iocb will not be issued to commands on the ELS
12327  * ring. Instead, the callback function shall be changed to those commands
12328  * so that nothing happens when them finishes. This function is called with
12329  * hbalock held andno ring_lock held (SLI4). The function returns IOCB_SUCCESS
12330  * when the command iocb is an abort request.
12331  *
12332  **/
12333 int
12334 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12335                            struct lpfc_iocbq *cmdiocb, void *cmpl)
12336 {
12337         struct lpfc_vport *vport = cmdiocb->vport;
12338         struct lpfc_iocbq *abtsiocbp;
12339         IOCB_t *icmd = NULL;
12340         IOCB_t *iabt = NULL;
12341         int retval = IOCB_ERROR;
12342         unsigned long iflags;
12343         struct lpfc_nodelist *ndlp;
12344
12345         /*
12346          * There are certain command types we don't want to abort.  And we
12347          * don't want to abort commands that are already in the process of
12348          * being aborted.
12349          */
12350         icmd = &cmdiocb->iocb;
12351         if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
12352             icmd->ulpCommand == CMD_CLOSE_XRI_CN ||
12353             cmdiocb->iocb_flag & LPFC_DRIVER_ABORTED)
12354                 return IOCB_ABORTING;
12355
12356         if (!pring) {
12357                 if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
12358                         cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
12359                 else
12360                         cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
12361                 return retval;
12362         }
12363
12364         /*
12365          * If we're unloading, don't abort iocb on the ELS ring, but change
12366          * the callback so that nothing happens when it finishes.
12367          */
12368         if ((vport->load_flag & FC_UNLOADING) &&
12369             pring->ringno == LPFC_ELS_RING) {
12370                 if (cmdiocb->iocb_flag & LPFC_IO_FABRIC)
12371                         cmdiocb->fabric_iocb_cmpl = lpfc_ignore_els_cmpl;
12372                 else
12373                         cmdiocb->iocb_cmpl = lpfc_ignore_els_cmpl;
12374                 return retval;
12375         }
12376
12377         /* issue ABTS for this IOCB based on iotag */
12378         abtsiocbp = __lpfc_sli_get_iocbq(phba);
12379         if (abtsiocbp == NULL)
12380                 return IOCB_NORESOURCE;
12381
12382         /* This signals the response to set the correct status
12383          * before calling the completion handler
12384          */
12385         cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
12386
12387         iabt = &abtsiocbp->iocb;
12388         iabt->un.acxri.abortType = ABORT_TYPE_ABTS;
12389         iabt->un.acxri.abortContextTag = icmd->ulpContext;
12390         if (phba->sli_rev == LPFC_SLI_REV4) {
12391                 iabt->un.acxri.abortIoTag = cmdiocb->sli4_xritag;
12392                 if (pring->ringno == LPFC_ELS_RING)
12393                         iabt->un.acxri.abortContextTag = cmdiocb->iotag;
12394         } else {
12395                 iabt->un.acxri.abortIoTag = icmd->ulpIoTag;
12396                 if (pring->ringno == LPFC_ELS_RING) {
12397                         ndlp = (struct lpfc_nodelist *)(cmdiocb->context1);
12398                         iabt->un.acxri.abortContextTag = ndlp->nlp_rpi;
12399                 }
12400         }
12401         iabt->ulpLe = 1;
12402         iabt->ulpClass = icmd->ulpClass;
12403
12404         /* ABTS WQE must go to the same WQ as the WQE to be aborted */
12405         abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
12406         if (cmdiocb->iocb_flag & LPFC_IO_FCP)
12407                 abtsiocbp->iocb_flag |= (LPFC_IO_FCP | LPFC_USE_FCPWQIDX);
12408         if (cmdiocb->iocb_flag & LPFC_IO_FOF)
12409                 abtsiocbp->iocb_flag |= LPFC_IO_FOF;
12410
12411         if (phba->link_state < LPFC_LINK_UP ||
12412             (phba->sli_rev == LPFC_SLI_REV4 &&
12413              phba->sli4_hba.link_state.status == LPFC_FC_LA_TYPE_LINK_DOWN))
12414                 iabt->ulpCommand = CMD_CLOSE_XRI_CN;
12415         else
12416                 iabt->ulpCommand = CMD_ABORT_XRI_CN;
12417
12418         if (cmpl)
12419                 abtsiocbp->iocb_cmpl = cmpl;
12420         else
12421                 abtsiocbp->iocb_cmpl = lpfc_sli_abort_els_cmpl;
12422         abtsiocbp->vport = vport;
12423
12424         if (phba->sli_rev == LPFC_SLI_REV4) {
12425                 pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
12426                 if (unlikely(pring == NULL))
12427                         goto abort_iotag_exit;
12428                 /* Note: both hbalock and ring_lock need to be set here */
12429                 spin_lock_irqsave(&pring->ring_lock, iflags);
12430                 retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12431                         abtsiocbp, 0);
12432                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
12433         } else {
12434                 retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12435                         abtsiocbp, 0);
12436         }
12437
12438 abort_iotag_exit:
12439
12440         lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
12441                          "0339 Abort xri x%x, original iotag x%x, "
12442                          "abort cmd iotag x%x retval x%x\n",
12443                          iabt->un.acxri.abortIoTag,
12444                          iabt->un.acxri.abortContextTag,
12445                          abtsiocbp->iotag, retval);
12446
12447         if (retval) {
12448                 cmdiocb->iocb_flag &= ~LPFC_DRIVER_ABORTED;
12449                 __lpfc_sli_release_iocbq(phba, abtsiocbp);
12450         }
12451
12452         /*
12453          * Caller to this routine should check for IOCB_ERROR
12454          * and handle it properly.  This routine no longer removes
12455          * iocb off txcmplq and call compl in case of IOCB_ERROR.
12456          */
12457         return retval;
12458 }
12459
12460 /**
12461  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
12462  * @phba: pointer to lpfc HBA data structure.
12463  *
12464  * This routine will abort all pending and outstanding iocbs to an HBA.
12465  **/
12466 void
12467 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
12468 {
12469         struct lpfc_sli *psli = &phba->sli;
12470         struct lpfc_sli_ring *pring;
12471         struct lpfc_queue *qp = NULL;
12472         int i;
12473
12474         if (phba->sli_rev != LPFC_SLI_REV4) {
12475                 for (i = 0; i < psli->num_rings; i++) {
12476                         pring = &psli->sli3_ring[i];
12477                         lpfc_sli_abort_iocb_ring(phba, pring);
12478                 }
12479                 return;
12480         }
12481         list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12482                 pring = qp->pring;
12483                 if (!pring)
12484                         continue;
12485                 lpfc_sli_abort_iocb_ring(phba, pring);
12486         }
12487 }
12488
12489 /**
12490  * lpfc_sli_validate_fcp_iocb_for_abort - filter iocbs appropriate for FCP aborts
12491  * @iocbq: Pointer to iocb object.
12492  * @vport: Pointer to driver virtual port object.
12493  *
12494  * This function acts as an iocb filter for functions which abort FCP iocbs.
12495  *
12496  * Return values
12497  * -ENODEV, if a null iocb or vport ptr is encountered
12498  * -EINVAL, if the iocb is not an FCP I/O, not on the TX cmpl queue, premarked as
12499  *          driver already started the abort process, or is an abort iocb itself
12500  * 0, passes criteria for aborting the FCP I/O iocb
12501  **/
12502 static int
12503 lpfc_sli_validate_fcp_iocb_for_abort(struct lpfc_iocbq *iocbq,
12504                                      struct lpfc_vport *vport)
12505 {
12506         IOCB_t *icmd = NULL;
12507
12508         /* No null ptr vports */
12509         if (!iocbq || iocbq->vport != vport)
12510                 return -ENODEV;
12511
12512         /* iocb must be for FCP IO, already exists on the TX cmpl queue,
12513          * can't be premarked as driver aborted, nor be an ABORT iocb itself
12514          */
12515         icmd = &iocbq->iocb;
12516         if (!(iocbq->iocb_flag & LPFC_IO_FCP) ||
12517             !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ) ||
12518             (iocbq->iocb_flag & LPFC_DRIVER_ABORTED) ||
12519             (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
12520              icmd->ulpCommand == CMD_CLOSE_XRI_CN))
12521                 return -EINVAL;
12522
12523         return 0;
12524 }
12525
12526 /**
12527  * lpfc_sli_validate_fcp_iocb - validate commands associated with a SCSI target
12528  * @iocbq: Pointer to driver iocb object.
12529  * @vport: Pointer to driver virtual port object.
12530  * @tgt_id: SCSI ID of the target.
12531  * @lun_id: LUN ID of the scsi device.
12532  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
12533  *
12534  * This function acts as an iocb filter for validating a lun/SCSI target/SCSI
12535  * host.
12536  *
12537  * It will return
12538  * 0 if the filtering criteria is met for the given iocb and will return
12539  * 1 if the filtering criteria is not met.
12540  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
12541  * given iocb is for the SCSI device specified by vport, tgt_id and
12542  * lun_id parameter.
12543  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
12544  * given iocb is for the SCSI target specified by vport and tgt_id
12545  * parameters.
12546  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
12547  * given iocb is for the SCSI host associated with the given vport.
12548  * This function is called with no locks held.
12549  **/
12550 static int
12551 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
12552                            uint16_t tgt_id, uint64_t lun_id,
12553                            lpfc_ctx_cmd ctx_cmd)
12554 {
12555         struct lpfc_io_buf *lpfc_cmd;
12556         int rc = 1;
12557
12558         lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12559
12560         if (lpfc_cmd->pCmd == NULL)
12561                 return rc;
12562
12563         switch (ctx_cmd) {
12564         case LPFC_CTX_LUN:
12565                 if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12566                     (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
12567                     (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
12568                         rc = 0;
12569                 break;
12570         case LPFC_CTX_TGT:
12571                 if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12572                     (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
12573                         rc = 0;
12574                 break;
12575         case LPFC_CTX_HOST:
12576                 rc = 0;
12577                 break;
12578         default:
12579                 printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
12580                         __func__, ctx_cmd);
12581                 break;
12582         }
12583
12584         return rc;
12585 }
12586
12587 /**
12588  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
12589  * @vport: Pointer to virtual port.
12590  * @tgt_id: SCSI ID of the target.
12591  * @lun_id: LUN ID of the scsi device.
12592  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12593  *
12594  * This function returns number of FCP commands pending for the vport.
12595  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
12596  * commands pending on the vport associated with SCSI device specified
12597  * by tgt_id and lun_id parameters.
12598  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
12599  * commands pending on the vport associated with SCSI target specified
12600  * by tgt_id parameter.
12601  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
12602  * commands pending on the vport.
12603  * This function returns the number of iocbs which satisfy the filter.
12604  * This function is called without any lock held.
12605  **/
12606 int
12607 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
12608                   lpfc_ctx_cmd ctx_cmd)
12609 {
12610         struct lpfc_hba *phba = vport->phba;
12611         struct lpfc_iocbq *iocbq;
12612         IOCB_t *icmd = NULL;
12613         int sum, i;
12614         unsigned long iflags;
12615
12616         spin_lock_irqsave(&phba->hbalock, iflags);
12617         for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
12618                 iocbq = phba->sli.iocbq_lookup[i];
12619
12620                 if (!iocbq || iocbq->vport != vport)
12621                         continue;
12622                 if (!(iocbq->iocb_flag & LPFC_IO_FCP) ||
12623                     !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ))
12624                         continue;
12625
12626                 /* Include counting outstanding aborts */
12627                 icmd = &iocbq->iocb;
12628                 if (icmd->ulpCommand == CMD_ABORT_XRI_CN ||
12629                     icmd->ulpCommand == CMD_CLOSE_XRI_CN) {
12630                         sum++;
12631                         continue;
12632                 }
12633
12634                 if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12635                                                ctx_cmd) == 0)
12636                         sum++;
12637         }
12638         spin_unlock_irqrestore(&phba->hbalock, iflags);
12639
12640         return sum;
12641 }
12642
12643 /**
12644  * lpfc_sli4_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
12645  * @phba: Pointer to HBA context object
12646  * @cmdiocb: Pointer to command iocb object.
12647  * @wcqe: pointer to the complete wcqe
12648  *
12649  * This function is called when an aborted FCP iocb completes. This
12650  * function is called by the ring event handler with no lock held.
12651  * This function frees the iocb. It is called for sli-4 adapters.
12652  **/
12653 void
12654 lpfc_sli4_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12655                          struct lpfc_wcqe_complete *wcqe)
12656 {
12657         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12658                         "3017 ABORT_XRI_CN completing on rpi x%x "
12659                         "original iotag x%x, abort cmd iotag x%x "
12660                         "status 0x%x, reason 0x%x\n",
12661                         cmdiocb->iocb.un.acxri.abortContextTag,
12662                         cmdiocb->iocb.un.acxri.abortIoTag,
12663                         cmdiocb->iotag,
12664                         (bf_get(lpfc_wcqe_c_status, wcqe)
12665                         & LPFC_IOCB_STATUS_MASK),
12666                         wcqe->parameter);
12667         lpfc_sli_release_iocbq(phba, cmdiocb);
12668 }
12669
12670 /**
12671  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
12672  * @phba: Pointer to HBA context object
12673  * @cmdiocb: Pointer to command iocb object.
12674  * @rspiocb: Pointer to response iocb object.
12675  *
12676  * This function is called when an aborted FCP iocb completes. This
12677  * function is called by the ring event handler with no lock held.
12678  * This function frees the iocb.
12679  **/
12680 void
12681 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12682                         struct lpfc_iocbq *rspiocb)
12683 {
12684         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12685                         "3096 ABORT_XRI_CN completing on rpi x%x "
12686                         "original iotag x%x, abort cmd iotag x%x "
12687                         "status 0x%x, reason 0x%x\n",
12688                         cmdiocb->iocb.un.acxri.abortContextTag,
12689                         cmdiocb->iocb.un.acxri.abortIoTag,
12690                         cmdiocb->iotag, rspiocb->iocb.ulpStatus,
12691                         rspiocb->iocb.un.ulpWord[4]);
12692         lpfc_sli_release_iocbq(phba, cmdiocb);
12693         return;
12694 }
12695
12696 /**
12697  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
12698  * @vport: Pointer to virtual port.
12699  * @tgt_id: SCSI ID of the target.
12700  * @lun_id: LUN ID of the scsi device.
12701  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12702  *
12703  * This function sends an abort command for every SCSI command
12704  * associated with the given virtual port pending on the ring
12705  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12706  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12707  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12708  * followed by lpfc_sli_validate_fcp_iocb.
12709  *
12710  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
12711  * FCP iocbs associated with lun specified by tgt_id and lun_id
12712  * parameters
12713  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
12714  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12715  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
12716  * FCP iocbs associated with virtual port.
12717  * The pring used for SLI3 is sli3_ring[LPFC_FCP_RING], for SLI4
12718  * lpfc_sli4_calc_ring is used.
12719  * This function returns number of iocbs it failed to abort.
12720  * This function is called with no locks held.
12721  **/
12722 int
12723 lpfc_sli_abort_iocb(struct lpfc_vport *vport, u16 tgt_id, u64 lun_id,
12724                     lpfc_ctx_cmd abort_cmd)
12725 {
12726         struct lpfc_hba *phba = vport->phba;
12727         struct lpfc_sli_ring *pring = NULL;
12728         struct lpfc_iocbq *iocbq;
12729         int errcnt = 0, ret_val = 0;
12730         unsigned long iflags;
12731         int i;
12732         void *fcp_cmpl = NULL;
12733
12734         /* all I/Os are in process of being flushed */
12735         if (phba->hba_flag & HBA_IOQ_FLUSH)
12736                 return errcnt;
12737
12738         for (i = 1; i <= phba->sli.last_iotag; i++) {
12739                 iocbq = phba->sli.iocbq_lookup[i];
12740
12741                 if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12742                         continue;
12743
12744                 if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12745                                                abort_cmd) != 0)
12746                         continue;
12747
12748                 spin_lock_irqsave(&phba->hbalock, iflags);
12749                 if (phba->sli_rev == LPFC_SLI_REV3) {
12750                         pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12751                         fcp_cmpl = lpfc_sli_abort_fcp_cmpl;
12752                 } else if (phba->sli_rev == LPFC_SLI_REV4) {
12753                         pring = lpfc_sli4_calc_ring(phba, iocbq);
12754                         fcp_cmpl = lpfc_sli4_abort_fcp_cmpl;
12755                 }
12756                 ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocbq,
12757                                                      fcp_cmpl);
12758                 spin_unlock_irqrestore(&phba->hbalock, iflags);
12759                 if (ret_val != IOCB_SUCCESS)
12760                         errcnt++;
12761         }
12762
12763         return errcnt;
12764 }
12765
12766 /**
12767  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
12768  * @vport: Pointer to virtual port.
12769  * @pring: Pointer to driver SLI ring object.
12770  * @tgt_id: SCSI ID of the target.
12771  * @lun_id: LUN ID of the scsi device.
12772  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12773  *
12774  * This function sends an abort command for every SCSI command
12775  * associated with the given virtual port pending on the ring
12776  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12777  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12778  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12779  * followed by lpfc_sli_validate_fcp_iocb.
12780  *
12781  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
12782  * FCP iocbs associated with lun specified by tgt_id and lun_id
12783  * parameters
12784  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
12785  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12786  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
12787  * FCP iocbs associated with virtual port.
12788  * This function returns number of iocbs it aborted .
12789  * This function is called with no locks held right after a taskmgmt
12790  * command is sent.
12791  **/
12792 int
12793 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
12794                         uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
12795 {
12796         struct lpfc_hba *phba = vport->phba;
12797         struct lpfc_io_buf *lpfc_cmd;
12798         struct lpfc_iocbq *abtsiocbq;
12799         struct lpfc_nodelist *ndlp;
12800         struct lpfc_iocbq *iocbq;
12801         IOCB_t *icmd;
12802         int sum, i, ret_val;
12803         unsigned long iflags;
12804         struct lpfc_sli_ring *pring_s4 = NULL;
12805
12806         spin_lock_irqsave(&phba->hbalock, iflags);
12807
12808         /* all I/Os are in process of being flushed */
12809         if (phba->hba_flag & HBA_IOQ_FLUSH) {
12810                 spin_unlock_irqrestore(&phba->hbalock, iflags);
12811                 return 0;
12812         }
12813         sum = 0;
12814
12815         for (i = 1; i <= phba->sli.last_iotag; i++) {
12816                 iocbq = phba->sli.iocbq_lookup[i];
12817
12818                 if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12819                         continue;
12820
12821                 if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12822                                                cmd) != 0)
12823                         continue;
12824
12825                 /* Guard against IO completion being called at same time */
12826                 lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12827                 spin_lock(&lpfc_cmd->buf_lock);
12828
12829                 if (!lpfc_cmd->pCmd) {
12830                         spin_unlock(&lpfc_cmd->buf_lock);
12831                         continue;
12832                 }
12833
12834                 if (phba->sli_rev == LPFC_SLI_REV4) {
12835                         pring_s4 =
12836                             phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
12837                         if (!pring_s4) {
12838                                 spin_unlock(&lpfc_cmd->buf_lock);
12839                                 continue;
12840                         }
12841                         /* Note: both hbalock and ring_lock must be set here */
12842                         spin_lock(&pring_s4->ring_lock);
12843                 }
12844
12845                 /*
12846                  * If the iocbq is already being aborted, don't take a second
12847                  * action, but do count it.
12848                  */
12849                 if ((iocbq->iocb_flag & LPFC_DRIVER_ABORTED) ||
12850                     !(iocbq->iocb_flag & LPFC_IO_ON_TXCMPLQ)) {
12851                         if (phba->sli_rev == LPFC_SLI_REV4)
12852                                 spin_unlock(&pring_s4->ring_lock);
12853                         spin_unlock(&lpfc_cmd->buf_lock);
12854                         continue;
12855                 }
12856
12857                 /* issue ABTS for this IOCB based on iotag */
12858                 abtsiocbq = __lpfc_sli_get_iocbq(phba);
12859                 if (!abtsiocbq) {
12860                         if (phba->sli_rev == LPFC_SLI_REV4)
12861                                 spin_unlock(&pring_s4->ring_lock);
12862                         spin_unlock(&lpfc_cmd->buf_lock);
12863                         continue;
12864                 }
12865
12866                 icmd = &iocbq->iocb;
12867                 abtsiocbq->iocb.un.acxri.abortType = ABORT_TYPE_ABTS;
12868                 abtsiocbq->iocb.un.acxri.abortContextTag = icmd->ulpContext;
12869                 if (phba->sli_rev == LPFC_SLI_REV4)
12870                         abtsiocbq->iocb.un.acxri.abortIoTag =
12871                                                          iocbq->sli4_xritag;
12872                 else
12873                         abtsiocbq->iocb.un.acxri.abortIoTag = icmd->ulpIoTag;
12874                 abtsiocbq->iocb.ulpLe = 1;
12875                 abtsiocbq->iocb.ulpClass = icmd->ulpClass;
12876                 abtsiocbq->vport = vport;
12877
12878                 /* ABTS WQE must go to the same WQ as the WQE to be aborted */
12879                 abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
12880                 if (iocbq->iocb_flag & LPFC_IO_FCP)
12881                         abtsiocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
12882                 if (iocbq->iocb_flag & LPFC_IO_FOF)
12883                         abtsiocbq->iocb_flag |= LPFC_IO_FOF;
12884
12885                 ndlp = lpfc_cmd->rdata->pnode;
12886
12887                 if (lpfc_is_link_up(phba) &&
12888                     (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE))
12889                         abtsiocbq->iocb.ulpCommand = CMD_ABORT_XRI_CN;
12890                 else
12891                         abtsiocbq->iocb.ulpCommand = CMD_CLOSE_XRI_CN;
12892
12893                 /* Setup callback routine and issue the command. */
12894                 abtsiocbq->iocb_cmpl = lpfc_sli_abort_fcp_cmpl;
12895
12896                 /*
12897                  * Indicate the IO is being aborted by the driver and set
12898                  * the caller's flag into the aborted IO.
12899                  */
12900                 iocbq->iocb_flag |= LPFC_DRIVER_ABORTED;
12901
12902                 if (phba->sli_rev == LPFC_SLI_REV4) {
12903                         ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
12904                                                         abtsiocbq, 0);
12905                         spin_unlock(&pring_s4->ring_lock);
12906                 } else {
12907                         ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
12908                                                         abtsiocbq, 0);
12909                 }
12910
12911                 spin_unlock(&lpfc_cmd->buf_lock);
12912
12913                 if (ret_val == IOCB_ERROR)
12914                         __lpfc_sli_release_iocbq(phba, abtsiocbq);
12915                 else
12916                         sum++;
12917         }
12918         spin_unlock_irqrestore(&phba->hbalock, iflags);
12919         return sum;
12920 }
12921
12922 /**
12923  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
12924  * @phba: Pointer to HBA context object.
12925  * @cmdiocbq: Pointer to command iocb.
12926  * @rspiocbq: Pointer to response iocb.
12927  *
12928  * This function is the completion handler for iocbs issued using
12929  * lpfc_sli_issue_iocb_wait function. This function is called by the
12930  * ring event handler function without any lock held. This function
12931  * can be called from both worker thread context and interrupt
12932  * context. This function also can be called from other thread which
12933  * cleans up the SLI layer objects.
12934  * This function copy the contents of the response iocb to the
12935  * response iocb memory object provided by the caller of
12936  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
12937  * sleeps for the iocb completion.
12938  **/
12939 static void
12940 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
12941                         struct lpfc_iocbq *cmdiocbq,
12942                         struct lpfc_iocbq *rspiocbq)
12943 {
12944         wait_queue_head_t *pdone_q;
12945         unsigned long iflags;
12946         struct lpfc_io_buf *lpfc_cmd;
12947
12948         spin_lock_irqsave(&phba->hbalock, iflags);
12949         if (cmdiocbq->iocb_flag & LPFC_IO_WAKE_TMO) {
12950
12951                 /*
12952                  * A time out has occurred for the iocb.  If a time out
12953                  * completion handler has been supplied, call it.  Otherwise,
12954                  * just free the iocbq.
12955                  */
12956
12957                 spin_unlock_irqrestore(&phba->hbalock, iflags);
12958                 cmdiocbq->iocb_cmpl = cmdiocbq->wait_iocb_cmpl;
12959                 cmdiocbq->wait_iocb_cmpl = NULL;
12960                 if (cmdiocbq->iocb_cmpl)
12961                         (cmdiocbq->iocb_cmpl)(phba, cmdiocbq, NULL);
12962                 else
12963                         lpfc_sli_release_iocbq(phba, cmdiocbq);
12964                 return;
12965         }
12966
12967         cmdiocbq->iocb_flag |= LPFC_IO_WAKE;
12968         if (cmdiocbq->context2 && rspiocbq)
12969                 memcpy(&((struct lpfc_iocbq *)cmdiocbq->context2)->iocb,
12970                        &rspiocbq->iocb, sizeof(IOCB_t));
12971
12972         /* Set the exchange busy flag for task management commands */
12973         if ((cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
12974                 !(cmdiocbq->iocb_flag & LPFC_IO_LIBDFC)) {
12975                 lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
12976                         cur_iocbq);
12977                 if (rspiocbq && (rspiocbq->iocb_flag & LPFC_EXCHANGE_BUSY))
12978                         lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
12979                 else
12980                         lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
12981         }
12982
12983         pdone_q = cmdiocbq->context_un.wait_queue;
12984         if (pdone_q)
12985                 wake_up(pdone_q);
12986         spin_unlock_irqrestore(&phba->hbalock, iflags);
12987         return;
12988 }
12989
12990 /**
12991  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
12992  * @phba: Pointer to HBA context object..
12993  * @piocbq: Pointer to command iocb.
12994  * @flag: Flag to test.
12995  *
12996  * This routine grabs the hbalock and then test the iocb_flag to
12997  * see if the passed in flag is set.
12998  * Returns:
12999  * 1 if flag is set.
13000  * 0 if flag is not set.
13001  **/
13002 static int
13003 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
13004                  struct lpfc_iocbq *piocbq, uint32_t flag)
13005 {
13006         unsigned long iflags;
13007         int ret;
13008
13009         spin_lock_irqsave(&phba->hbalock, iflags);
13010         ret = piocbq->iocb_flag & flag;
13011         spin_unlock_irqrestore(&phba->hbalock, iflags);
13012         return ret;
13013
13014 }
13015
13016 /**
13017  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
13018  * @phba: Pointer to HBA context object..
13019  * @ring_number: Ring number
13020  * @piocb: Pointer to command iocb.
13021  * @prspiocbq: Pointer to response iocb.
13022  * @timeout: Timeout in number of seconds.
13023  *
13024  * This function issues the iocb to firmware and waits for the
13025  * iocb to complete. The iocb_cmpl field of the shall be used
13026  * to handle iocbs which time out. If the field is NULL, the
13027  * function shall free the iocbq structure.  If more clean up is
13028  * needed, the caller is expected to provide a completion function
13029  * that will provide the needed clean up.  If the iocb command is
13030  * not completed within timeout seconds, the function will either
13031  * free the iocbq structure (if iocb_cmpl == NULL) or execute the
13032  * completion function set in the iocb_cmpl field and then return
13033  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
13034  * resources if this function returns IOCB_TIMEDOUT.
13035  * The function waits for the iocb completion using an
13036  * non-interruptible wait.
13037  * This function will sleep while waiting for iocb completion.
13038  * So, this function should not be called from any context which
13039  * does not allow sleeping. Due to the same reason, this function
13040  * cannot be called with interrupt disabled.
13041  * This function assumes that the iocb completions occur while
13042  * this function sleep. So, this function cannot be called from
13043  * the thread which process iocb completion for this ring.
13044  * This function clears the iocb_flag of the iocb object before
13045  * issuing the iocb and the iocb completion handler sets this
13046  * flag and wakes this thread when the iocb completes.
13047  * The contents of the response iocb will be copied to prspiocbq
13048  * by the completion handler when the command completes.
13049  * This function returns IOCB_SUCCESS when success.
13050  * This function is called with no lock held.
13051  **/
13052 int
13053 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
13054                          uint32_t ring_number,
13055                          struct lpfc_iocbq *piocb,
13056                          struct lpfc_iocbq *prspiocbq,
13057                          uint32_t timeout)
13058 {
13059         DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
13060         long timeleft, timeout_req = 0;
13061         int retval = IOCB_SUCCESS;
13062         uint32_t creg_val;
13063         struct lpfc_iocbq *iocb;
13064         int txq_cnt = 0;
13065         int txcmplq_cnt = 0;
13066         struct lpfc_sli_ring *pring;
13067         unsigned long iflags;
13068         bool iocb_completed = true;
13069
13070         if (phba->sli_rev >= LPFC_SLI_REV4)
13071                 pring = lpfc_sli4_calc_ring(phba, piocb);
13072         else
13073                 pring = &phba->sli.sli3_ring[ring_number];
13074         /*
13075          * If the caller has provided a response iocbq buffer, then context2
13076          * is NULL or its an error.
13077          */
13078         if (prspiocbq) {
13079                 if (piocb->context2)
13080                         return IOCB_ERROR;
13081                 piocb->context2 = prspiocbq;
13082         }
13083
13084         piocb->wait_iocb_cmpl = piocb->iocb_cmpl;
13085         piocb->iocb_cmpl = lpfc_sli_wake_iocb_wait;
13086         piocb->context_un.wait_queue = &done_q;
13087         piocb->iocb_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
13088
13089         if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13090                 if (lpfc_readl(phba->HCregaddr, &creg_val))
13091                         return IOCB_ERROR;
13092                 creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
13093                 writel(creg_val, phba->HCregaddr);
13094                 readl(phba->HCregaddr); /* flush */
13095         }
13096
13097         retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
13098                                      SLI_IOCB_RET_IOCB);
13099         if (retval == IOCB_SUCCESS) {
13100                 timeout_req = msecs_to_jiffies(timeout * 1000);
13101                 timeleft = wait_event_timeout(done_q,
13102                                 lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
13103                                 timeout_req);
13104                 spin_lock_irqsave(&phba->hbalock, iflags);
13105                 if (!(piocb->iocb_flag & LPFC_IO_WAKE)) {
13106
13107                         /*
13108                          * IOCB timed out.  Inform the wake iocb wait
13109                          * completion function and set local status
13110                          */
13111
13112                         iocb_completed = false;
13113                         piocb->iocb_flag |= LPFC_IO_WAKE_TMO;
13114                 }
13115                 spin_unlock_irqrestore(&phba->hbalock, iflags);
13116                 if (iocb_completed) {
13117                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13118                                         "0331 IOCB wake signaled\n");
13119                         /* Note: we are not indicating if the IOCB has a success
13120                          * status or not - that's for the caller to check.
13121                          * IOCB_SUCCESS means just that the command was sent and
13122                          * completed. Not that it completed successfully.
13123                          * */
13124                 } else if (timeleft == 0) {
13125                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13126                                         "0338 IOCB wait timeout error - no "
13127                                         "wake response Data x%x\n", timeout);
13128                         retval = IOCB_TIMEDOUT;
13129                 } else {
13130                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13131                                         "0330 IOCB wake NOT set, "
13132                                         "Data x%x x%lx\n",
13133                                         timeout, (timeleft / jiffies));
13134                         retval = IOCB_TIMEDOUT;
13135                 }
13136         } else if (retval == IOCB_BUSY) {
13137                 if (phba->cfg_log_verbose & LOG_SLI) {
13138                         list_for_each_entry(iocb, &pring->txq, list) {
13139                                 txq_cnt++;
13140                         }
13141                         list_for_each_entry(iocb, &pring->txcmplq, list) {
13142                                 txcmplq_cnt++;
13143                         }
13144                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13145                                 "2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
13146                                 phba->iocb_cnt, txq_cnt, txcmplq_cnt);
13147                 }
13148                 return retval;
13149         } else {
13150                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13151                                 "0332 IOCB wait issue failed, Data x%x\n",
13152                                 retval);
13153                 retval = IOCB_ERROR;
13154         }
13155
13156         if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13157                 if (lpfc_readl(phba->HCregaddr, &creg_val))
13158                         return IOCB_ERROR;
13159                 creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
13160                 writel(creg_val, phba->HCregaddr);
13161                 readl(phba->HCregaddr); /* flush */
13162         }
13163
13164         if (prspiocbq)
13165                 piocb->context2 = NULL;
13166
13167         piocb->context_un.wait_queue = NULL;
13168         piocb->iocb_cmpl = NULL;
13169         return retval;
13170 }
13171
13172 /**
13173  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
13174  * @phba: Pointer to HBA context object.
13175  * @pmboxq: Pointer to driver mailbox object.
13176  * @timeout: Timeout in number of seconds.
13177  *
13178  * This function issues the mailbox to firmware and waits for the
13179  * mailbox command to complete. If the mailbox command is not
13180  * completed within timeout seconds, it returns MBX_TIMEOUT.
13181  * The function waits for the mailbox completion using an
13182  * interruptible wait. If the thread is woken up due to a
13183  * signal, MBX_TIMEOUT error is returned to the caller. Caller
13184  * should not free the mailbox resources, if this function returns
13185  * MBX_TIMEOUT.
13186  * This function will sleep while waiting for mailbox completion.
13187  * So, this function should not be called from any context which
13188  * does not allow sleeping. Due to the same reason, this function
13189  * cannot be called with interrupt disabled.
13190  * This function assumes that the mailbox completion occurs while
13191  * this function sleep. So, this function cannot be called from
13192  * the worker thread which processes mailbox completion.
13193  * This function is called in the context of HBA management
13194  * applications.
13195  * This function returns MBX_SUCCESS when successful.
13196  * This function is called with no lock held.
13197  **/
13198 int
13199 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
13200                          uint32_t timeout)
13201 {
13202         struct completion mbox_done;
13203         int retval;
13204         unsigned long flag;
13205
13206         pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
13207         /* setup wake call as IOCB callback */
13208         pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
13209
13210         /* setup context3 field to pass wait_queue pointer to wake function  */
13211         init_completion(&mbox_done);
13212         pmboxq->context3 = &mbox_done;
13213         /* now issue the command */
13214         retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
13215         if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
13216                 wait_for_completion_timeout(&mbox_done,
13217                                             msecs_to_jiffies(timeout * 1000));
13218
13219                 spin_lock_irqsave(&phba->hbalock, flag);
13220                 pmboxq->context3 = NULL;
13221                 /*
13222                  * if LPFC_MBX_WAKE flag is set the mailbox is completed
13223                  * else do not free the resources.
13224                  */
13225                 if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
13226                         retval = MBX_SUCCESS;
13227                 } else {
13228                         retval = MBX_TIMEOUT;
13229                         pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13230                 }
13231                 spin_unlock_irqrestore(&phba->hbalock, flag);
13232         }
13233         return retval;
13234 }
13235
13236 /**
13237  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
13238  * @phba: Pointer to HBA context.
13239  * @mbx_action: Mailbox shutdown options.
13240  *
13241  * This function is called to shutdown the driver's mailbox sub-system.
13242  * It first marks the mailbox sub-system is in a block state to prevent
13243  * the asynchronous mailbox command from issued off the pending mailbox
13244  * command queue. If the mailbox command sub-system shutdown is due to
13245  * HBA error conditions such as EEH or ERATT, this routine shall invoke
13246  * the mailbox sub-system flush routine to forcefully bring down the
13247  * mailbox sub-system. Otherwise, if it is due to normal condition (such
13248  * as with offline or HBA function reset), this routine will wait for the
13249  * outstanding mailbox command to complete before invoking the mailbox
13250  * sub-system flush routine to gracefully bring down mailbox sub-system.
13251  **/
13252 void
13253 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
13254 {
13255         struct lpfc_sli *psli = &phba->sli;
13256         unsigned long timeout;
13257
13258         if (mbx_action == LPFC_MBX_NO_WAIT) {
13259                 /* delay 100ms for port state */
13260                 msleep(100);
13261                 lpfc_sli_mbox_sys_flush(phba);
13262                 return;
13263         }
13264         timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
13265
13266         /* Disable softirqs, including timers from obtaining phba->hbalock */
13267         local_bh_disable();
13268
13269         spin_lock_irq(&phba->hbalock);
13270         psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13271
13272         if (psli->sli_flag & LPFC_SLI_ACTIVE) {
13273                 /* Determine how long we might wait for the active mailbox
13274                  * command to be gracefully completed by firmware.
13275                  */
13276                 if (phba->sli.mbox_active)
13277                         timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
13278                                                 phba->sli.mbox_active) *
13279                                                 1000) + jiffies;
13280                 spin_unlock_irq(&phba->hbalock);
13281
13282                 /* Enable softirqs again, done with phba->hbalock */
13283                 local_bh_enable();
13284
13285                 while (phba->sli.mbox_active) {
13286                         /* Check active mailbox complete status every 2ms */
13287                         msleep(2);
13288                         if (time_after(jiffies, timeout))
13289                                 /* Timeout, let the mailbox flush routine to
13290                                  * forcefully release active mailbox command
13291                                  */
13292                                 break;
13293                 }
13294         } else {
13295                 spin_unlock_irq(&phba->hbalock);
13296
13297                 /* Enable softirqs again, done with phba->hbalock */
13298                 local_bh_enable();
13299         }
13300
13301         lpfc_sli_mbox_sys_flush(phba);
13302 }
13303
13304 /**
13305  * lpfc_sli_eratt_read - read sli-3 error attention events
13306  * @phba: Pointer to HBA context.
13307  *
13308  * This function is called to read the SLI3 device error attention registers
13309  * for possible error attention events. The caller must hold the hostlock
13310  * with spin_lock_irq().
13311  *
13312  * This function returns 1 when there is Error Attention in the Host Attention
13313  * Register and returns 0 otherwise.
13314  **/
13315 static int
13316 lpfc_sli_eratt_read(struct lpfc_hba *phba)
13317 {
13318         uint32_t ha_copy;
13319
13320         /* Read chip Host Attention (HA) register */
13321         if (lpfc_readl(phba->HAregaddr, &ha_copy))
13322                 goto unplug_err;
13323
13324         if (ha_copy & HA_ERATT) {
13325                 /* Read host status register to retrieve error event */
13326                 if (lpfc_sli_read_hs(phba))
13327                         goto unplug_err;
13328
13329                 /* Check if there is a deferred error condition is active */
13330                 if ((HS_FFER1 & phba->work_hs) &&
13331                     ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13332                       HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
13333                         phba->hba_flag |= DEFER_ERATT;
13334                         /* Clear all interrupt enable conditions */
13335                         writel(0, phba->HCregaddr);
13336                         readl(phba->HCregaddr);
13337                 }
13338
13339                 /* Set the driver HA work bitmap */
13340                 phba->work_ha |= HA_ERATT;
13341                 /* Indicate polling handles this ERATT */
13342                 phba->hba_flag |= HBA_ERATT_HANDLED;
13343                 return 1;
13344         }
13345         return 0;
13346
13347 unplug_err:
13348         /* Set the driver HS work bitmap */
13349         phba->work_hs |= UNPLUG_ERR;
13350         /* Set the driver HA work bitmap */
13351         phba->work_ha |= HA_ERATT;
13352         /* Indicate polling handles this ERATT */
13353         phba->hba_flag |= HBA_ERATT_HANDLED;
13354         return 1;
13355 }
13356
13357 /**
13358  * lpfc_sli4_eratt_read - read sli-4 error attention events
13359  * @phba: Pointer to HBA context.
13360  *
13361  * This function is called to read the SLI4 device error attention registers
13362  * for possible error attention events. The caller must hold the hostlock
13363  * with spin_lock_irq().
13364  *
13365  * This function returns 1 when there is Error Attention in the Host Attention
13366  * Register and returns 0 otherwise.
13367  **/
13368 static int
13369 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
13370 {
13371         uint32_t uerr_sta_hi, uerr_sta_lo;
13372         uint32_t if_type, portsmphr;
13373         struct lpfc_register portstat_reg;
13374
13375         /*
13376          * For now, use the SLI4 device internal unrecoverable error
13377          * registers for error attention. This can be changed later.
13378          */
13379         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
13380         switch (if_type) {
13381         case LPFC_SLI_INTF_IF_TYPE_0:
13382                 if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
13383                         &uerr_sta_lo) ||
13384                         lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
13385                         &uerr_sta_hi)) {
13386                         phba->work_hs |= UNPLUG_ERR;
13387                         phba->work_ha |= HA_ERATT;
13388                         phba->hba_flag |= HBA_ERATT_HANDLED;
13389                         return 1;
13390                 }
13391                 if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
13392                     (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
13393                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13394                                         "1423 HBA Unrecoverable error: "
13395                                         "uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
13396                                         "ue_mask_lo_reg=0x%x, "
13397                                         "ue_mask_hi_reg=0x%x\n",
13398                                         uerr_sta_lo, uerr_sta_hi,
13399                                         phba->sli4_hba.ue_mask_lo,
13400                                         phba->sli4_hba.ue_mask_hi);
13401                         phba->work_status[0] = uerr_sta_lo;
13402                         phba->work_status[1] = uerr_sta_hi;
13403                         phba->work_ha |= HA_ERATT;
13404                         phba->hba_flag |= HBA_ERATT_HANDLED;
13405                         return 1;
13406                 }
13407                 break;
13408         case LPFC_SLI_INTF_IF_TYPE_2:
13409         case LPFC_SLI_INTF_IF_TYPE_6:
13410                 if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
13411                         &portstat_reg.word0) ||
13412                         lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
13413                         &portsmphr)){
13414                         phba->work_hs |= UNPLUG_ERR;
13415                         phba->work_ha |= HA_ERATT;
13416                         phba->hba_flag |= HBA_ERATT_HANDLED;
13417                         return 1;
13418                 }
13419                 if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
13420                         phba->work_status[0] =
13421                                 readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
13422                         phba->work_status[1] =
13423                                 readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
13424                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13425                                         "2885 Port Status Event: "
13426                                         "port status reg 0x%x, "
13427                                         "port smphr reg 0x%x, "
13428                                         "error 1=0x%x, error 2=0x%x\n",
13429                                         portstat_reg.word0,
13430                                         portsmphr,
13431                                         phba->work_status[0],
13432                                         phba->work_status[1]);
13433                         phba->work_ha |= HA_ERATT;
13434                         phba->hba_flag |= HBA_ERATT_HANDLED;
13435                         return 1;
13436                 }
13437                 break;
13438         case LPFC_SLI_INTF_IF_TYPE_1:
13439         default:
13440                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13441                                 "2886 HBA Error Attention on unsupported "
13442                                 "if type %d.", if_type);
13443                 return 1;
13444         }
13445
13446         return 0;
13447 }
13448
13449 /**
13450  * lpfc_sli_check_eratt - check error attention events
13451  * @phba: Pointer to HBA context.
13452  *
13453  * This function is called from timer soft interrupt context to check HBA's
13454  * error attention register bit for error attention events.
13455  *
13456  * This function returns 1 when there is Error Attention in the Host Attention
13457  * Register and returns 0 otherwise.
13458  **/
13459 int
13460 lpfc_sli_check_eratt(struct lpfc_hba *phba)
13461 {
13462         uint32_t ha_copy;
13463
13464         /* If somebody is waiting to handle an eratt, don't process it
13465          * here. The brdkill function will do this.
13466          */
13467         if (phba->link_flag & LS_IGNORE_ERATT)
13468                 return 0;
13469
13470         /* Check if interrupt handler handles this ERATT */
13471         spin_lock_irq(&phba->hbalock);
13472         if (phba->hba_flag & HBA_ERATT_HANDLED) {
13473                 /* Interrupt handler has handled ERATT */
13474                 spin_unlock_irq(&phba->hbalock);
13475                 return 0;
13476         }
13477
13478         /*
13479          * If there is deferred error attention, do not check for error
13480          * attention
13481          */
13482         if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13483                 spin_unlock_irq(&phba->hbalock);
13484                 return 0;
13485         }
13486
13487         /* If PCI channel is offline, don't process it */
13488         if (unlikely(pci_channel_offline(phba->pcidev))) {
13489                 spin_unlock_irq(&phba->hbalock);
13490                 return 0;
13491         }
13492
13493         switch (phba->sli_rev) {
13494         case LPFC_SLI_REV2:
13495         case LPFC_SLI_REV3:
13496                 /* Read chip Host Attention (HA) register */
13497                 ha_copy = lpfc_sli_eratt_read(phba);
13498                 break;
13499         case LPFC_SLI_REV4:
13500                 /* Read device Uncoverable Error (UERR) registers */
13501                 ha_copy = lpfc_sli4_eratt_read(phba);
13502                 break;
13503         default:
13504                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13505                                 "0299 Invalid SLI revision (%d)\n",
13506                                 phba->sli_rev);
13507                 ha_copy = 0;
13508                 break;
13509         }
13510         spin_unlock_irq(&phba->hbalock);
13511
13512         return ha_copy;
13513 }
13514
13515 /**
13516  * lpfc_intr_state_check - Check device state for interrupt handling
13517  * @phba: Pointer to HBA context.
13518  *
13519  * This inline routine checks whether a device or its PCI slot is in a state
13520  * that the interrupt should be handled.
13521  *
13522  * This function returns 0 if the device or the PCI slot is in a state that
13523  * interrupt should be handled, otherwise -EIO.
13524  */
13525 static inline int
13526 lpfc_intr_state_check(struct lpfc_hba *phba)
13527 {
13528         /* If the pci channel is offline, ignore all the interrupts */
13529         if (unlikely(pci_channel_offline(phba->pcidev)))
13530                 return -EIO;
13531
13532         /* Update device level interrupt statistics */
13533         phba->sli.slistat.sli_intr++;
13534
13535         /* Ignore all interrupts during initialization. */
13536         if (unlikely(phba->link_state < LPFC_LINK_DOWN))
13537                 return -EIO;
13538
13539         return 0;
13540 }
13541
13542 /**
13543  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
13544  * @irq: Interrupt number.
13545  * @dev_id: The device context pointer.
13546  *
13547  * This function is directly called from the PCI layer as an interrupt
13548  * service routine when device with SLI-3 interface spec is enabled with
13549  * MSI-X multi-message interrupt mode and there are slow-path events in
13550  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
13551  * interrupt mode, this function is called as part of the device-level
13552  * interrupt handler. When the PCI slot is in error recovery or the HBA
13553  * is undergoing initialization, the interrupt handler will not process
13554  * the interrupt. The link attention and ELS ring attention events are
13555  * handled by the worker thread. The interrupt handler signals the worker
13556  * thread and returns for these events. This function is called without
13557  * any lock held. It gets the hbalock to access and update SLI data
13558  * structures.
13559  *
13560  * This function returns IRQ_HANDLED when interrupt is handled else it
13561  * returns IRQ_NONE.
13562  **/
13563 irqreturn_t
13564 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
13565 {
13566         struct lpfc_hba  *phba;
13567         uint32_t ha_copy, hc_copy;
13568         uint32_t work_ha_copy;
13569         unsigned long status;
13570         unsigned long iflag;
13571         uint32_t control;
13572
13573         MAILBOX_t *mbox, *pmbox;
13574         struct lpfc_vport *vport;
13575         struct lpfc_nodelist *ndlp;
13576         struct lpfc_dmabuf *mp;
13577         LPFC_MBOXQ_t *pmb;
13578         int rc;
13579
13580         /*
13581          * Get the driver's phba structure from the dev_id and
13582          * assume the HBA is not interrupting.
13583          */
13584         phba = (struct lpfc_hba *)dev_id;
13585
13586         if (unlikely(!phba))
13587                 return IRQ_NONE;
13588
13589         /*
13590          * Stuff needs to be attented to when this function is invoked as an
13591          * individual interrupt handler in MSI-X multi-message interrupt mode
13592          */
13593         if (phba->intr_type == MSIX) {
13594                 /* Check device state for handling interrupt */
13595                 if (lpfc_intr_state_check(phba))
13596                         return IRQ_NONE;
13597                 /* Need to read HA REG for slow-path events */
13598                 spin_lock_irqsave(&phba->hbalock, iflag);
13599                 if (lpfc_readl(phba->HAregaddr, &ha_copy))
13600                         goto unplug_error;
13601                 /* If somebody is waiting to handle an eratt don't process it
13602                  * here. The brdkill function will do this.
13603                  */
13604                 if (phba->link_flag & LS_IGNORE_ERATT)
13605                         ha_copy &= ~HA_ERATT;
13606                 /* Check the need for handling ERATT in interrupt handler */
13607                 if (ha_copy & HA_ERATT) {
13608                         if (phba->hba_flag & HBA_ERATT_HANDLED)
13609                                 /* ERATT polling has handled ERATT */
13610                                 ha_copy &= ~HA_ERATT;
13611                         else
13612                                 /* Indicate interrupt handler handles ERATT */
13613                                 phba->hba_flag |= HBA_ERATT_HANDLED;
13614                 }
13615
13616                 /*
13617                  * If there is deferred error attention, do not check for any
13618                  * interrupt.
13619                  */
13620                 if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13621                         spin_unlock_irqrestore(&phba->hbalock, iflag);
13622                         return IRQ_NONE;
13623                 }
13624
13625                 /* Clear up only attention source related to slow-path */
13626                 if (lpfc_readl(phba->HCregaddr, &hc_copy))
13627                         goto unplug_error;
13628
13629                 writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
13630                         HC_LAINT_ENA | HC_ERINT_ENA),
13631                         phba->HCregaddr);
13632                 writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
13633                         phba->HAregaddr);
13634                 writel(hc_copy, phba->HCregaddr);
13635                 readl(phba->HAregaddr); /* flush */
13636                 spin_unlock_irqrestore(&phba->hbalock, iflag);
13637         } else
13638                 ha_copy = phba->ha_copy;
13639
13640         work_ha_copy = ha_copy & phba->work_ha_mask;
13641
13642         if (work_ha_copy) {
13643                 if (work_ha_copy & HA_LATT) {
13644                         if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
13645                                 /*
13646                                  * Turn off Link Attention interrupts
13647                                  * until CLEAR_LA done
13648                                  */
13649                                 spin_lock_irqsave(&phba->hbalock, iflag);
13650                                 phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
13651                                 if (lpfc_readl(phba->HCregaddr, &control))
13652                                         goto unplug_error;
13653                                 control &= ~HC_LAINT_ENA;
13654                                 writel(control, phba->HCregaddr);
13655                                 readl(phba->HCregaddr); /* flush */
13656                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
13657                         }
13658                         else
13659                                 work_ha_copy &= ~HA_LATT;
13660                 }
13661
13662                 if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
13663                         /*
13664                          * Turn off Slow Rings interrupts, LPFC_ELS_RING is
13665                          * the only slow ring.
13666                          */
13667                         status = (work_ha_copy &
13668                                 (HA_RXMASK  << (4*LPFC_ELS_RING)));
13669                         status >>= (4*LPFC_ELS_RING);
13670                         if (status & HA_RXMASK) {
13671                                 spin_lock_irqsave(&phba->hbalock, iflag);
13672                                 if (lpfc_readl(phba->HCregaddr, &control))
13673                                         goto unplug_error;
13674
13675                                 lpfc_debugfs_slow_ring_trc(phba,
13676                                 "ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
13677                                 control, status,
13678                                 (uint32_t)phba->sli.slistat.sli_intr);
13679
13680                                 if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
13681                                         lpfc_debugfs_slow_ring_trc(phba,
13682                                                 "ISR Disable ring:"
13683                                                 "pwork:x%x hawork:x%x wait:x%x",
13684                                                 phba->work_ha, work_ha_copy,
13685                                                 (uint32_t)((unsigned long)
13686                                                 &phba->work_waitq));
13687
13688                                         control &=
13689                                             ~(HC_R0INT_ENA << LPFC_ELS_RING);
13690                                         writel(control, phba->HCregaddr);
13691                                         readl(phba->HCregaddr); /* flush */
13692                                 }
13693                                 else {
13694                                         lpfc_debugfs_slow_ring_trc(phba,
13695                                                 "ISR slow ring:   pwork:"
13696                                                 "x%x hawork:x%x wait:x%x",
13697                                                 phba->work_ha, work_ha_copy,
13698                                                 (uint32_t)((unsigned long)
13699                                                 &phba->work_waitq));
13700                                 }
13701                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
13702                         }
13703                 }
13704                 spin_lock_irqsave(&phba->hbalock, iflag);
13705                 if (work_ha_copy & HA_ERATT) {
13706                         if (lpfc_sli_read_hs(phba))
13707                                 goto unplug_error;
13708                         /*
13709                          * Check if there is a deferred error condition
13710                          * is active
13711                          */
13712                         if ((HS_FFER1 & phba->work_hs) &&
13713                                 ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13714                                   HS_FFER6 | HS_FFER7 | HS_FFER8) &
13715                                   phba->work_hs)) {
13716                                 phba->hba_flag |= DEFER_ERATT;
13717                                 /* Clear all interrupt enable conditions */
13718                                 writel(0, phba->HCregaddr);
13719                                 readl(phba->HCregaddr);
13720                         }
13721                 }
13722
13723                 if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
13724                         pmb = phba->sli.mbox_active;
13725                         pmbox = &pmb->u.mb;
13726                         mbox = phba->mbox;
13727                         vport = pmb->vport;
13728
13729                         /* First check out the status word */
13730                         lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
13731                         if (pmbox->mbxOwner != OWN_HOST) {
13732                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
13733                                 /*
13734                                  * Stray Mailbox Interrupt, mbxCommand <cmd>
13735                                  * mbxStatus <status>
13736                                  */
13737                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13738                                                 "(%d):0304 Stray Mailbox "
13739                                                 "Interrupt mbxCommand x%x "
13740                                                 "mbxStatus x%x\n",
13741                                                 (vport ? vport->vpi : 0),
13742                                                 pmbox->mbxCommand,
13743                                                 pmbox->mbxStatus);
13744                                 /* clear mailbox attention bit */
13745                                 work_ha_copy &= ~HA_MBATT;
13746                         } else {
13747                                 phba->sli.mbox_active = NULL;
13748                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
13749                                 phba->last_completion_time = jiffies;
13750                                 del_timer(&phba->sli.mbox_tmo);
13751                                 if (pmb->mbox_cmpl) {
13752                                         lpfc_sli_pcimem_bcopy(mbox, pmbox,
13753                                                         MAILBOX_CMD_SIZE);
13754                                         if (pmb->out_ext_byte_len &&
13755                                                 pmb->ctx_buf)
13756                                                 lpfc_sli_pcimem_bcopy(
13757                                                 phba->mbox_ext,
13758                                                 pmb->ctx_buf,
13759                                                 pmb->out_ext_byte_len);
13760                                 }
13761                                 if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13762                                         pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13763
13764                                         lpfc_debugfs_disc_trc(vport,
13765                                                 LPFC_DISC_TRC_MBOX_VPORT,
13766                                                 "MBOX dflt rpi: : "
13767                                                 "status:x%x rpi:x%x",
13768                                                 (uint32_t)pmbox->mbxStatus,
13769                                                 pmbox->un.varWords[0], 0);
13770
13771                                         if (!pmbox->mbxStatus) {
13772                                                 mp = (struct lpfc_dmabuf *)
13773                                                         (pmb->ctx_buf);
13774                                                 ndlp = (struct lpfc_nodelist *)
13775                                                         pmb->ctx_ndlp;
13776
13777                                                 /* Reg_LOGIN of dflt RPI was
13778                                                  * successful. new lets get
13779                                                  * rid of the RPI using the
13780                                                  * same mbox buffer.
13781                                                  */
13782                                                 lpfc_unreg_login(phba,
13783                                                         vport->vpi,
13784                                                         pmbox->un.varWords[0],
13785                                                         pmb);
13786                                                 pmb->mbox_cmpl =
13787                                                         lpfc_mbx_cmpl_dflt_rpi;
13788                                                 pmb->ctx_buf = mp;
13789                                                 pmb->ctx_ndlp = ndlp;
13790                                                 pmb->vport = vport;
13791                                                 rc = lpfc_sli_issue_mbox(phba,
13792                                                                 pmb,
13793                                                                 MBX_NOWAIT);
13794                                                 if (rc != MBX_BUSY)
13795                                                         lpfc_printf_log(phba,
13796                                                         KERN_ERR,
13797                                                         LOG_TRACE_EVENT,
13798                                                         "0350 rc should have"
13799                                                         "been MBX_BUSY\n");
13800                                                 if (rc != MBX_NOT_FINISHED)
13801                                                         goto send_current_mbox;
13802                                         }
13803                                 }
13804                                 spin_lock_irqsave(
13805                                                 &phba->pport->work_port_lock,
13806                                                 iflag);
13807                                 phba->pport->work_port_events &=
13808                                         ~WORKER_MBOX_TMO;
13809                                 spin_unlock_irqrestore(
13810                                                 &phba->pport->work_port_lock,
13811                                                 iflag);
13812
13813                                 /* Do NOT queue MBX_HEARTBEAT to the worker
13814                                  * thread for processing.
13815                                  */
13816                                 if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13817                                         /* Process mbox now */
13818                                         phba->sli.mbox_active = NULL;
13819                                         phba->sli.sli_flag &=
13820                                                 ~LPFC_SLI_MBOX_ACTIVE;
13821                                         if (pmb->mbox_cmpl)
13822                                                 pmb->mbox_cmpl(phba, pmb);
13823                                 } else {
13824                                         /* Queue to worker thread to process */
13825                                         lpfc_mbox_cmpl_put(phba, pmb);
13826                                 }
13827                         }
13828                 } else
13829                         spin_unlock_irqrestore(&phba->hbalock, iflag);
13830
13831                 if ((work_ha_copy & HA_MBATT) &&
13832                     (phba->sli.mbox_active == NULL)) {
13833 send_current_mbox:
13834                         /* Process next mailbox command if there is one */
13835                         do {
13836                                 rc = lpfc_sli_issue_mbox(phba, NULL,
13837                                                          MBX_NOWAIT);
13838                         } while (rc == MBX_NOT_FINISHED);
13839                         if (rc != MBX_SUCCESS)
13840                                 lpfc_printf_log(phba, KERN_ERR,
13841                                                 LOG_TRACE_EVENT,
13842                                                 "0349 rc should be "
13843                                                 "MBX_SUCCESS\n");
13844                 }
13845
13846                 spin_lock_irqsave(&phba->hbalock, iflag);
13847                 phba->work_ha |= work_ha_copy;
13848                 spin_unlock_irqrestore(&phba->hbalock, iflag);
13849                 lpfc_worker_wake_up(phba);
13850         }
13851         return IRQ_HANDLED;
13852 unplug_error:
13853         spin_unlock_irqrestore(&phba->hbalock, iflag);
13854         return IRQ_HANDLED;
13855
13856 } /* lpfc_sli_sp_intr_handler */
13857
13858 /**
13859  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
13860  * @irq: Interrupt number.
13861  * @dev_id: The device context pointer.
13862  *
13863  * This function is directly called from the PCI layer as an interrupt
13864  * service routine when device with SLI-3 interface spec is enabled with
13865  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13866  * ring event in the HBA. However, when the device is enabled with either
13867  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13868  * device-level interrupt handler. When the PCI slot is in error recovery
13869  * or the HBA is undergoing initialization, the interrupt handler will not
13870  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13871  * the intrrupt context. This function is called without any lock held.
13872  * It gets the hbalock to access and update SLI data structures.
13873  *
13874  * This function returns IRQ_HANDLED when interrupt is handled else it
13875  * returns IRQ_NONE.
13876  **/
13877 irqreturn_t
13878 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
13879 {
13880         struct lpfc_hba  *phba;
13881         uint32_t ha_copy;
13882         unsigned long status;
13883         unsigned long iflag;
13884         struct lpfc_sli_ring *pring;
13885
13886         /* Get the driver's phba structure from the dev_id and
13887          * assume the HBA is not interrupting.
13888          */
13889         phba = (struct lpfc_hba *) dev_id;
13890
13891         if (unlikely(!phba))
13892                 return IRQ_NONE;
13893
13894         /*
13895          * Stuff needs to be attented to when this function is invoked as an
13896          * individual interrupt handler in MSI-X multi-message interrupt mode
13897          */
13898         if (phba->intr_type == MSIX) {
13899                 /* Check device state for handling interrupt */
13900                 if (lpfc_intr_state_check(phba))
13901                         return IRQ_NONE;
13902                 /* Need to read HA REG for FCP ring and other ring events */
13903                 if (lpfc_readl(phba->HAregaddr, &ha_copy))
13904                         return IRQ_HANDLED;
13905                 /* Clear up only attention source related to fast-path */
13906                 spin_lock_irqsave(&phba->hbalock, iflag);
13907                 /*
13908                  * If there is deferred error attention, do not check for
13909                  * any interrupt.
13910                  */
13911                 if (unlikely(phba->hba_flag & DEFER_ERATT)) {
13912                         spin_unlock_irqrestore(&phba->hbalock, iflag);
13913                         return IRQ_NONE;
13914                 }
13915                 writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
13916                         phba->HAregaddr);
13917                 readl(phba->HAregaddr); /* flush */
13918                 spin_unlock_irqrestore(&phba->hbalock, iflag);
13919         } else
13920                 ha_copy = phba->ha_copy;
13921
13922         /*
13923          * Process all events on FCP ring. Take the optimized path for FCP IO.
13924          */
13925         ha_copy &= ~(phba->work_ha_mask);
13926
13927         status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13928         status >>= (4*LPFC_FCP_RING);
13929         pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
13930         if (status & HA_RXMASK)
13931                 lpfc_sli_handle_fast_ring_event(phba, pring, status);
13932
13933         if (phba->cfg_multi_ring_support == 2) {
13934                 /*
13935                  * Process all events on extra ring. Take the optimized path
13936                  * for extra ring IO.
13937                  */
13938                 status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13939                 status >>= (4*LPFC_EXTRA_RING);
13940                 if (status & HA_RXMASK) {
13941                         lpfc_sli_handle_fast_ring_event(phba,
13942                                         &phba->sli.sli3_ring[LPFC_EXTRA_RING],
13943                                         status);
13944                 }
13945         }
13946         return IRQ_HANDLED;
13947 }  /* lpfc_sli_fp_intr_handler */
13948
13949 /**
13950  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
13951  * @irq: Interrupt number.
13952  * @dev_id: The device context pointer.
13953  *
13954  * This function is the HBA device-level interrupt handler to device with
13955  * SLI-3 interface spec, called from the PCI layer when either MSI or
13956  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
13957  * requires driver attention. This function invokes the slow-path interrupt
13958  * attention handling function and fast-path interrupt attention handling
13959  * function in turn to process the relevant HBA attention events. This
13960  * function is called without any lock held. It gets the hbalock to access
13961  * and update SLI data structures.
13962  *
13963  * This function returns IRQ_HANDLED when interrupt is handled, else it
13964  * returns IRQ_NONE.
13965  **/
13966 irqreturn_t
13967 lpfc_sli_intr_handler(int irq, void *dev_id)
13968 {
13969         struct lpfc_hba  *phba;
13970         irqreturn_t sp_irq_rc, fp_irq_rc;
13971         unsigned long status1, status2;
13972         uint32_t hc_copy;
13973
13974         /*
13975          * Get the driver's phba structure from the dev_id and
13976          * assume the HBA is not interrupting.
13977          */
13978         phba = (struct lpfc_hba *) dev_id;
13979
13980         if (unlikely(!phba))
13981                 return IRQ_NONE;
13982
13983         /* Check device state for handling interrupt */
13984         if (lpfc_intr_state_check(phba))
13985                 return IRQ_NONE;
13986
13987         spin_lock(&phba->hbalock);
13988         if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
13989                 spin_unlock(&phba->hbalock);
13990                 return IRQ_HANDLED;
13991         }
13992
13993         if (unlikely(!phba->ha_copy)) {
13994                 spin_unlock(&phba->hbalock);
13995                 return IRQ_NONE;
13996         } else if (phba->ha_copy & HA_ERATT) {
13997                 if (phba->hba_flag & HBA_ERATT_HANDLED)
13998                         /* ERATT polling has handled ERATT */
13999                         phba->ha_copy &= ~HA_ERATT;
14000                 else
14001                         /* Indicate interrupt handler handles ERATT */
14002                         phba->hba_flag |= HBA_ERATT_HANDLED;
14003         }
14004
14005         /*
14006          * If there is deferred error attention, do not check for any interrupt.
14007          */
14008         if (unlikely(phba->hba_flag & DEFER_ERATT)) {
14009                 spin_unlock(&phba->hbalock);
14010                 return IRQ_NONE;
14011         }
14012
14013         /* Clear attention sources except link and error attentions */
14014         if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
14015                 spin_unlock(&phba->hbalock);
14016                 return IRQ_HANDLED;
14017         }
14018         writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
14019                 | HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
14020                 phba->HCregaddr);
14021         writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
14022         writel(hc_copy, phba->HCregaddr);
14023         readl(phba->HAregaddr); /* flush */
14024         spin_unlock(&phba->hbalock);
14025
14026         /*
14027          * Invokes slow-path host attention interrupt handling as appropriate.
14028          */
14029
14030         /* status of events with mailbox and link attention */
14031         status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
14032
14033         /* status of events with ELS ring */
14034         status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
14035         status2 >>= (4*LPFC_ELS_RING);
14036
14037         if (status1 || (status2 & HA_RXMASK))
14038                 sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
14039         else
14040                 sp_irq_rc = IRQ_NONE;
14041
14042         /*
14043          * Invoke fast-path host attention interrupt handling as appropriate.
14044          */
14045
14046         /* status of events with FCP ring */
14047         status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
14048         status1 >>= (4*LPFC_FCP_RING);
14049
14050         /* status of events with extra ring */
14051         if (phba->cfg_multi_ring_support == 2) {
14052                 status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
14053                 status2 >>= (4*LPFC_EXTRA_RING);
14054         } else
14055                 status2 = 0;
14056
14057         if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
14058                 fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
14059         else
14060                 fp_irq_rc = IRQ_NONE;
14061
14062         /* Return device-level interrupt handling status */
14063         return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
14064 }  /* lpfc_sli_intr_handler */
14065
14066 /**
14067  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
14068  * @phba: pointer to lpfc hba data structure.
14069  *
14070  * This routine is invoked by the worker thread to process all the pending
14071  * SLI4 els abort xri events.
14072  **/
14073 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
14074 {
14075         struct lpfc_cq_event *cq_event;
14076         unsigned long iflags;
14077
14078         /* First, declare the els xri abort event has been handled */
14079         spin_lock_irqsave(&phba->hbalock, iflags);
14080         phba->hba_flag &= ~ELS_XRI_ABORT_EVENT;
14081         spin_unlock_irqrestore(&phba->hbalock, iflags);
14082
14083         /* Now, handle all the els xri abort events */
14084         spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14085         while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
14086                 /* Get the first event from the head of the event queue */
14087                 list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
14088                                  cq_event, struct lpfc_cq_event, list);
14089                 spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14090                                        iflags);
14091                 /* Notify aborted XRI for ELS work queue */
14092                 lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
14093
14094                 /* Free the event processed back to the free pool */
14095                 lpfc_sli4_cq_event_release(phba, cq_event);
14096                 spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14097                                   iflags);
14098         }
14099         spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14100 }
14101
14102 /**
14103  * lpfc_sli4_iocb_param_transfer - Transfer pIocbOut and cmpl status to pIocbIn
14104  * @phba: pointer to lpfc hba data structure
14105  * @pIocbIn: pointer to the rspiocbq
14106  * @pIocbOut: pointer to the cmdiocbq
14107  * @wcqe: pointer to the complete wcqe
14108  *
14109  * This routine transfers the fields of a command iocbq to a response iocbq
14110  * by copying all the IOCB fields from command iocbq and transferring the
14111  * completion status information from the complete wcqe.
14112  **/
14113 static void
14114 lpfc_sli4_iocb_param_transfer(struct lpfc_hba *phba,
14115                               struct lpfc_iocbq *pIocbIn,
14116                               struct lpfc_iocbq *pIocbOut,
14117                               struct lpfc_wcqe_complete *wcqe)
14118 {
14119         int numBdes, i;
14120         unsigned long iflags;
14121         uint32_t status, max_response;
14122         struct lpfc_dmabuf *dmabuf;
14123         struct ulp_bde64 *bpl, bde;
14124         size_t offset = offsetof(struct lpfc_iocbq, iocb);
14125
14126         memcpy((char *)pIocbIn + offset, (char *)pIocbOut + offset,
14127                sizeof(struct lpfc_iocbq) - offset);
14128         /* Map WCQE parameters into irspiocb parameters */
14129         status = bf_get(lpfc_wcqe_c_status, wcqe);
14130         pIocbIn->iocb.ulpStatus = (status & LPFC_IOCB_STATUS_MASK);
14131         if (pIocbOut->iocb_flag & LPFC_IO_FCP)
14132                 if (pIocbIn->iocb.ulpStatus == IOSTAT_FCP_RSP_ERROR)
14133                         pIocbIn->iocb.un.fcpi.fcpi_parm =
14134                                         pIocbOut->iocb.un.fcpi.fcpi_parm -
14135                                         wcqe->total_data_placed;
14136                 else
14137                         pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
14138         else {
14139                 pIocbIn->iocb.un.ulpWord[4] = wcqe->parameter;
14140                 switch (pIocbOut->iocb.ulpCommand) {
14141                 case CMD_ELS_REQUEST64_CR:
14142                         dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
14143                         bpl  = (struct ulp_bde64 *)dmabuf->virt;
14144                         bde.tus.w = le32_to_cpu(bpl[1].tus.w);
14145                         max_response = bde.tus.f.bdeSize;
14146                         break;
14147                 case CMD_GEN_REQUEST64_CR:
14148                         max_response = 0;
14149                         if (!pIocbOut->context3)
14150                                 break;
14151                         numBdes = pIocbOut->iocb.un.genreq64.bdl.bdeSize/
14152                                         sizeof(struct ulp_bde64);
14153                         dmabuf = (struct lpfc_dmabuf *)pIocbOut->context3;
14154                         bpl = (struct ulp_bde64 *)dmabuf->virt;
14155                         for (i = 0; i < numBdes; i++) {
14156                                 bde.tus.w = le32_to_cpu(bpl[i].tus.w);
14157                                 if (bde.tus.f.bdeFlags != BUFF_TYPE_BDE_64)
14158                                         max_response += bde.tus.f.bdeSize;
14159                         }
14160                         break;
14161                 default:
14162                         max_response = wcqe->total_data_placed;
14163                         break;
14164                 }
14165                 if (max_response < wcqe->total_data_placed)
14166                         pIocbIn->iocb.un.genreq64.bdl.bdeSize = max_response;
14167                 else
14168                         pIocbIn->iocb.un.genreq64.bdl.bdeSize =
14169                                 wcqe->total_data_placed;
14170         }
14171
14172         /* Convert BG errors for completion status */
14173         if (status == CQE_STATUS_DI_ERROR) {
14174                 pIocbIn->iocb.ulpStatus = IOSTAT_LOCAL_REJECT;
14175
14176                 if (bf_get(lpfc_wcqe_c_bg_edir, wcqe))
14177                         pIocbIn->iocb.un.ulpWord[4] = IOERR_RX_DMA_FAILED;
14178                 else
14179                         pIocbIn->iocb.un.ulpWord[4] = IOERR_TX_DMA_FAILED;
14180
14181                 pIocbIn->iocb.unsli3.sli3_bg.bgstat = 0;
14182                 if (bf_get(lpfc_wcqe_c_bg_ge, wcqe)) /* Guard Check failed */
14183                         pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
14184                                 BGS_GUARD_ERR_MASK;
14185                 if (bf_get(lpfc_wcqe_c_bg_ae, wcqe)) /* App Tag Check failed */
14186                         pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
14187                                 BGS_APPTAG_ERR_MASK;
14188                 if (bf_get(lpfc_wcqe_c_bg_re, wcqe)) /* Ref Tag Check failed */
14189                         pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
14190                                 BGS_REFTAG_ERR_MASK;
14191
14192                 /* Check to see if there was any good data before the error */
14193                 if (bf_get(lpfc_wcqe_c_bg_tdpv, wcqe)) {
14194                         pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
14195                                 BGS_HI_WATER_MARK_PRESENT_MASK;
14196                         pIocbIn->iocb.unsli3.sli3_bg.bghm =
14197                                 wcqe->total_data_placed;
14198                 }
14199
14200                 /*
14201                 * Set ALL the error bits to indicate we don't know what
14202                 * type of error it is.
14203                 */
14204                 if (!pIocbIn->iocb.unsli3.sli3_bg.bgstat)
14205                         pIocbIn->iocb.unsli3.sli3_bg.bgstat |=
14206                                 (BGS_REFTAG_ERR_MASK | BGS_APPTAG_ERR_MASK |
14207                                 BGS_GUARD_ERR_MASK);
14208         }
14209
14210         /* Pick up HBA exchange busy condition */
14211         if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
14212                 spin_lock_irqsave(&phba->hbalock, iflags);
14213                 pIocbIn->iocb_flag |= LPFC_EXCHANGE_BUSY;
14214                 spin_unlock_irqrestore(&phba->hbalock, iflags);
14215         }
14216 }
14217
14218 /**
14219  * lpfc_sli4_els_wcqe_to_rspiocbq - Get response iocbq from els wcqe
14220  * @phba: Pointer to HBA context object.
14221  * @irspiocbq: Pointer to work-queue completion queue entry.
14222  *
14223  * This routine handles an ELS work-queue completion event and construct
14224  * a pseudo response ELS IODBQ from the SLI4 ELS WCQE for the common
14225  * discovery engine to handle.
14226  *
14227  * Return: Pointer to the receive IOCBQ, NULL otherwise.
14228  **/
14229 static struct lpfc_iocbq *
14230 lpfc_sli4_els_wcqe_to_rspiocbq(struct lpfc_hba *phba,
14231                                struct lpfc_iocbq *irspiocbq)
14232 {
14233         struct lpfc_sli_ring *pring;
14234         struct lpfc_iocbq *cmdiocbq;
14235         struct lpfc_wcqe_complete *wcqe;
14236         unsigned long iflags;
14237
14238         pring = lpfc_phba_elsring(phba);
14239         if (unlikely(!pring))
14240                 return NULL;
14241
14242         wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
14243         pring->stats.iocb_event++;
14244         /* Look up the ELS command IOCB and create pseudo response IOCB */
14245         cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14246                                 bf_get(lpfc_wcqe_c_request_tag, wcqe));
14247         if (unlikely(!cmdiocbq)) {
14248                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14249                                 "0386 ELS complete with no corresponding "
14250                                 "cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
14251                                 wcqe->word0, wcqe->total_data_placed,
14252                                 wcqe->parameter, wcqe->word3);
14253                 lpfc_sli_release_iocbq(phba, irspiocbq);
14254                 return NULL;
14255         }
14256
14257         spin_lock_irqsave(&pring->ring_lock, iflags);
14258         /* Put the iocb back on the txcmplq */
14259         lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
14260         spin_unlock_irqrestore(&pring->ring_lock, iflags);
14261
14262         /* Fake the irspiocbq and copy necessary response information */
14263         lpfc_sli4_iocb_param_transfer(phba, irspiocbq, cmdiocbq, wcqe);
14264
14265         return irspiocbq;
14266 }
14267
14268 inline struct lpfc_cq_event *
14269 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
14270 {
14271         struct lpfc_cq_event *cq_event;
14272
14273         /* Allocate a new internal CQ_EVENT entry */
14274         cq_event = lpfc_sli4_cq_event_alloc(phba);
14275         if (!cq_event) {
14276                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14277                                 "0602 Failed to alloc CQ_EVENT entry\n");
14278                 return NULL;
14279         }
14280
14281         /* Move the CQE into the event */
14282         memcpy(&cq_event->cqe, entry, size);
14283         return cq_event;
14284 }
14285
14286 /**
14287  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
14288  * @phba: Pointer to HBA context object.
14289  * @mcqe: Pointer to mailbox completion queue entry.
14290  *
14291  * This routine process a mailbox completion queue entry with asynchronous
14292  * event.
14293  *
14294  * Return: true if work posted to worker thread, otherwise false.
14295  **/
14296 static bool
14297 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14298 {
14299         struct lpfc_cq_event *cq_event;
14300         unsigned long iflags;
14301
14302         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14303                         "0392 Async Event: word0:x%x, word1:x%x, "
14304                         "word2:x%x, word3:x%x\n", mcqe->word0,
14305                         mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
14306
14307         cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
14308         if (!cq_event)
14309                 return false;
14310
14311         spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
14312         list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
14313         spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
14314
14315         /* Set the async event flag */
14316         spin_lock_irqsave(&phba->hbalock, iflags);
14317         phba->hba_flag |= ASYNC_EVENT;
14318         spin_unlock_irqrestore(&phba->hbalock, iflags);
14319
14320         return true;
14321 }
14322
14323 /**
14324  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
14325  * @phba: Pointer to HBA context object.
14326  * @mcqe: Pointer to mailbox completion queue entry.
14327  *
14328  * This routine process a mailbox completion queue entry with mailbox
14329  * completion event.
14330  *
14331  * Return: true if work posted to worker thread, otherwise false.
14332  **/
14333 static bool
14334 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14335 {
14336         uint32_t mcqe_status;
14337         MAILBOX_t *mbox, *pmbox;
14338         struct lpfc_mqe *mqe;
14339         struct lpfc_vport *vport;
14340         struct lpfc_nodelist *ndlp;
14341         struct lpfc_dmabuf *mp;
14342         unsigned long iflags;
14343         LPFC_MBOXQ_t *pmb;
14344         bool workposted = false;
14345         int rc;
14346
14347         /* If not a mailbox complete MCQE, out by checking mailbox consume */
14348         if (!bf_get(lpfc_trailer_completed, mcqe))
14349                 goto out_no_mqe_complete;
14350
14351         /* Get the reference to the active mbox command */
14352         spin_lock_irqsave(&phba->hbalock, iflags);
14353         pmb = phba->sli.mbox_active;
14354         if (unlikely(!pmb)) {
14355                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14356                                 "1832 No pending MBOX command to handle\n");
14357                 spin_unlock_irqrestore(&phba->hbalock, iflags);
14358                 goto out_no_mqe_complete;
14359         }
14360         spin_unlock_irqrestore(&phba->hbalock, iflags);
14361         mqe = &pmb->u.mqe;
14362         pmbox = (MAILBOX_t *)&pmb->u.mqe;
14363         mbox = phba->mbox;
14364         vport = pmb->vport;
14365
14366         /* Reset heartbeat timer */
14367         phba->last_completion_time = jiffies;
14368         del_timer(&phba->sli.mbox_tmo);
14369
14370         /* Move mbox data to caller's mailbox region, do endian swapping */
14371         if (pmb->mbox_cmpl && mbox)
14372                 lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
14373
14374         /*
14375          * For mcqe errors, conditionally move a modified error code to
14376          * the mbox so that the error will not be missed.
14377          */
14378         mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
14379         if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
14380                 if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
14381                         bf_set(lpfc_mqe_status, mqe,
14382                                (LPFC_MBX_ERROR_RANGE | mcqe_status));
14383         }
14384         if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
14385                 pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
14386                 lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
14387                                       "MBOX dflt rpi: status:x%x rpi:x%x",
14388                                       mcqe_status,
14389                                       pmbox->un.varWords[0], 0);
14390                 if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
14391                         mp = (struct lpfc_dmabuf *)(pmb->ctx_buf);
14392                         ndlp = (struct lpfc_nodelist *)pmb->ctx_ndlp;
14393
14394                         /* Reg_LOGIN of dflt RPI was successful. Mark the
14395                          * node as having an UNREG_LOGIN in progress to stop
14396                          * an unsolicited PLOGI from the same NPortId from
14397                          * starting another mailbox transaction.
14398                          */
14399                         spin_lock_irqsave(&ndlp->lock, iflags);
14400                         ndlp->nlp_flag |= NLP_UNREG_INP;
14401                         spin_unlock_irqrestore(&ndlp->lock, iflags);
14402                         lpfc_unreg_login(phba, vport->vpi,
14403                                          pmbox->un.varWords[0], pmb);
14404                         pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
14405                         pmb->ctx_buf = mp;
14406
14407                         /* No reference taken here.  This is a default
14408                          * RPI reg/immediate unreg cycle. The reference was
14409                          * taken in the reg rpi path and is released when
14410                          * this mailbox completes.
14411                          */
14412                         pmb->ctx_ndlp = ndlp;
14413                         pmb->vport = vport;
14414                         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
14415                         if (rc != MBX_BUSY)
14416                                 lpfc_printf_log(phba, KERN_ERR,
14417                                                 LOG_TRACE_EVENT,
14418                                                 "0385 rc should "
14419                                                 "have been MBX_BUSY\n");
14420                         if (rc != MBX_NOT_FINISHED)
14421                                 goto send_current_mbox;
14422                 }
14423         }
14424         spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
14425         phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
14426         spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
14427
14428         /* Do NOT queue MBX_HEARTBEAT to the worker thread for processing. */
14429         if (pmbox->mbxCommand == MBX_HEARTBEAT) {
14430                 spin_lock_irqsave(&phba->hbalock, iflags);
14431                 /* Release the mailbox command posting token */
14432                 phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14433                 phba->sli.mbox_active = NULL;
14434                 if (bf_get(lpfc_trailer_consumed, mcqe))
14435                         lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14436                 spin_unlock_irqrestore(&phba->hbalock, iflags);
14437
14438                 /* Post the next mbox command, if there is one */
14439                 lpfc_sli4_post_async_mbox(phba);
14440
14441                 /* Process cmpl now */
14442                 if (pmb->mbox_cmpl)
14443                         pmb->mbox_cmpl(phba, pmb);
14444                 return false;
14445         }
14446
14447         /* There is mailbox completion work to queue to the worker thread */
14448         spin_lock_irqsave(&phba->hbalock, iflags);
14449         __lpfc_mbox_cmpl_put(phba, pmb);
14450         phba->work_ha |= HA_MBATT;
14451         spin_unlock_irqrestore(&phba->hbalock, iflags);
14452         workposted = true;
14453
14454 send_current_mbox:
14455         spin_lock_irqsave(&phba->hbalock, iflags);
14456         /* Release the mailbox command posting token */
14457         phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14458         /* Setting active mailbox pointer need to be in sync to flag clear */
14459         phba->sli.mbox_active = NULL;
14460         if (bf_get(lpfc_trailer_consumed, mcqe))
14461                 lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14462         spin_unlock_irqrestore(&phba->hbalock, iflags);
14463         /* Wake up worker thread to post the next pending mailbox command */
14464         lpfc_worker_wake_up(phba);
14465         return workposted;
14466
14467 out_no_mqe_complete:
14468         spin_lock_irqsave(&phba->hbalock, iflags);
14469         if (bf_get(lpfc_trailer_consumed, mcqe))
14470                 lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14471         spin_unlock_irqrestore(&phba->hbalock, iflags);
14472         return false;
14473 }
14474
14475 /**
14476  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
14477  * @phba: Pointer to HBA context object.
14478  * @cq: Pointer to associated CQ
14479  * @cqe: Pointer to mailbox completion queue entry.
14480  *
14481  * This routine process a mailbox completion queue entry, it invokes the
14482  * proper mailbox complete handling or asynchronous event handling routine
14483  * according to the MCQE's async bit.
14484  *
14485  * Return: true if work posted to worker thread, otherwise false.
14486  **/
14487 static bool
14488 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14489                          struct lpfc_cqe *cqe)
14490 {
14491         struct lpfc_mcqe mcqe;
14492         bool workposted;
14493
14494         cq->CQ_mbox++;
14495
14496         /* Copy the mailbox MCQE and convert endian order as needed */
14497         lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
14498
14499         /* Invoke the proper event handling routine */
14500         if (!bf_get(lpfc_trailer_async, &mcqe))
14501                 workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
14502         else
14503                 workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
14504         return workposted;
14505 }
14506
14507 /**
14508  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
14509  * @phba: Pointer to HBA context object.
14510  * @cq: Pointer to associated CQ
14511  * @wcqe: Pointer to work-queue completion queue entry.
14512  *
14513  * This routine handles an ELS work-queue completion event.
14514  *
14515  * Return: true if work posted to worker thread, otherwise false.
14516  **/
14517 static bool
14518 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14519                              struct lpfc_wcqe_complete *wcqe)
14520 {
14521         struct lpfc_iocbq *irspiocbq;
14522         unsigned long iflags;
14523         struct lpfc_sli_ring *pring = cq->pring;
14524         int txq_cnt = 0;
14525         int txcmplq_cnt = 0;
14526
14527         /* Check for response status */
14528         if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14529                 /* Log the error status */
14530                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14531                                 "0357 ELS CQE error: status=x%x: "
14532                                 "CQE: %08x %08x %08x %08x\n",
14533                                 bf_get(lpfc_wcqe_c_status, wcqe),
14534                                 wcqe->word0, wcqe->total_data_placed,
14535                                 wcqe->parameter, wcqe->word3);
14536         }
14537
14538         /* Get an irspiocbq for later ELS response processing use */
14539         irspiocbq = lpfc_sli_get_iocbq(phba);
14540         if (!irspiocbq) {
14541                 if (!list_empty(&pring->txq))
14542                         txq_cnt++;
14543                 if (!list_empty(&pring->txcmplq))
14544                         txcmplq_cnt++;
14545                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14546                         "0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
14547                         "els_txcmplq_cnt=%d\n",
14548                         txq_cnt, phba->iocb_cnt,
14549                         txcmplq_cnt);
14550                 return false;
14551         }
14552
14553         /* Save off the slow-path queue event for work thread to process */
14554         memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
14555         spin_lock_irqsave(&phba->hbalock, iflags);
14556         list_add_tail(&irspiocbq->cq_event.list,
14557                       &phba->sli4_hba.sp_queue_event);
14558         phba->hba_flag |= HBA_SP_QUEUE_EVT;
14559         spin_unlock_irqrestore(&phba->hbalock, iflags);
14560
14561         return true;
14562 }
14563
14564 /**
14565  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
14566  * @phba: Pointer to HBA context object.
14567  * @wcqe: Pointer to work-queue completion queue entry.
14568  *
14569  * This routine handles slow-path WQ entry consumed event by invoking the
14570  * proper WQ release routine to the slow-path WQ.
14571  **/
14572 static void
14573 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
14574                              struct lpfc_wcqe_release *wcqe)
14575 {
14576         /* sanity check on queue memory */
14577         if (unlikely(!phba->sli4_hba.els_wq))
14578                 return;
14579         /* Check for the slow-path ELS work queue */
14580         if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
14581                 lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
14582                                      bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14583         else
14584                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14585                                 "2579 Slow-path wqe consume event carries "
14586                                 "miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
14587                                 bf_get(lpfc_wcqe_r_wqe_index, wcqe),
14588                                 phba->sli4_hba.els_wq->queue_id);
14589 }
14590
14591 /**
14592  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
14593  * @phba: Pointer to HBA context object.
14594  * @cq: Pointer to a WQ completion queue.
14595  * @wcqe: Pointer to work-queue completion queue entry.
14596  *
14597  * This routine handles an XRI abort event.
14598  *
14599  * Return: true if work posted to worker thread, otherwise false.
14600  **/
14601 static bool
14602 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
14603                                    struct lpfc_queue *cq,
14604                                    struct sli4_wcqe_xri_aborted *wcqe)
14605 {
14606         bool workposted = false;
14607         struct lpfc_cq_event *cq_event;
14608         unsigned long iflags;
14609
14610         switch (cq->subtype) {
14611         case LPFC_IO:
14612                 lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
14613                 if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14614                         /* Notify aborted XRI for NVME work queue */
14615                         if (phba->nvmet_support)
14616                                 lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
14617                 }
14618                 workposted = false;
14619                 break;
14620         case LPFC_NVME_LS: /* NVME LS uses ELS resources */
14621         case LPFC_ELS:
14622                 cq_event = lpfc_cq_event_setup(phba, wcqe, sizeof(*wcqe));
14623                 if (!cq_event) {
14624                         workposted = false;
14625                         break;
14626                 }
14627                 cq_event->hdwq = cq->hdwq;
14628                 spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14629                                   iflags);
14630                 list_add_tail(&cq_event->list,
14631                               &phba->sli4_hba.sp_els_xri_aborted_work_queue);
14632                 /* Set the els xri abort event flag */
14633                 phba->hba_flag |= ELS_XRI_ABORT_EVENT;
14634                 spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14635                                        iflags);
14636                 workposted = true;
14637                 break;
14638         default:
14639                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14640                                 "0603 Invalid CQ subtype %d: "
14641                                 "%08x %08x %08x %08x\n",
14642                                 cq->subtype, wcqe->word0, wcqe->parameter,
14643                                 wcqe->word2, wcqe->word3);
14644                 workposted = false;
14645                 break;
14646         }
14647         return workposted;
14648 }
14649
14650 #define FC_RCTL_MDS_DIAGS       0xF4
14651
14652 /**
14653  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
14654  * @phba: Pointer to HBA context object.
14655  * @rcqe: Pointer to receive-queue completion queue entry.
14656  *
14657  * This routine process a receive-queue completion queue entry.
14658  *
14659  * Return: true if work posted to worker thread, otherwise false.
14660  **/
14661 static bool
14662 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
14663 {
14664         bool workposted = false;
14665         struct fc_frame_header *fc_hdr;
14666         struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
14667         struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
14668         struct lpfc_nvmet_tgtport *tgtp;
14669         struct hbq_dmabuf *dma_buf;
14670         uint32_t status, rq_id;
14671         unsigned long iflags;
14672
14673         /* sanity check on queue memory */
14674         if (unlikely(!hrq) || unlikely(!drq))
14675                 return workposted;
14676
14677         if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14678                 rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14679         else
14680                 rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14681         if (rq_id != hrq->queue_id)
14682                 goto out;
14683
14684         status = bf_get(lpfc_rcqe_status, rcqe);
14685         switch (status) {
14686         case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14687                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14688                                 "2537 Receive Frame Truncated!!\n");
14689                 fallthrough;
14690         case FC_STATUS_RQ_SUCCESS:
14691                 spin_lock_irqsave(&phba->hbalock, iflags);
14692                 lpfc_sli4_rq_release(hrq, drq);
14693                 dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14694                 if (!dma_buf) {
14695                         hrq->RQ_no_buf_found++;
14696                         spin_unlock_irqrestore(&phba->hbalock, iflags);
14697                         goto out;
14698                 }
14699                 hrq->RQ_rcv_buf++;
14700                 hrq->RQ_buf_posted--;
14701                 memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
14702
14703                 fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14704
14705                 if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
14706                     fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
14707                         spin_unlock_irqrestore(&phba->hbalock, iflags);
14708                         /* Handle MDS Loopback frames */
14709                         if  (!(phba->pport->load_flag & FC_UNLOADING))
14710                                 lpfc_sli4_handle_mds_loopback(phba->pport,
14711                                                               dma_buf);
14712                         else
14713                                 lpfc_in_buf_free(phba, &dma_buf->dbuf);
14714                         break;
14715                 }
14716
14717                 /* save off the frame for the work thread to process */
14718                 list_add_tail(&dma_buf->cq_event.list,
14719                               &phba->sli4_hba.sp_queue_event);
14720                 /* Frame received */
14721                 phba->hba_flag |= HBA_SP_QUEUE_EVT;
14722                 spin_unlock_irqrestore(&phba->hbalock, iflags);
14723                 workposted = true;
14724                 break;
14725         case FC_STATUS_INSUFF_BUF_FRM_DISC:
14726                 if (phba->nvmet_support) {
14727                         tgtp = phba->targetport->private;
14728                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14729                                         "6402 RQE Error x%x, posted %d err_cnt "
14730                                         "%d: %x %x %x\n",
14731                                         status, hrq->RQ_buf_posted,
14732                                         hrq->RQ_no_posted_buf,
14733                                         atomic_read(&tgtp->rcv_fcp_cmd_in),
14734                                         atomic_read(&tgtp->rcv_fcp_cmd_out),
14735                                         atomic_read(&tgtp->xmt_fcp_release));
14736                 }
14737                 fallthrough;
14738
14739         case FC_STATUS_INSUFF_BUF_NEED_BUF:
14740                 hrq->RQ_no_posted_buf++;
14741                 /* Post more buffers if possible */
14742                 spin_lock_irqsave(&phba->hbalock, iflags);
14743                 phba->hba_flag |= HBA_POST_RECEIVE_BUFFER;
14744                 spin_unlock_irqrestore(&phba->hbalock, iflags);
14745                 workposted = true;
14746                 break;
14747         }
14748 out:
14749         return workposted;
14750 }
14751
14752 /**
14753  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
14754  * @phba: Pointer to HBA context object.
14755  * @cq: Pointer to the completion queue.
14756  * @cqe: Pointer to a completion queue entry.
14757  *
14758  * This routine process a slow-path work-queue or receive queue completion queue
14759  * entry.
14760  *
14761  * Return: true if work posted to worker thread, otherwise false.
14762  **/
14763 static bool
14764 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14765                          struct lpfc_cqe *cqe)
14766 {
14767         struct lpfc_cqe cqevt;
14768         bool workposted = false;
14769
14770         /* Copy the work queue CQE and convert endian order if needed */
14771         lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
14772
14773         /* Check and process for different type of WCQE and dispatch */
14774         switch (bf_get(lpfc_cqe_code, &cqevt)) {
14775         case CQE_CODE_COMPL_WQE:
14776                 /* Process the WQ/RQ complete event */
14777                 phba->last_completion_time = jiffies;
14778                 workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
14779                                 (struct lpfc_wcqe_complete *)&cqevt);
14780                 break;
14781         case CQE_CODE_RELEASE_WQE:
14782                 /* Process the WQ release event */
14783                 lpfc_sli4_sp_handle_rel_wcqe(phba,
14784                                 (struct lpfc_wcqe_release *)&cqevt);
14785                 break;
14786         case CQE_CODE_XRI_ABORTED:
14787                 /* Process the WQ XRI abort event */
14788                 phba->last_completion_time = jiffies;
14789                 workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14790                                 (struct sli4_wcqe_xri_aborted *)&cqevt);
14791                 break;
14792         case CQE_CODE_RECEIVE:
14793         case CQE_CODE_RECEIVE_V1:
14794                 /* Process the RQ event */
14795                 phba->last_completion_time = jiffies;
14796                 workposted = lpfc_sli4_sp_handle_rcqe(phba,
14797                                 (struct lpfc_rcqe *)&cqevt);
14798                 break;
14799         default:
14800                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14801                                 "0388 Not a valid WCQE code: x%x\n",
14802                                 bf_get(lpfc_cqe_code, &cqevt));
14803                 break;
14804         }
14805         return workposted;
14806 }
14807
14808 /**
14809  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
14810  * @phba: Pointer to HBA context object.
14811  * @eqe: Pointer to fast-path event queue entry.
14812  * @speq: Pointer to slow-path event queue.
14813  *
14814  * This routine process a event queue entry from the slow-path event queue.
14815  * It will check the MajorCode and MinorCode to determine this is for a
14816  * completion event on a completion queue, if not, an error shall be logged
14817  * and just return. Otherwise, it will get to the corresponding completion
14818  * queue and process all the entries on that completion queue, rearm the
14819  * completion queue, and then return.
14820  *
14821  **/
14822 static void
14823 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14824         struct lpfc_queue *speq)
14825 {
14826         struct lpfc_queue *cq = NULL, *childq;
14827         uint16_t cqid;
14828         int ret = 0;
14829
14830         /* Get the reference to the corresponding CQ */
14831         cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14832
14833         list_for_each_entry(childq, &speq->child_list, list) {
14834                 if (childq->queue_id == cqid) {
14835                         cq = childq;
14836                         break;
14837                 }
14838         }
14839         if (unlikely(!cq)) {
14840                 if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14841                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14842                                         "0365 Slow-path CQ identifier "
14843                                         "(%d) does not exist\n", cqid);
14844                 return;
14845         }
14846
14847         /* Save EQ associated with this CQ */
14848         cq->assoc_qp = speq;
14849
14850         if (is_kdump_kernel())
14851                 ret = queue_work(phba->wq, &cq->spwork);
14852         else
14853                 ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
14854
14855         if (!ret)
14856                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14857                                 "0390 Cannot schedule queue work "
14858                                 "for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14859                                 cqid, cq->queue_id, raw_smp_processor_id());
14860 }
14861
14862 /**
14863  * __lpfc_sli4_process_cq - Process elements of a CQ
14864  * @phba: Pointer to HBA context object.
14865  * @cq: Pointer to CQ to be processed
14866  * @handler: Routine to process each cqe
14867  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
14868  * @poll_mode: Polling mode we were called from
14869  *
14870  * This routine processes completion queue entries in a CQ. While a valid
14871  * queue element is found, the handler is called. During processing checks
14872  * are made for periodic doorbell writes to let the hardware know of
14873  * element consumption.
14874  *
14875  * If the max limit on cqes to process is hit, or there are no more valid
14876  * entries, the loop stops. If we processed a sufficient number of elements,
14877  * meaning there is sufficient load, rather than rearming and generating
14878  * another interrupt, a cq rescheduling delay will be set. A delay of 0
14879  * indicates no rescheduling.
14880  *
14881  * Returns True if work scheduled, False otherwise.
14882  **/
14883 static bool
14884 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
14885         bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
14886                         struct lpfc_cqe *), unsigned long *delay,
14887                         enum lpfc_poll_mode poll_mode)
14888 {
14889         struct lpfc_cqe *cqe;
14890         bool workposted = false;
14891         int count = 0, consumed = 0;
14892         bool arm = true;
14893
14894         /* default - no reschedule */
14895         *delay = 0;
14896
14897         if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
14898                 goto rearm_and_exit;
14899
14900         /* Process all the entries to the CQ */
14901         cq->q_flag = 0;
14902         cqe = lpfc_sli4_cq_get(cq);
14903         while (cqe) {
14904                 workposted |= handler(phba, cq, cqe);
14905                 __lpfc_sli4_consume_cqe(phba, cq, cqe);
14906
14907                 consumed++;
14908                 if (!(++count % cq->max_proc_limit))
14909                         break;
14910
14911                 if (!(count % cq->notify_interval)) {
14912                         phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14913                                                 LPFC_QUEUE_NOARM);
14914                         consumed = 0;
14915                         cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
14916                 }
14917
14918                 if (count == LPFC_NVMET_CQ_NOTIFY)
14919                         cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
14920
14921                 cqe = lpfc_sli4_cq_get(cq);
14922         }
14923         if (count >= phba->cfg_cq_poll_threshold) {
14924                 *delay = 1;
14925                 arm = false;
14926         }
14927
14928         /* Note: complete the irq_poll softirq before rearming CQ */
14929         if (poll_mode == LPFC_IRQ_POLL)
14930                 irq_poll_complete(&cq->iop);
14931
14932         /* Track the max number of CQEs processed in 1 EQ */
14933         if (count > cq->CQ_max_cqe)
14934                 cq->CQ_max_cqe = count;
14935
14936         cq->assoc_qp->EQ_cqe_cnt += count;
14937
14938         /* Catch the no cq entry condition */
14939         if (unlikely(count == 0))
14940                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14941                                 "0369 No entry from completion queue "
14942                                 "qid=%d\n", cq->queue_id);
14943
14944         xchg(&cq->queue_claimed, 0);
14945
14946 rearm_and_exit:
14947         phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14948                         arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
14949
14950         return workposted;
14951 }
14952
14953 /**
14954  * __lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
14955  * @cq: pointer to CQ to process
14956  *
14957  * This routine calls the cq processing routine with a handler specific
14958  * to the type of queue bound to it.
14959  *
14960  * The CQ routine returns two values: the first is the calling status,
14961  * which indicates whether work was queued to the  background discovery
14962  * thread. If true, the routine should wakeup the discovery thread;
14963  * the second is the delay parameter. If non-zero, rather than rearming
14964  * the CQ and yet another interrupt, the CQ handler should be queued so
14965  * that it is processed in a subsequent polling action. The value of
14966  * the delay indicates when to reschedule it.
14967  **/
14968 static void
14969 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
14970 {
14971         struct lpfc_hba *phba = cq->phba;
14972         unsigned long delay;
14973         bool workposted = false;
14974         int ret = 0;
14975
14976         /* Process and rearm the CQ */
14977         switch (cq->type) {
14978         case LPFC_MCQ:
14979                 workposted |= __lpfc_sli4_process_cq(phba, cq,
14980                                                 lpfc_sli4_sp_handle_mcqe,
14981                                                 &delay, LPFC_QUEUE_WORK);
14982                 break;
14983         case LPFC_WCQ:
14984                 if (cq->subtype == LPFC_IO)
14985                         workposted |= __lpfc_sli4_process_cq(phba, cq,
14986                                                 lpfc_sli4_fp_handle_cqe,
14987                                                 &delay, LPFC_QUEUE_WORK);
14988                 else
14989                         workposted |= __lpfc_sli4_process_cq(phba, cq,
14990                                                 lpfc_sli4_sp_handle_cqe,
14991                                                 &delay, LPFC_QUEUE_WORK);
14992                 break;
14993         default:
14994                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14995                                 "0370 Invalid completion queue type (%d)\n",
14996                                 cq->type);
14997                 return;
14998         }
14999
15000         if (delay) {
15001                 if (is_kdump_kernel())
15002                         ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
15003                                                 delay);
15004                 else
15005                         ret = queue_delayed_work_on(cq->chann, phba->wq,
15006                                                 &cq->sched_spwork, delay);
15007                 if (!ret)
15008                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15009                                 "0394 Cannot schedule queue work "
15010                                 "for cqid=%d on CPU %d\n",
15011                                 cq->queue_id, cq->chann);
15012         }
15013
15014         /* wake up worker thread if there are works to be done */
15015         if (workposted)
15016                 lpfc_worker_wake_up(phba);
15017 }
15018
15019 /**
15020  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
15021  *   interrupt
15022  * @work: pointer to work element
15023  *
15024  * translates from the work handler and calls the slow-path handler.
15025  **/
15026 static void
15027 lpfc_sli4_sp_process_cq(struct work_struct *work)
15028 {
15029         struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
15030
15031         __lpfc_sli4_sp_process_cq(cq);
15032 }
15033
15034 /**
15035  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
15036  * @work: pointer to work element
15037  *
15038  * translates from the work handler and calls the slow-path handler.
15039  **/
15040 static void
15041 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
15042 {
15043         struct lpfc_queue *cq = container_of(to_delayed_work(work),
15044                                         struct lpfc_queue, sched_spwork);
15045
15046         __lpfc_sli4_sp_process_cq(cq);
15047 }
15048
15049 /**
15050  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
15051  * @phba: Pointer to HBA context object.
15052  * @cq: Pointer to associated CQ
15053  * @wcqe: Pointer to work-queue completion queue entry.
15054  *
15055  * This routine process a fast-path work queue completion entry from fast-path
15056  * event queue for FCP command response completion.
15057  **/
15058 static void
15059 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15060                              struct lpfc_wcqe_complete *wcqe)
15061 {
15062         struct lpfc_sli_ring *pring = cq->pring;
15063         struct lpfc_iocbq *cmdiocbq;
15064         struct lpfc_iocbq irspiocbq;
15065         unsigned long iflags;
15066
15067         /* Check for response status */
15068         if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
15069                 /* If resource errors reported from HBA, reduce queue
15070                  * depth of the SCSI device.
15071                  */
15072                 if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
15073                      IOSTAT_LOCAL_REJECT)) &&
15074                     ((wcqe->parameter & IOERR_PARAM_MASK) ==
15075                      IOERR_NO_RESOURCES))
15076                         phba->lpfc_rampdown_queue_depth(phba);
15077
15078                 /* Log the cmpl status */
15079                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
15080                                 "0373 FCP CQE cmpl: status=x%x: "
15081                                 "CQE: %08x %08x %08x %08x\n",
15082                                 bf_get(lpfc_wcqe_c_status, wcqe),
15083                                 wcqe->word0, wcqe->total_data_placed,
15084                                 wcqe->parameter, wcqe->word3);
15085         }
15086
15087         /* Look up the FCP command IOCB and create pseudo response IOCB */
15088         spin_lock_irqsave(&pring->ring_lock, iflags);
15089         pring->stats.iocb_event++;
15090         spin_unlock_irqrestore(&pring->ring_lock, iflags);
15091         cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
15092                                 bf_get(lpfc_wcqe_c_request_tag, wcqe));
15093         if (unlikely(!cmdiocbq)) {
15094                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15095                                 "0374 FCP complete with no corresponding "
15096                                 "cmdiocb: iotag (%d)\n",
15097                                 bf_get(lpfc_wcqe_c_request_tag, wcqe));
15098                 return;
15099         }
15100 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
15101         cmdiocbq->isr_timestamp = cq->isr_timestamp;
15102 #endif
15103         if (cmdiocbq->iocb_cmpl == NULL) {
15104                 if (cmdiocbq->wqe_cmpl) {
15105                         /* For FCP the flag is cleared in wqe_cmpl */
15106                         if (!(cmdiocbq->iocb_flag & LPFC_IO_FCP) &&
15107                             cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
15108                                 spin_lock_irqsave(&phba->hbalock, iflags);
15109                                 cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
15110                                 spin_unlock_irqrestore(&phba->hbalock, iflags);
15111                         }
15112
15113                         /* Pass the cmd_iocb and the wcqe to the upper layer */
15114                         (cmdiocbq->wqe_cmpl)(phba, cmdiocbq, wcqe);
15115                         return;
15116                 }
15117                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15118                                 "0375 FCP cmdiocb not callback function "
15119                                 "iotag: (%d)\n",
15120                                 bf_get(lpfc_wcqe_c_request_tag, wcqe));
15121                 return;
15122         }
15123
15124         /* Only SLI4 non-IO commands stil use IOCB */
15125         /* Fake the irspiocb and copy necessary response information */
15126         lpfc_sli4_iocb_param_transfer(phba, &irspiocbq, cmdiocbq, wcqe);
15127
15128         if (cmdiocbq->iocb_flag & LPFC_DRIVER_ABORTED) {
15129                 spin_lock_irqsave(&phba->hbalock, iflags);
15130                 cmdiocbq->iocb_flag &= ~LPFC_DRIVER_ABORTED;
15131                 spin_unlock_irqrestore(&phba->hbalock, iflags);
15132         }
15133
15134         /* Pass the cmd_iocb and the rsp state to the upper layer */
15135         (cmdiocbq->iocb_cmpl)(phba, cmdiocbq, &irspiocbq);
15136 }
15137
15138 /**
15139  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
15140  * @phba: Pointer to HBA context object.
15141  * @cq: Pointer to completion queue.
15142  * @wcqe: Pointer to work-queue completion queue entry.
15143  *
15144  * This routine handles an fast-path WQ entry consumed event by invoking the
15145  * proper WQ release routine to the slow-path WQ.
15146  **/
15147 static void
15148 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15149                              struct lpfc_wcqe_release *wcqe)
15150 {
15151         struct lpfc_queue *childwq;
15152         bool wqid_matched = false;
15153         uint16_t hba_wqid;
15154
15155         /* Check for fast-path FCP work queue release */
15156         hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
15157         list_for_each_entry(childwq, &cq->child_list, list) {
15158                 if (childwq->queue_id == hba_wqid) {
15159                         lpfc_sli4_wq_release(childwq,
15160                                         bf_get(lpfc_wcqe_r_wqe_index, wcqe));
15161                         if (childwq->q_flag & HBA_NVMET_WQFULL)
15162                                 lpfc_nvmet_wqfull_process(phba, childwq);
15163                         wqid_matched = true;
15164                         break;
15165                 }
15166         }
15167         /* Report warning log message if no match found */
15168         if (wqid_matched != true)
15169                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15170                                 "2580 Fast-path wqe consume event carries "
15171                                 "miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
15172 }
15173
15174 /**
15175  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
15176  * @phba: Pointer to HBA context object.
15177  * @cq: Pointer to completion queue.
15178  * @rcqe: Pointer to receive-queue completion queue entry.
15179  *
15180  * This routine process a receive-queue completion queue entry.
15181  *
15182  * Return: true if work posted to worker thread, otherwise false.
15183  **/
15184 static bool
15185 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15186                             struct lpfc_rcqe *rcqe)
15187 {
15188         bool workposted = false;
15189         struct lpfc_queue *hrq;
15190         struct lpfc_queue *drq;
15191         struct rqb_dmabuf *dma_buf;
15192         struct fc_frame_header *fc_hdr;
15193         struct lpfc_nvmet_tgtport *tgtp;
15194         uint32_t status, rq_id;
15195         unsigned long iflags;
15196         uint32_t fctl, idx;
15197
15198         if ((phba->nvmet_support == 0) ||
15199             (phba->sli4_hba.nvmet_cqset == NULL))
15200                 return workposted;
15201
15202         idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
15203         hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
15204         drq = phba->sli4_hba.nvmet_mrq_data[idx];
15205
15206         /* sanity check on queue memory */
15207         if (unlikely(!hrq) || unlikely(!drq))
15208                 return workposted;
15209
15210         if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
15211                 rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
15212         else
15213                 rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
15214
15215         if ((phba->nvmet_support == 0) ||
15216             (rq_id != hrq->queue_id))
15217                 return workposted;
15218
15219         status = bf_get(lpfc_rcqe_status, rcqe);
15220         switch (status) {
15221         case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
15222                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15223                                 "6126 Receive Frame Truncated!!\n");
15224                 fallthrough;
15225         case FC_STATUS_RQ_SUCCESS:
15226                 spin_lock_irqsave(&phba->hbalock, iflags);
15227                 lpfc_sli4_rq_release(hrq, drq);
15228                 dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15229                 if (!dma_buf) {
15230                         hrq->RQ_no_buf_found++;
15231                         spin_unlock_irqrestore(&phba->hbalock, iflags);
15232                         goto out;
15233                 }
15234                 spin_unlock_irqrestore(&phba->hbalock, iflags);
15235                 hrq->RQ_rcv_buf++;
15236                 hrq->RQ_buf_posted--;
15237                 fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
15238
15239                 /* Just some basic sanity checks on FCP Command frame */
15240                 fctl = (fc_hdr->fh_f_ctl[0] << 16 |
15241                         fc_hdr->fh_f_ctl[1] << 8 |
15242                         fc_hdr->fh_f_ctl[2]);
15243                 if (((fctl &
15244                     (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
15245                     (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
15246                     (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
15247                         goto drop;
15248
15249                 if (fc_hdr->fh_type == FC_TYPE_FCP) {
15250                         dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
15251                         lpfc_nvmet_unsol_fcp_event(
15252                                 phba, idx, dma_buf, cq->isr_timestamp,
15253                                 cq->q_flag & HBA_NVMET_CQ_NOTIFY);
15254                         return false;
15255                 }
15256 drop:
15257                 lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15258                 break;
15259         case FC_STATUS_INSUFF_BUF_FRM_DISC:
15260                 if (phba->nvmet_support) {
15261                         tgtp = phba->targetport->private;
15262                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15263                                         "6401 RQE Error x%x, posted %d err_cnt "
15264                                         "%d: %x %x %x\n",
15265                                         status, hrq->RQ_buf_posted,
15266                                         hrq->RQ_no_posted_buf,
15267                                         atomic_read(&tgtp->rcv_fcp_cmd_in),
15268                                         atomic_read(&tgtp->rcv_fcp_cmd_out),
15269                                         atomic_read(&tgtp->xmt_fcp_release));
15270                 }
15271                 fallthrough;
15272
15273         case FC_STATUS_INSUFF_BUF_NEED_BUF:
15274                 hrq->RQ_no_posted_buf++;
15275                 /* Post more buffers if possible */
15276                 break;
15277         }
15278 out:
15279         return workposted;
15280 }
15281
15282 /**
15283  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
15284  * @phba: adapter with cq
15285  * @cq: Pointer to the completion queue.
15286  * @cqe: Pointer to fast-path completion queue entry.
15287  *
15288  * This routine process a fast-path work queue completion entry from fast-path
15289  * event queue for FCP command response completion.
15290  *
15291  * Return: true if work posted to worker thread, otherwise false.
15292  **/
15293 static bool
15294 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15295                          struct lpfc_cqe *cqe)
15296 {
15297         struct lpfc_wcqe_release wcqe;
15298         bool workposted = false;
15299
15300         /* Copy the work queue CQE and convert endian order if needed */
15301         lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
15302
15303         /* Check and process for different type of WCQE and dispatch */
15304         switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
15305         case CQE_CODE_COMPL_WQE:
15306         case CQE_CODE_NVME_ERSP:
15307                 cq->CQ_wq++;
15308                 /* Process the WQ complete event */
15309                 phba->last_completion_time = jiffies;
15310                 if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
15311                         lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
15312                                 (struct lpfc_wcqe_complete *)&wcqe);
15313                 break;
15314         case CQE_CODE_RELEASE_WQE:
15315                 cq->CQ_release_wqe++;
15316                 /* Process the WQ release event */
15317                 lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
15318                                 (struct lpfc_wcqe_release *)&wcqe);
15319                 break;
15320         case CQE_CODE_XRI_ABORTED:
15321                 cq->CQ_xri_aborted++;
15322                 /* Process the WQ XRI abort event */
15323                 phba->last_completion_time = jiffies;
15324                 workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
15325                                 (struct sli4_wcqe_xri_aborted *)&wcqe);
15326                 break;
15327         case CQE_CODE_RECEIVE_V1:
15328         case CQE_CODE_RECEIVE:
15329                 phba->last_completion_time = jiffies;
15330                 if (cq->subtype == LPFC_NVMET) {
15331                         workposted = lpfc_sli4_nvmet_handle_rcqe(
15332                                 phba, cq, (struct lpfc_rcqe *)&wcqe);
15333                 }
15334                 break;
15335         default:
15336                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15337                                 "0144 Not a valid CQE code: x%x\n",
15338                                 bf_get(lpfc_wcqe_c_code, &wcqe));
15339                 break;
15340         }
15341         return workposted;
15342 }
15343
15344 /**
15345  * lpfc_sli4_sched_cq_work - Schedules cq work
15346  * @phba: Pointer to HBA context object.
15347  * @cq: Pointer to CQ
15348  * @cqid: CQ ID
15349  *
15350  * This routine checks the poll mode of the CQ corresponding to
15351  * cq->chann, then either schedules a softirq or queue_work to complete
15352  * cq work.
15353  *
15354  * queue_work path is taken if in NVMET mode, or if poll_mode is in
15355  * LPFC_QUEUE_WORK mode.  Otherwise, softirq path is taken.
15356  *
15357  **/
15358 static void lpfc_sli4_sched_cq_work(struct lpfc_hba *phba,
15359                                     struct lpfc_queue *cq, uint16_t cqid)
15360 {
15361         int ret = 0;
15362
15363         switch (cq->poll_mode) {
15364         case LPFC_IRQ_POLL:
15365                 /* CGN mgmt is mutually exclusive from softirq processing */
15366                 if (phba->cmf_active_mode == LPFC_CFG_OFF) {
15367                         irq_poll_sched(&cq->iop);
15368                         break;
15369                 }
15370                 fallthrough;
15371         case LPFC_QUEUE_WORK:
15372         default:
15373                 if (is_kdump_kernel())
15374                         ret = queue_work(phba->wq, &cq->irqwork);
15375                 else
15376                         ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
15377                 if (!ret)
15378                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15379                                         "0383 Cannot schedule queue work "
15380                                         "for CQ eqcqid=%d, cqid=%d on CPU %d\n",
15381                                         cqid, cq->queue_id,
15382                                         raw_smp_processor_id());
15383         }
15384 }
15385
15386 /**
15387  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
15388  * @phba: Pointer to HBA context object.
15389  * @eq: Pointer to the queue structure.
15390  * @eqe: Pointer to fast-path event queue entry.
15391  *
15392  * This routine process a event queue entry from the fast-path event queue.
15393  * It will check the MajorCode and MinorCode to determine this is for a
15394  * completion event on a completion queue, if not, an error shall be logged
15395  * and just return. Otherwise, it will get to the corresponding completion
15396  * queue and process all the entries on the completion queue, rearm the
15397  * completion queue, and then return.
15398  **/
15399 static void
15400 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
15401                          struct lpfc_eqe *eqe)
15402 {
15403         struct lpfc_queue *cq = NULL;
15404         uint32_t qidx = eq->hdwq;
15405         uint16_t cqid, id;
15406
15407         if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
15408                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15409                                 "0366 Not a valid completion "
15410                                 "event: majorcode=x%x, minorcode=x%x\n",
15411                                 bf_get_le32(lpfc_eqe_major_code, eqe),
15412                                 bf_get_le32(lpfc_eqe_minor_code, eqe));
15413                 return;
15414         }
15415
15416         /* Get the reference to the corresponding CQ */
15417         cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
15418
15419         /* Use the fast lookup method first */
15420         if (cqid <= phba->sli4_hba.cq_max) {
15421                 cq = phba->sli4_hba.cq_lookup[cqid];
15422                 if (cq)
15423                         goto  work_cq;
15424         }
15425
15426         /* Next check for NVMET completion */
15427         if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
15428                 id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
15429                 if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
15430                         /* Process NVMET unsol rcv */
15431                         cq = phba->sli4_hba.nvmet_cqset[cqid - id];
15432                         goto  process_cq;
15433                 }
15434         }
15435
15436         if (phba->sli4_hba.nvmels_cq &&
15437             (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
15438                 /* Process NVME unsol rcv */
15439                 cq = phba->sli4_hba.nvmels_cq;
15440         }
15441
15442         /* Otherwise this is a Slow path event */
15443         if (cq == NULL) {
15444                 lpfc_sli4_sp_handle_eqe(phba, eqe,
15445                                         phba->sli4_hba.hdwq[qidx].hba_eq);
15446                 return;
15447         }
15448
15449 process_cq:
15450         if (unlikely(cqid != cq->queue_id)) {
15451                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15452                                 "0368 Miss-matched fast-path completion "
15453                                 "queue identifier: eqcqid=%d, fcpcqid=%d\n",
15454                                 cqid, cq->queue_id);
15455                 return;
15456         }
15457
15458 work_cq:
15459 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
15460         if (phba->ktime_on)
15461                 cq->isr_timestamp = ktime_get_ns();
15462         else
15463                 cq->isr_timestamp = 0;
15464 #endif
15465         lpfc_sli4_sched_cq_work(phba, cq, cqid);
15466 }
15467
15468 /**
15469  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
15470  * @cq: Pointer to CQ to be processed
15471  * @poll_mode: Enum lpfc_poll_state to determine poll mode
15472  *
15473  * This routine calls the cq processing routine with the handler for
15474  * fast path CQEs.
15475  *
15476  * The CQ routine returns two values: the first is the calling status,
15477  * which indicates whether work was queued to the  background discovery
15478  * thread. If true, the routine should wakeup the discovery thread;
15479  * the second is the delay parameter. If non-zero, rather than rearming
15480  * the CQ and yet another interrupt, the CQ handler should be queued so
15481  * that it is processed in a subsequent polling action. The value of
15482  * the delay indicates when to reschedule it.
15483  **/
15484 static void
15485 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq,
15486                            enum lpfc_poll_mode poll_mode)
15487 {
15488         struct lpfc_hba *phba = cq->phba;
15489         unsigned long delay;
15490         bool workposted = false;
15491         int ret = 0;
15492
15493         /* process and rearm the CQ */
15494         workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
15495                                              &delay, poll_mode);
15496
15497         if (delay) {
15498                 if (is_kdump_kernel())
15499                         ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
15500                                                 delay);
15501                 else
15502                         ret = queue_delayed_work_on(cq->chann, phba->wq,
15503                                                 &cq->sched_irqwork, delay);
15504                 if (!ret)
15505                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15506                                         "0367 Cannot schedule queue work "
15507                                         "for cqid=%d on CPU %d\n",
15508                                         cq->queue_id, cq->chann);
15509         }
15510
15511         /* wake up worker thread if there are works to be done */
15512         if (workposted)
15513                 lpfc_worker_wake_up(phba);
15514 }
15515
15516 /**
15517  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
15518  *   interrupt
15519  * @work: pointer to work element
15520  *
15521  * translates from the work handler and calls the fast-path handler.
15522  **/
15523 static void
15524 lpfc_sli4_hba_process_cq(struct work_struct *work)
15525 {
15526         struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
15527
15528         __lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
15529 }
15530
15531 /**
15532  * lpfc_sli4_dly_hba_process_cq - fast-path work handler when started by timer
15533  * @work: pointer to work element
15534  *
15535  * translates from the work handler and calls the fast-path handler.
15536  **/
15537 static void
15538 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
15539 {
15540         struct lpfc_queue *cq = container_of(to_delayed_work(work),
15541                                         struct lpfc_queue, sched_irqwork);
15542
15543         __lpfc_sli4_hba_process_cq(cq, LPFC_QUEUE_WORK);
15544 }
15545
15546 /**
15547  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
15548  * @irq: Interrupt number.
15549  * @dev_id: The device context pointer.
15550  *
15551  * This function is directly called from the PCI layer as an interrupt
15552  * service routine when device with SLI-4 interface spec is enabled with
15553  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
15554  * ring event in the HBA. However, when the device is enabled with either
15555  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
15556  * device-level interrupt handler. When the PCI slot is in error recovery
15557  * or the HBA is undergoing initialization, the interrupt handler will not
15558  * process the interrupt. The SCSI FCP fast-path ring event are handled in
15559  * the intrrupt context. This function is called without any lock held.
15560  * It gets the hbalock to access and update SLI data structures. Note that,
15561  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
15562  * equal to that of FCP CQ index.
15563  *
15564  * The link attention and ELS ring attention events are handled
15565  * by the worker thread. The interrupt handler signals the worker thread
15566  * and returns for these events. This function is called without any lock
15567  * held. It gets the hbalock to access and update SLI data structures.
15568  *
15569  * This function returns IRQ_HANDLED when interrupt is handled else it
15570  * returns IRQ_NONE.
15571  **/
15572 irqreturn_t
15573 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
15574 {
15575         struct lpfc_hba *phba;
15576         struct lpfc_hba_eq_hdl *hba_eq_hdl;
15577         struct lpfc_queue *fpeq;
15578         unsigned long iflag;
15579         int ecount = 0;
15580         int hba_eqidx;
15581         struct lpfc_eq_intr_info *eqi;
15582
15583         /* Get the driver's phba structure from the dev_id */
15584         hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
15585         phba = hba_eq_hdl->phba;
15586         hba_eqidx = hba_eq_hdl->idx;
15587
15588         if (unlikely(!phba))
15589                 return IRQ_NONE;
15590         if (unlikely(!phba->sli4_hba.hdwq))
15591                 return IRQ_NONE;
15592
15593         /* Get to the EQ struct associated with this vector */
15594         fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
15595         if (unlikely(!fpeq))
15596                 return IRQ_NONE;
15597
15598         /* Check device state for handling interrupt */
15599         if (unlikely(lpfc_intr_state_check(phba))) {
15600                 /* Check again for link_state with lock held */
15601                 spin_lock_irqsave(&phba->hbalock, iflag);
15602                 if (phba->link_state < LPFC_LINK_DOWN)
15603                         /* Flush, clear interrupt, and rearm the EQ */
15604                         lpfc_sli4_eqcq_flush(phba, fpeq);
15605                 spin_unlock_irqrestore(&phba->hbalock, iflag);
15606                 return IRQ_NONE;
15607         }
15608
15609         eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
15610         eqi->icnt++;
15611
15612         fpeq->last_cpu = raw_smp_processor_id();
15613
15614         if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
15615             fpeq->q_flag & HBA_EQ_DELAY_CHK &&
15616             phba->cfg_auto_imax &&
15617             fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
15618             phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
15619                 lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
15620
15621         /* process and rearm the EQ */
15622         ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM);
15623
15624         if (unlikely(ecount == 0)) {
15625                 fpeq->EQ_no_entry++;
15626                 if (phba->intr_type == MSIX)
15627                         /* MSI-X treated interrupt served as no EQ share INT */
15628                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15629                                         "0358 MSI-X interrupt with no EQE\n");
15630                 else
15631                         /* Non MSI-X treated on interrupt as EQ share INT */
15632                         return IRQ_NONE;
15633         }
15634
15635         return IRQ_HANDLED;
15636 } /* lpfc_sli4_hba_intr_handler */
15637
15638 /**
15639  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
15640  * @irq: Interrupt number.
15641  * @dev_id: The device context pointer.
15642  *
15643  * This function is the device-level interrupt handler to device with SLI-4
15644  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
15645  * interrupt mode is enabled and there is an event in the HBA which requires
15646  * driver attention. This function invokes the slow-path interrupt attention
15647  * handling function and fast-path interrupt attention handling function in
15648  * turn to process the relevant HBA attention events. This function is called
15649  * without any lock held. It gets the hbalock to access and update SLI data
15650  * structures.
15651  *
15652  * This function returns IRQ_HANDLED when interrupt is handled, else it
15653  * returns IRQ_NONE.
15654  **/
15655 irqreturn_t
15656 lpfc_sli4_intr_handler(int irq, void *dev_id)
15657 {
15658         struct lpfc_hba  *phba;
15659         irqreturn_t hba_irq_rc;
15660         bool hba_handled = false;
15661         int qidx;
15662
15663         /* Get the driver's phba structure from the dev_id */
15664         phba = (struct lpfc_hba *)dev_id;
15665
15666         if (unlikely(!phba))
15667                 return IRQ_NONE;
15668
15669         /*
15670          * Invoke fast-path host attention interrupt handling as appropriate.
15671          */
15672         for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
15673                 hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
15674                                         &phba->sli4_hba.hba_eq_hdl[qidx]);
15675                 if (hba_irq_rc == IRQ_HANDLED)
15676                         hba_handled |= true;
15677         }
15678
15679         return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
15680 } /* lpfc_sli4_intr_handler */
15681
15682 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
15683 {
15684         struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
15685         struct lpfc_queue *eq;
15686         int i = 0;
15687
15688         rcu_read_lock();
15689
15690         list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
15691                 i += lpfc_sli4_poll_eq(eq, LPFC_POLL_SLOWPATH);
15692         if (!list_empty(&phba->poll_list))
15693                 mod_timer(&phba->cpuhp_poll_timer,
15694                           jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15695
15696         rcu_read_unlock();
15697 }
15698
15699 inline int lpfc_sli4_poll_eq(struct lpfc_queue *eq, uint8_t path)
15700 {
15701         struct lpfc_hba *phba = eq->phba;
15702         int i = 0;
15703
15704         /*
15705          * Unlocking an irq is one of the entry point to check
15706          * for re-schedule, but we are good for io submission
15707          * path as midlayer does a get_cpu to glue us in. Flush
15708          * out the invalidate queue so we can see the updated
15709          * value for flag.
15710          */
15711         smp_rmb();
15712
15713         if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
15714                 /* We will not likely get the completion for the caller
15715                  * during this iteration but i guess that's fine.
15716                  * Future io's coming on this eq should be able to
15717                  * pick it up.  As for the case of single io's, they
15718                  * will be handled through a sched from polling timer
15719                  * function which is currently triggered every 1msec.
15720                  */
15721                 i = lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM);
15722
15723         return i;
15724 }
15725
15726 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
15727 {
15728         struct lpfc_hba *phba = eq->phba;
15729
15730         /* kickstart slowpath processing if needed */
15731         if (list_empty(&phba->poll_list))
15732                 mod_timer(&phba->cpuhp_poll_timer,
15733                           jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15734
15735         list_add_rcu(&eq->_poll_list, &phba->poll_list);
15736         synchronize_rcu();
15737 }
15738
15739 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
15740 {
15741         struct lpfc_hba *phba = eq->phba;
15742
15743         /* Disable slowpath processing for this eq.  Kick start the eq
15744          * by RE-ARMING the eq's ASAP
15745          */
15746         list_del_rcu(&eq->_poll_list);
15747         synchronize_rcu();
15748
15749         if (list_empty(&phba->poll_list))
15750                 del_timer_sync(&phba->cpuhp_poll_timer);
15751 }
15752
15753 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
15754 {
15755         struct lpfc_queue *eq, *next;
15756
15757         list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
15758                 list_del(&eq->_poll_list);
15759
15760         INIT_LIST_HEAD(&phba->poll_list);
15761         synchronize_rcu();
15762 }
15763
15764 static inline void
15765 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
15766 {
15767         if (mode == eq->mode)
15768                 return;
15769         /*
15770          * currently this function is only called during a hotplug
15771          * event and the cpu on which this function is executing
15772          * is going offline.  By now the hotplug has instructed
15773          * the scheduler to remove this cpu from cpu active mask.
15774          * So we don't need to work about being put aside by the
15775          * scheduler for a high priority process.  Yes, the inte-
15776          * rrupts could come but they are known to retire ASAP.
15777          */
15778
15779         /* Disable polling in the fastpath */
15780         WRITE_ONCE(eq->mode, mode);
15781         /* flush out the store buffer */
15782         smp_wmb();
15783
15784         /*
15785          * Add this eq to the polling list and start polling. For
15786          * a grace period both interrupt handler and poller will
15787          * try to process the eq _but_ that's fine.  We have a
15788          * synchronization mechanism in place (queue_claimed) to
15789          * deal with it.  This is just a draining phase for int-
15790          * errupt handler (not eq's) as we have guranteed through
15791          * barrier that all the CPUs have seen the new CQ_POLLED
15792          * state. which will effectively disable the REARMING of
15793          * the EQ.  The whole idea is eq's die off eventually as
15794          * we are not rearming EQ's anymore.
15795          */
15796         mode ? lpfc_sli4_add_to_poll_list(eq) :
15797                lpfc_sli4_remove_from_poll_list(eq);
15798 }
15799
15800 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
15801 {
15802         __lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
15803 }
15804
15805 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
15806 {
15807         struct lpfc_hba *phba = eq->phba;
15808
15809         __lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
15810
15811         /* Kick start for the pending io's in h/w.
15812          * Once we switch back to interrupt processing on a eq
15813          * the io path completion will only arm eq's when it
15814          * receives a completion.  But since eq's are in disa-
15815          * rmed state it doesn't receive a completion.  This
15816          * creates a deadlock scenaro.
15817          */
15818         phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
15819 }
15820
15821 /**
15822  * lpfc_sli4_queue_free - free a queue structure and associated memory
15823  * @queue: The queue structure to free.
15824  *
15825  * This function frees a queue structure and the DMAable memory used for
15826  * the host resident queue. This function must be called after destroying the
15827  * queue on the HBA.
15828  **/
15829 void
15830 lpfc_sli4_queue_free(struct lpfc_queue *queue)
15831 {
15832         struct lpfc_dmabuf *dmabuf;
15833
15834         if (!queue)
15835                 return;
15836
15837         if (!list_empty(&queue->wq_list))
15838                 list_del(&queue->wq_list);
15839
15840         while (!list_empty(&queue->page_list)) {
15841                 list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
15842                                  list);
15843                 dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
15844                                   dmabuf->virt, dmabuf->phys);
15845                 kfree(dmabuf);
15846         }
15847         if (queue->rqbp) {
15848                 lpfc_free_rq_buffer(queue->phba, queue);
15849                 kfree(queue->rqbp);
15850         }
15851
15852         if (!list_empty(&queue->cpu_list))
15853                 list_del(&queue->cpu_list);
15854
15855         kfree(queue);
15856         return;
15857 }
15858
15859 /**
15860  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
15861  * @phba: The HBA that this queue is being created on.
15862  * @page_size: The size of a queue page
15863  * @entry_size: The size of each queue entry for this queue.
15864  * @entry_count: The number of entries that this queue will handle.
15865  * @cpu: The cpu that will primarily utilize this queue.
15866  *
15867  * This function allocates a queue structure and the DMAable memory used for
15868  * the host resident queue. This function must be called before creating the
15869  * queue on the HBA.
15870  **/
15871 struct lpfc_queue *
15872 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
15873                       uint32_t entry_size, uint32_t entry_count, int cpu)
15874 {
15875         struct lpfc_queue *queue;
15876         struct lpfc_dmabuf *dmabuf;
15877         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15878         uint16_t x, pgcnt;
15879
15880         if (!phba->sli4_hba.pc_sli4_params.supported)
15881                 hw_page_size = page_size;
15882
15883         pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
15884
15885         /* If needed, Adjust page count to match the max the adapter supports */
15886         if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
15887                 pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
15888
15889         queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
15890                              GFP_KERNEL, cpu_to_node(cpu));
15891         if (!queue)
15892                 return NULL;
15893
15894         INIT_LIST_HEAD(&queue->list);
15895         INIT_LIST_HEAD(&queue->_poll_list);
15896         INIT_LIST_HEAD(&queue->wq_list);
15897         INIT_LIST_HEAD(&queue->wqfull_list);
15898         INIT_LIST_HEAD(&queue->page_list);
15899         INIT_LIST_HEAD(&queue->child_list);
15900         INIT_LIST_HEAD(&queue->cpu_list);
15901
15902         /* Set queue parameters now.  If the system cannot provide memory
15903          * resources, the free routine needs to know what was allocated.
15904          */
15905         queue->page_count = pgcnt;
15906         queue->q_pgs = (void **)&queue[1];
15907         queue->entry_cnt_per_pg = hw_page_size / entry_size;
15908         queue->entry_size = entry_size;
15909         queue->entry_count = entry_count;
15910         queue->page_size = hw_page_size;
15911         queue->phba = phba;
15912
15913         for (x = 0; x < queue->page_count; x++) {
15914                 dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
15915                                       dev_to_node(&phba->pcidev->dev));
15916                 if (!dmabuf)
15917                         goto out_fail;
15918                 dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
15919                                                   hw_page_size, &dmabuf->phys,
15920                                                   GFP_KERNEL);
15921                 if (!dmabuf->virt) {
15922                         kfree(dmabuf);
15923                         goto out_fail;
15924                 }
15925                 dmabuf->buffer_tag = x;
15926                 list_add_tail(&dmabuf->list, &queue->page_list);
15927                 /* use lpfc_sli4_qe to index a paritcular entry in this page */
15928                 queue->q_pgs[x] = dmabuf->virt;
15929         }
15930         INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
15931         INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
15932         INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
15933         INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
15934
15935         /* notify_interval will be set during q creation */
15936
15937         return queue;
15938 out_fail:
15939         lpfc_sli4_queue_free(queue);
15940         return NULL;
15941 }
15942
15943 /**
15944  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
15945  * @phba: HBA structure that indicates port to create a queue on.
15946  * @pci_barset: PCI BAR set flag.
15947  *
15948  * This function shall perform iomap of the specified PCI BAR address to host
15949  * memory address if not already done so and return it. The returned host
15950  * memory address can be NULL.
15951  */
15952 static void __iomem *
15953 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
15954 {
15955         if (!phba->pcidev)
15956                 return NULL;
15957
15958         switch (pci_barset) {
15959         case WQ_PCI_BAR_0_AND_1:
15960                 return phba->pci_bar0_memmap_p;
15961         case WQ_PCI_BAR_2_AND_3:
15962                 return phba->pci_bar2_memmap_p;
15963         case WQ_PCI_BAR_4_AND_5:
15964                 return phba->pci_bar4_memmap_p;
15965         default:
15966                 break;
15967         }
15968         return NULL;
15969 }
15970
15971 /**
15972  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
15973  * @phba: HBA structure that EQs are on.
15974  * @startq: The starting EQ index to modify
15975  * @numq: The number of EQs (consecutive indexes) to modify
15976  * @usdelay: amount of delay
15977  *
15978  * This function revises the EQ delay on 1 or more EQs. The EQ delay
15979  * is set either by writing to a register (if supported by the SLI Port)
15980  * or by mailbox command. The mailbox command allows several EQs to be
15981  * updated at once.
15982  *
15983  * The @phba struct is used to send a mailbox command to HBA. The @startq
15984  * is used to get the starting EQ index to change. The @numq value is
15985  * used to specify how many consecutive EQ indexes, starting at EQ index,
15986  * are to be changed. This function is asynchronous and will wait for any
15987  * mailbox commands to finish before returning.
15988  *
15989  * On success this function will return a zero. If unable to allocate
15990  * enough memory this function will return -ENOMEM. If a mailbox command
15991  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
15992  * have had their delay multipler changed.
15993  **/
15994 void
15995 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
15996                          uint32_t numq, uint32_t usdelay)
15997 {
15998         struct lpfc_mbx_modify_eq_delay *eq_delay;
15999         LPFC_MBOXQ_t *mbox;
16000         struct lpfc_queue *eq;
16001         int cnt = 0, rc, length;
16002         uint32_t shdr_status, shdr_add_status;
16003         uint32_t dmult;
16004         int qidx;
16005         union lpfc_sli4_cfg_shdr *shdr;
16006
16007         if (startq >= phba->cfg_irq_chann)
16008                 return;
16009
16010         if (usdelay > 0xFFFF) {
16011                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
16012                                 "6429 usdelay %d too large. Scaled down to "
16013                                 "0xFFFF.\n", usdelay);
16014                 usdelay = 0xFFFF;
16015         }
16016
16017         /* set values by EQ_DELAY register if supported */
16018         if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
16019                 for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
16020                         eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
16021                         if (!eq)
16022                                 continue;
16023
16024                         lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
16025
16026                         if (++cnt >= numq)
16027                                 break;
16028                 }
16029                 return;
16030         }
16031
16032         /* Otherwise, set values by mailbox cmd */
16033
16034         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16035         if (!mbox) {
16036                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16037                                 "6428 Failed allocating mailbox cmd buffer."
16038                                 " EQ delay was not set.\n");
16039                 return;
16040         }
16041         length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
16042                   sizeof(struct lpfc_sli4_cfg_mhdr));
16043         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16044                          LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
16045                          length, LPFC_SLI4_MBX_EMBED);
16046         eq_delay = &mbox->u.mqe.un.eq_delay;
16047
16048         /* Calculate delay multiper from maximum interrupt per second */
16049         dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
16050         if (dmult)
16051                 dmult--;
16052         if (dmult > LPFC_DMULT_MAX)
16053                 dmult = LPFC_DMULT_MAX;
16054
16055         for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
16056                 eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
16057                 if (!eq)
16058                         continue;
16059                 eq->q_mode = usdelay;
16060                 eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
16061                 eq_delay->u.request.eq[cnt].phase = 0;
16062                 eq_delay->u.request.eq[cnt].delay_multi = dmult;
16063
16064                 if (++cnt >= numq)
16065                         break;
16066         }
16067         eq_delay->u.request.num_eq = cnt;
16068
16069         mbox->vport = phba->pport;
16070         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16071         mbox->ctx_buf = NULL;
16072         mbox->ctx_ndlp = NULL;
16073         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16074         shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
16075         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16076         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16077         if (shdr_status || shdr_add_status || rc) {
16078                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16079                                 "2512 MODIFY_EQ_DELAY mailbox failed with "
16080                                 "status x%x add_status x%x, mbx status x%x\n",
16081                                 shdr_status, shdr_add_status, rc);
16082         }
16083         mempool_free(mbox, phba->mbox_mem_pool);
16084         return;
16085 }
16086
16087 /**
16088  * lpfc_eq_create - Create an Event Queue on the HBA
16089  * @phba: HBA structure that indicates port to create a queue on.
16090  * @eq: The queue structure to use to create the event queue.
16091  * @imax: The maximum interrupt per second limit.
16092  *
16093  * This function creates an event queue, as detailed in @eq, on a port,
16094  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
16095  *
16096  * The @phba struct is used to send mailbox command to HBA. The @eq struct
16097  * is used to get the entry count and entry size that are necessary to
16098  * determine the number of pages to allocate and use for this queue. This
16099  * function will send the EQ_CREATE mailbox command to the HBA to setup the
16100  * event queue. This function is asynchronous and will wait for the mailbox
16101  * command to finish before continuing.
16102  *
16103  * On success this function will return a zero. If unable to allocate enough
16104  * memory this function will return -ENOMEM. If the queue create mailbox command
16105  * fails this function will return -ENXIO.
16106  **/
16107 int
16108 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
16109 {
16110         struct lpfc_mbx_eq_create *eq_create;
16111         LPFC_MBOXQ_t *mbox;
16112         int rc, length, status = 0;
16113         struct lpfc_dmabuf *dmabuf;
16114         uint32_t shdr_status, shdr_add_status;
16115         union lpfc_sli4_cfg_shdr *shdr;
16116         uint16_t dmult;
16117         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16118
16119         /* sanity check on queue memory */
16120         if (!eq)
16121                 return -ENODEV;
16122         if (!phba->sli4_hba.pc_sli4_params.supported)
16123                 hw_page_size = SLI4_PAGE_SIZE;
16124
16125         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16126         if (!mbox)
16127                 return -ENOMEM;
16128         length = (sizeof(struct lpfc_mbx_eq_create) -
16129                   sizeof(struct lpfc_sli4_cfg_mhdr));
16130         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16131                          LPFC_MBOX_OPCODE_EQ_CREATE,
16132                          length, LPFC_SLI4_MBX_EMBED);
16133         eq_create = &mbox->u.mqe.un.eq_create;
16134         shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
16135         bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
16136                eq->page_count);
16137         bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
16138                LPFC_EQE_SIZE);
16139         bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
16140
16141         /* Use version 2 of CREATE_EQ if eqav is set */
16142         if (phba->sli4_hba.pc_sli4_params.eqav) {
16143                 bf_set(lpfc_mbox_hdr_version, &shdr->request,
16144                        LPFC_Q_CREATE_VERSION_2);
16145                 bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
16146                        phba->sli4_hba.pc_sli4_params.eqav);
16147         }
16148
16149         /* don't setup delay multiplier using EQ_CREATE */
16150         dmult = 0;
16151         bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
16152                dmult);
16153         switch (eq->entry_count) {
16154         default:
16155                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16156                                 "0360 Unsupported EQ count. (%d)\n",
16157                                 eq->entry_count);
16158                 if (eq->entry_count < 256) {
16159                         status = -EINVAL;
16160                         goto out;
16161                 }
16162                 fallthrough;    /* otherwise default to smallest count */
16163         case 256:
16164                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16165                        LPFC_EQ_CNT_256);
16166                 break;
16167         case 512:
16168                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16169                        LPFC_EQ_CNT_512);
16170                 break;
16171         case 1024:
16172                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16173                        LPFC_EQ_CNT_1024);
16174                 break;
16175         case 2048:
16176                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16177                        LPFC_EQ_CNT_2048);
16178                 break;
16179         case 4096:
16180                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16181                        LPFC_EQ_CNT_4096);
16182                 break;
16183         }
16184         list_for_each_entry(dmabuf, &eq->page_list, list) {
16185                 memset(dmabuf->virt, 0, hw_page_size);
16186                 eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16187                                         putPaddrLow(dmabuf->phys);
16188                 eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16189                                         putPaddrHigh(dmabuf->phys);
16190         }
16191         mbox->vport = phba->pport;
16192         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16193         mbox->ctx_buf = NULL;
16194         mbox->ctx_ndlp = NULL;
16195         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16196         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16197         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16198         if (shdr_status || shdr_add_status || rc) {
16199                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16200                                 "2500 EQ_CREATE mailbox failed with "
16201                                 "status x%x add_status x%x, mbx status x%x\n",
16202                                 shdr_status, shdr_add_status, rc);
16203                 status = -ENXIO;
16204         }
16205         eq->type = LPFC_EQ;
16206         eq->subtype = LPFC_NONE;
16207         eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
16208         if (eq->queue_id == 0xFFFF)
16209                 status = -ENXIO;
16210         eq->host_index = 0;
16211         eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
16212         eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
16213 out:
16214         mempool_free(mbox, phba->mbox_mem_pool);
16215         return status;
16216 }
16217
16218 static int lpfc_cq_poll_hdler(struct irq_poll *iop, int budget)
16219 {
16220         struct lpfc_queue *cq = container_of(iop, struct lpfc_queue, iop);
16221
16222         __lpfc_sli4_hba_process_cq(cq, LPFC_IRQ_POLL);
16223
16224         return 1;
16225 }
16226
16227 /**
16228  * lpfc_cq_create - Create a Completion Queue on the HBA
16229  * @phba: HBA structure that indicates port to create a queue on.
16230  * @cq: The queue structure to use to create the completion queue.
16231  * @eq: The event queue to bind this completion queue to.
16232  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16233  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16234  *
16235  * This function creates a completion queue, as detailed in @wq, on a port,
16236  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
16237  *
16238  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16239  * is used to get the entry count and entry size that are necessary to
16240  * determine the number of pages to allocate and use for this queue. The @eq
16241  * is used to indicate which event queue to bind this completion queue to. This
16242  * function will send the CQ_CREATE mailbox command to the HBA to setup the
16243  * completion queue. This function is asynchronous and will wait for the mailbox
16244  * command to finish before continuing.
16245  *
16246  * On success this function will return a zero. If unable to allocate enough
16247  * memory this function will return -ENOMEM. If the queue create mailbox command
16248  * fails this function will return -ENXIO.
16249  **/
16250 int
16251 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
16252                struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
16253 {
16254         struct lpfc_mbx_cq_create *cq_create;
16255         struct lpfc_dmabuf *dmabuf;
16256         LPFC_MBOXQ_t *mbox;
16257         int rc, length, status = 0;
16258         uint32_t shdr_status, shdr_add_status;
16259         union lpfc_sli4_cfg_shdr *shdr;
16260
16261         /* sanity check on queue memory */
16262         if (!cq || !eq)
16263                 return -ENODEV;
16264
16265         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16266         if (!mbox)
16267                 return -ENOMEM;
16268         length = (sizeof(struct lpfc_mbx_cq_create) -
16269                   sizeof(struct lpfc_sli4_cfg_mhdr));
16270         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16271                          LPFC_MBOX_OPCODE_CQ_CREATE,
16272                          length, LPFC_SLI4_MBX_EMBED);
16273         cq_create = &mbox->u.mqe.un.cq_create;
16274         shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
16275         bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
16276                     cq->page_count);
16277         bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
16278         bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
16279         bf_set(lpfc_mbox_hdr_version, &shdr->request,
16280                phba->sli4_hba.pc_sli4_params.cqv);
16281         if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
16282                 bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
16283                        (cq->page_size / SLI4_PAGE_SIZE));
16284                 bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
16285                        eq->queue_id);
16286                 bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
16287                        phba->sli4_hba.pc_sli4_params.cqav);
16288         } else {
16289                 bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
16290                        eq->queue_id);
16291         }
16292         switch (cq->entry_count) {
16293         case 2048:
16294         case 4096:
16295                 if (phba->sli4_hba.pc_sli4_params.cqv ==
16296                     LPFC_Q_CREATE_VERSION_2) {
16297                         cq_create->u.request.context.lpfc_cq_context_count =
16298                                 cq->entry_count;
16299                         bf_set(lpfc_cq_context_count,
16300                                &cq_create->u.request.context,
16301                                LPFC_CQ_CNT_WORD7);
16302                         break;
16303                 }
16304                 fallthrough;
16305         default:
16306                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16307                                 "0361 Unsupported CQ count: "
16308                                 "entry cnt %d sz %d pg cnt %d\n",
16309                                 cq->entry_count, cq->entry_size,
16310                                 cq->page_count);
16311                 if (cq->entry_count < 256) {
16312                         status = -EINVAL;
16313                         goto out;
16314                 }
16315                 fallthrough;    /* otherwise default to smallest count */
16316         case 256:
16317                 bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16318                        LPFC_CQ_CNT_256);
16319                 break;
16320         case 512:
16321                 bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16322                        LPFC_CQ_CNT_512);
16323                 break;
16324         case 1024:
16325                 bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16326                        LPFC_CQ_CNT_1024);
16327                 break;
16328         }
16329         list_for_each_entry(dmabuf, &cq->page_list, list) {
16330                 memset(dmabuf->virt, 0, cq->page_size);
16331                 cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16332                                         putPaddrLow(dmabuf->phys);
16333                 cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16334                                         putPaddrHigh(dmabuf->phys);
16335         }
16336         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16337
16338         /* The IOCTL status is embedded in the mailbox subheader. */
16339         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16340         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16341         if (shdr_status || shdr_add_status || rc) {
16342                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16343                                 "2501 CQ_CREATE mailbox failed with "
16344                                 "status x%x add_status x%x, mbx status x%x\n",
16345                                 shdr_status, shdr_add_status, rc);
16346                 status = -ENXIO;
16347                 goto out;
16348         }
16349         cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16350         if (cq->queue_id == 0xFFFF) {
16351                 status = -ENXIO;
16352                 goto out;
16353         }
16354         /* link the cq onto the parent eq child list */
16355         list_add_tail(&cq->list, &eq->child_list);
16356         /* Set up completion queue's type and subtype */
16357         cq->type = type;
16358         cq->subtype = subtype;
16359         cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16360         cq->assoc_qid = eq->queue_id;
16361         cq->assoc_qp = eq;
16362         cq->host_index = 0;
16363         cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16364         cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
16365
16366         if (cq->queue_id > phba->sli4_hba.cq_max)
16367                 phba->sli4_hba.cq_max = cq->queue_id;
16368
16369         irq_poll_init(&cq->iop, LPFC_IRQ_POLL_WEIGHT, lpfc_cq_poll_hdler);
16370 out:
16371         mempool_free(mbox, phba->mbox_mem_pool);
16372         return status;
16373 }
16374
16375 /**
16376  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
16377  * @phba: HBA structure that indicates port to create a queue on.
16378  * @cqp: The queue structure array to use to create the completion queues.
16379  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
16380  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16381  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16382  *
16383  * This function creates a set of  completion queue, s to support MRQ
16384  * as detailed in @cqp, on a port,
16385  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
16386  *
16387  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16388  * is used to get the entry count and entry size that are necessary to
16389  * determine the number of pages to allocate and use for this queue. The @eq
16390  * is used to indicate which event queue to bind this completion queue to. This
16391  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
16392  * completion queue. This function is asynchronous and will wait for the mailbox
16393  * command to finish before continuing.
16394  *
16395  * On success this function will return a zero. If unable to allocate enough
16396  * memory this function will return -ENOMEM. If the queue create mailbox command
16397  * fails this function will return -ENXIO.
16398  **/
16399 int
16400 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
16401                    struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
16402                    uint32_t subtype)
16403 {
16404         struct lpfc_queue *cq;
16405         struct lpfc_queue *eq;
16406         struct lpfc_mbx_cq_create_set *cq_set;
16407         struct lpfc_dmabuf *dmabuf;
16408         LPFC_MBOXQ_t *mbox;
16409         int rc, length, alloclen, status = 0;
16410         int cnt, idx, numcq, page_idx = 0;
16411         uint32_t shdr_status, shdr_add_status;
16412         union lpfc_sli4_cfg_shdr *shdr;
16413         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16414
16415         /* sanity check on queue memory */
16416         numcq = phba->cfg_nvmet_mrq;
16417         if (!cqp || !hdwq || !numcq)
16418                 return -ENODEV;
16419
16420         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16421         if (!mbox)
16422                 return -ENOMEM;
16423
16424         length = sizeof(struct lpfc_mbx_cq_create_set);
16425         length += ((numcq * cqp[0]->page_count) *
16426                    sizeof(struct dma_address));
16427         alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16428                         LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
16429                         LPFC_SLI4_MBX_NEMBED);
16430         if (alloclen < length) {
16431                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16432                                 "3098 Allocated DMA memory size (%d) is "
16433                                 "less than the requested DMA memory size "
16434                                 "(%d)\n", alloclen, length);
16435                 status = -ENOMEM;
16436                 goto out;
16437         }
16438         cq_set = mbox->sge_array->addr[0];
16439         shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
16440         bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
16441
16442         for (idx = 0; idx < numcq; idx++) {
16443                 cq = cqp[idx];
16444                 eq = hdwq[idx].hba_eq;
16445                 if (!cq || !eq) {
16446                         status = -ENOMEM;
16447                         goto out;
16448                 }
16449                 if (!phba->sli4_hba.pc_sli4_params.supported)
16450                         hw_page_size = cq->page_size;
16451
16452                 switch (idx) {
16453                 case 0:
16454                         bf_set(lpfc_mbx_cq_create_set_page_size,
16455                                &cq_set->u.request,
16456                                (hw_page_size / SLI4_PAGE_SIZE));
16457                         bf_set(lpfc_mbx_cq_create_set_num_pages,
16458                                &cq_set->u.request, cq->page_count);
16459                         bf_set(lpfc_mbx_cq_create_set_evt,
16460                                &cq_set->u.request, 1);
16461                         bf_set(lpfc_mbx_cq_create_set_valid,
16462                                &cq_set->u.request, 1);
16463                         bf_set(lpfc_mbx_cq_create_set_cqe_size,
16464                                &cq_set->u.request, 0);
16465                         bf_set(lpfc_mbx_cq_create_set_num_cq,
16466                                &cq_set->u.request, numcq);
16467                         bf_set(lpfc_mbx_cq_create_set_autovalid,
16468                                &cq_set->u.request,
16469                                phba->sli4_hba.pc_sli4_params.cqav);
16470                         switch (cq->entry_count) {
16471                         case 2048:
16472                         case 4096:
16473                                 if (phba->sli4_hba.pc_sli4_params.cqv ==
16474                                     LPFC_Q_CREATE_VERSION_2) {
16475                                         bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16476                                                &cq_set->u.request,
16477                                                 cq->entry_count);
16478                                         bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16479                                                &cq_set->u.request,
16480                                                LPFC_CQ_CNT_WORD7);
16481                                         break;
16482                                 }
16483                                 fallthrough;
16484                         default:
16485                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16486                                                 "3118 Bad CQ count. (%d)\n",
16487                                                 cq->entry_count);
16488                                 if (cq->entry_count < 256) {
16489                                         status = -EINVAL;
16490                                         goto out;
16491                                 }
16492                                 fallthrough;    /* otherwise default to smallest */
16493                         case 256:
16494                                 bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16495                                        &cq_set->u.request, LPFC_CQ_CNT_256);
16496                                 break;
16497                         case 512:
16498                                 bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16499                                        &cq_set->u.request, LPFC_CQ_CNT_512);
16500                                 break;
16501                         case 1024:
16502                                 bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16503                                        &cq_set->u.request, LPFC_CQ_CNT_1024);
16504                                 break;
16505                         }
16506                         bf_set(lpfc_mbx_cq_create_set_eq_id0,
16507                                &cq_set->u.request, eq->queue_id);
16508                         break;
16509                 case 1:
16510                         bf_set(lpfc_mbx_cq_create_set_eq_id1,
16511                                &cq_set->u.request, eq->queue_id);
16512                         break;
16513                 case 2:
16514                         bf_set(lpfc_mbx_cq_create_set_eq_id2,
16515                                &cq_set->u.request, eq->queue_id);
16516                         break;
16517                 case 3:
16518                         bf_set(lpfc_mbx_cq_create_set_eq_id3,
16519                                &cq_set->u.request, eq->queue_id);
16520                         break;
16521                 case 4:
16522                         bf_set(lpfc_mbx_cq_create_set_eq_id4,
16523                                &cq_set->u.request, eq->queue_id);
16524                         break;
16525                 case 5:
16526                         bf_set(lpfc_mbx_cq_create_set_eq_id5,
16527                                &cq_set->u.request, eq->queue_id);
16528                         break;
16529                 case 6:
16530                         bf_set(lpfc_mbx_cq_create_set_eq_id6,
16531                                &cq_set->u.request, eq->queue_id);
16532                         break;
16533                 case 7:
16534                         bf_set(lpfc_mbx_cq_create_set_eq_id7,
16535                                &cq_set->u.request, eq->queue_id);
16536                         break;
16537                 case 8:
16538                         bf_set(lpfc_mbx_cq_create_set_eq_id8,
16539                                &cq_set->u.request, eq->queue_id);
16540                         break;
16541                 case 9:
16542                         bf_set(lpfc_mbx_cq_create_set_eq_id9,
16543                                &cq_set->u.request, eq->queue_id);
16544                         break;
16545                 case 10:
16546                         bf_set(lpfc_mbx_cq_create_set_eq_id10,
16547                                &cq_set->u.request, eq->queue_id);
16548                         break;
16549                 case 11:
16550                         bf_set(lpfc_mbx_cq_create_set_eq_id11,
16551                                &cq_set->u.request, eq->queue_id);
16552                         break;
16553                 case 12:
16554                         bf_set(lpfc_mbx_cq_create_set_eq_id12,
16555                                &cq_set->u.request, eq->queue_id);
16556                         break;
16557                 case 13:
16558                         bf_set(lpfc_mbx_cq_create_set_eq_id13,
16559                                &cq_set->u.request, eq->queue_id);
16560                         break;
16561                 case 14:
16562                         bf_set(lpfc_mbx_cq_create_set_eq_id14,
16563                                &cq_set->u.request, eq->queue_id);
16564                         break;
16565                 case 15:
16566                         bf_set(lpfc_mbx_cq_create_set_eq_id15,
16567                                &cq_set->u.request, eq->queue_id);
16568                         break;
16569                 }
16570
16571                 /* link the cq onto the parent eq child list */
16572                 list_add_tail(&cq->list, &eq->child_list);
16573                 /* Set up completion queue's type and subtype */
16574                 cq->type = type;
16575                 cq->subtype = subtype;
16576                 cq->assoc_qid = eq->queue_id;
16577                 cq->assoc_qp = eq;
16578                 cq->host_index = 0;
16579                 cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16580                 cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
16581                                          cq->entry_count);
16582                 cq->chann = idx;
16583
16584                 rc = 0;
16585                 list_for_each_entry(dmabuf, &cq->page_list, list) {
16586                         memset(dmabuf->virt, 0, hw_page_size);
16587                         cnt = page_idx + dmabuf->buffer_tag;
16588                         cq_set->u.request.page[cnt].addr_lo =
16589                                         putPaddrLow(dmabuf->phys);
16590                         cq_set->u.request.page[cnt].addr_hi =
16591                                         putPaddrHigh(dmabuf->phys);
16592                         rc++;
16593                 }
16594                 page_idx += rc;
16595         }
16596
16597         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16598
16599         /* The IOCTL status is embedded in the mailbox subheader. */
16600         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16601         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16602         if (shdr_status || shdr_add_status || rc) {
16603                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16604                                 "3119 CQ_CREATE_SET mailbox failed with "
16605                                 "status x%x add_status x%x, mbx status x%x\n",
16606                                 shdr_status, shdr_add_status, rc);
16607                 status = -ENXIO;
16608                 goto out;
16609         }
16610         rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
16611         if (rc == 0xFFFF) {
16612                 status = -ENXIO;
16613                 goto out;
16614         }
16615
16616         for (idx = 0; idx < numcq; idx++) {
16617                 cq = cqp[idx];
16618                 cq->queue_id = rc + idx;
16619                 if (cq->queue_id > phba->sli4_hba.cq_max)
16620                         phba->sli4_hba.cq_max = cq->queue_id;
16621         }
16622
16623 out:
16624         lpfc_sli4_mbox_cmd_free(phba, mbox);
16625         return status;
16626 }
16627
16628 /**
16629  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
16630  * @phba: HBA structure that indicates port to create a queue on.
16631  * @mq: The queue structure to use to create the mailbox queue.
16632  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
16633  * @cq: The completion queue to associate with this cq.
16634  *
16635  * This function provides failback (fb) functionality when the
16636  * mq_create_ext fails on older FW generations.  It's purpose is identical
16637  * to mq_create_ext otherwise.
16638  *
16639  * This routine cannot fail as all attributes were previously accessed and
16640  * initialized in mq_create_ext.
16641  **/
16642 static void
16643 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
16644                        LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
16645 {
16646         struct lpfc_mbx_mq_create *mq_create;
16647         struct lpfc_dmabuf *dmabuf;
16648         int length;
16649
16650         length = (sizeof(struct lpfc_mbx_mq_create) -
16651                   sizeof(struct lpfc_sli4_cfg_mhdr));
16652         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16653                          LPFC_MBOX_OPCODE_MQ_CREATE,
16654                          length, LPFC_SLI4_MBX_EMBED);
16655         mq_create = &mbox->u.mqe.un.mq_create;
16656         bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
16657                mq->page_count);
16658         bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
16659                cq->queue_id);
16660         bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
16661         switch (mq->entry_count) {
16662         case 16:
16663                 bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16664                        LPFC_MQ_RING_SIZE_16);
16665                 break;
16666         case 32:
16667                 bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16668                        LPFC_MQ_RING_SIZE_32);
16669                 break;
16670         case 64:
16671                 bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16672                        LPFC_MQ_RING_SIZE_64);
16673                 break;
16674         case 128:
16675                 bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16676                        LPFC_MQ_RING_SIZE_128);
16677                 break;
16678         }
16679         list_for_each_entry(dmabuf, &mq->page_list, list) {
16680                 mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16681                         putPaddrLow(dmabuf->phys);
16682                 mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16683                         putPaddrHigh(dmabuf->phys);
16684         }
16685 }
16686
16687 /**
16688  * lpfc_mq_create - Create a mailbox Queue on the HBA
16689  * @phba: HBA structure that indicates port to create a queue on.
16690  * @mq: The queue structure to use to create the mailbox queue.
16691  * @cq: The completion queue to associate with this cq.
16692  * @subtype: The queue's subtype.
16693  *
16694  * This function creates a mailbox queue, as detailed in @mq, on a port,
16695  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
16696  *
16697  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16698  * is used to get the entry count and entry size that are necessary to
16699  * determine the number of pages to allocate and use for this queue. This
16700  * function will send the MQ_CREATE mailbox command to the HBA to setup the
16701  * mailbox queue. This function is asynchronous and will wait for the mailbox
16702  * command to finish before continuing.
16703  *
16704  * On success this function will return a zero. If unable to allocate enough
16705  * memory this function will return -ENOMEM. If the queue create mailbox command
16706  * fails this function will return -ENXIO.
16707  **/
16708 int32_t
16709 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
16710                struct lpfc_queue *cq, uint32_t subtype)
16711 {
16712         struct lpfc_mbx_mq_create *mq_create;
16713         struct lpfc_mbx_mq_create_ext *mq_create_ext;
16714         struct lpfc_dmabuf *dmabuf;
16715         LPFC_MBOXQ_t *mbox;
16716         int rc, length, status = 0;
16717         uint32_t shdr_status, shdr_add_status;
16718         union lpfc_sli4_cfg_shdr *shdr;
16719         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16720
16721         /* sanity check on queue memory */
16722         if (!mq || !cq)
16723                 return -ENODEV;
16724         if (!phba->sli4_hba.pc_sli4_params.supported)
16725                 hw_page_size = SLI4_PAGE_SIZE;
16726
16727         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16728         if (!mbox)
16729                 return -ENOMEM;
16730         length = (sizeof(struct lpfc_mbx_mq_create_ext) -
16731                   sizeof(struct lpfc_sli4_cfg_mhdr));
16732         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16733                          LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
16734                          length, LPFC_SLI4_MBX_EMBED);
16735
16736         mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
16737         shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
16738         bf_set(lpfc_mbx_mq_create_ext_num_pages,
16739                &mq_create_ext->u.request, mq->page_count);
16740         bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
16741                &mq_create_ext->u.request, 1);
16742         bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
16743                &mq_create_ext->u.request, 1);
16744         bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
16745                &mq_create_ext->u.request, 1);
16746         bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
16747                &mq_create_ext->u.request, 1);
16748         bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
16749                &mq_create_ext->u.request, 1);
16750         bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
16751         bf_set(lpfc_mbox_hdr_version, &shdr->request,
16752                phba->sli4_hba.pc_sli4_params.mqv);
16753         if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
16754                 bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
16755                        cq->queue_id);
16756         else
16757                 bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
16758                        cq->queue_id);
16759         switch (mq->entry_count) {
16760         default:
16761                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16762                                 "0362 Unsupported MQ count. (%d)\n",
16763                                 mq->entry_count);
16764                 if (mq->entry_count < 16) {
16765                         status = -EINVAL;
16766                         goto out;
16767                 }
16768                 fallthrough;    /* otherwise default to smallest count */
16769         case 16:
16770                 bf_set(lpfc_mq_context_ring_size,
16771                        &mq_create_ext->u.request.context,
16772                        LPFC_MQ_RING_SIZE_16);
16773                 break;
16774         case 32:
16775                 bf_set(lpfc_mq_context_ring_size,
16776                        &mq_create_ext->u.request.context,
16777                        LPFC_MQ_RING_SIZE_32);
16778                 break;
16779         case 64:
16780                 bf_set(lpfc_mq_context_ring_size,
16781                        &mq_create_ext->u.request.context,
16782                        LPFC_MQ_RING_SIZE_64);
16783                 break;
16784         case 128:
16785                 bf_set(lpfc_mq_context_ring_size,
16786                        &mq_create_ext->u.request.context,
16787                        LPFC_MQ_RING_SIZE_128);
16788                 break;
16789         }
16790         list_for_each_entry(dmabuf, &mq->page_list, list) {
16791                 memset(dmabuf->virt, 0, hw_page_size);
16792                 mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
16793                                         putPaddrLow(dmabuf->phys);
16794                 mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
16795                                         putPaddrHigh(dmabuf->phys);
16796         }
16797         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16798         mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16799                               &mq_create_ext->u.response);
16800         if (rc != MBX_SUCCESS) {
16801                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16802                                 "2795 MQ_CREATE_EXT failed with "
16803                                 "status x%x. Failback to MQ_CREATE.\n",
16804                                 rc);
16805                 lpfc_mq_create_fb_init(phba, mq, mbox, cq);
16806                 mq_create = &mbox->u.mqe.un.mq_create;
16807                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16808                 shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
16809                 mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16810                                       &mq_create->u.response);
16811         }
16812
16813         /* The IOCTL status is embedded in the mailbox subheader. */
16814         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16815         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16816         if (shdr_status || shdr_add_status || rc) {
16817                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16818                                 "2502 MQ_CREATE mailbox failed with "
16819                                 "status x%x add_status x%x, mbx status x%x\n",
16820                                 shdr_status, shdr_add_status, rc);
16821                 status = -ENXIO;
16822                 goto out;
16823         }
16824         if (mq->queue_id == 0xFFFF) {
16825                 status = -ENXIO;
16826                 goto out;
16827         }
16828         mq->type = LPFC_MQ;
16829         mq->assoc_qid = cq->queue_id;
16830         mq->subtype = subtype;
16831         mq->host_index = 0;
16832         mq->hba_index = 0;
16833
16834         /* link the mq onto the parent cq child list */
16835         list_add_tail(&mq->list, &cq->child_list);
16836 out:
16837         mempool_free(mbox, phba->mbox_mem_pool);
16838         return status;
16839 }
16840
16841 /**
16842  * lpfc_wq_create - Create a Work Queue on the HBA
16843  * @phba: HBA structure that indicates port to create a queue on.
16844  * @wq: The queue structure to use to create the work queue.
16845  * @cq: The completion queue to bind this work queue to.
16846  * @subtype: The subtype of the work queue indicating its functionality.
16847  *
16848  * This function creates a work queue, as detailed in @wq, on a port, described
16849  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
16850  *
16851  * The @phba struct is used to send mailbox command to HBA. The @wq struct
16852  * is used to get the entry count and entry size that are necessary to
16853  * determine the number of pages to allocate and use for this queue. The @cq
16854  * is used to indicate which completion queue to bind this work queue to. This
16855  * function will send the WQ_CREATE mailbox command to the HBA to setup the
16856  * work queue. This function is asynchronous and will wait for the mailbox
16857  * command to finish before continuing.
16858  *
16859  * On success this function will return a zero. If unable to allocate enough
16860  * memory this function will return -ENOMEM. If the queue create mailbox command
16861  * fails this function will return -ENXIO.
16862  **/
16863 int
16864 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
16865                struct lpfc_queue *cq, uint32_t subtype)
16866 {
16867         struct lpfc_mbx_wq_create *wq_create;
16868         struct lpfc_dmabuf *dmabuf;
16869         LPFC_MBOXQ_t *mbox;
16870         int rc, length, status = 0;
16871         uint32_t shdr_status, shdr_add_status;
16872         union lpfc_sli4_cfg_shdr *shdr;
16873         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16874         struct dma_address *page;
16875         void __iomem *bar_memmap_p;
16876         uint32_t db_offset;
16877         uint16_t pci_barset;
16878         uint8_t dpp_barset;
16879         uint32_t dpp_offset;
16880         uint8_t wq_create_version;
16881 #ifdef CONFIG_X86
16882         unsigned long pg_addr;
16883 #endif
16884
16885         /* sanity check on queue memory */
16886         if (!wq || !cq)
16887                 return -ENODEV;
16888         if (!phba->sli4_hba.pc_sli4_params.supported)
16889                 hw_page_size = wq->page_size;
16890
16891         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16892         if (!mbox)
16893                 return -ENOMEM;
16894         length = (sizeof(struct lpfc_mbx_wq_create) -
16895                   sizeof(struct lpfc_sli4_cfg_mhdr));
16896         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16897                          LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
16898                          length, LPFC_SLI4_MBX_EMBED);
16899         wq_create = &mbox->u.mqe.un.wq_create;
16900         shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
16901         bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
16902                     wq->page_count);
16903         bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
16904                     cq->queue_id);
16905
16906         /* wqv is the earliest version supported, NOT the latest */
16907         bf_set(lpfc_mbox_hdr_version, &shdr->request,
16908                phba->sli4_hba.pc_sli4_params.wqv);
16909
16910         if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
16911             (wq->page_size > SLI4_PAGE_SIZE))
16912                 wq_create_version = LPFC_Q_CREATE_VERSION_1;
16913         else
16914                 wq_create_version = LPFC_Q_CREATE_VERSION_0;
16915
16916         switch (wq_create_version) {
16917         case LPFC_Q_CREATE_VERSION_1:
16918                 bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
16919                        wq->entry_count);
16920                 bf_set(lpfc_mbox_hdr_version, &shdr->request,
16921                        LPFC_Q_CREATE_VERSION_1);
16922
16923                 switch (wq->entry_size) {
16924                 default:
16925                 case 64:
16926                         bf_set(lpfc_mbx_wq_create_wqe_size,
16927                                &wq_create->u.request_1,
16928                                LPFC_WQ_WQE_SIZE_64);
16929                         break;
16930                 case 128:
16931                         bf_set(lpfc_mbx_wq_create_wqe_size,
16932                                &wq_create->u.request_1,
16933                                LPFC_WQ_WQE_SIZE_128);
16934                         break;
16935                 }
16936                 /* Request DPP by default */
16937                 bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
16938                 bf_set(lpfc_mbx_wq_create_page_size,
16939                        &wq_create->u.request_1,
16940                        (wq->page_size / SLI4_PAGE_SIZE));
16941                 page = wq_create->u.request_1.page;
16942                 break;
16943         default:
16944                 page = wq_create->u.request.page;
16945                 break;
16946         }
16947
16948         list_for_each_entry(dmabuf, &wq->page_list, list) {
16949                 memset(dmabuf->virt, 0, hw_page_size);
16950                 page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
16951                 page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
16952         }
16953
16954         if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16955                 bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
16956
16957         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16958         /* The IOCTL status is embedded in the mailbox subheader. */
16959         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16960         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16961         if (shdr_status || shdr_add_status || rc) {
16962                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16963                                 "2503 WQ_CREATE mailbox failed with "
16964                                 "status x%x add_status x%x, mbx status x%x\n",
16965                                 shdr_status, shdr_add_status, rc);
16966                 status = -ENXIO;
16967                 goto out;
16968         }
16969
16970         if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
16971                 wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
16972                                         &wq_create->u.response);
16973         else
16974                 wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
16975                                         &wq_create->u.response_1);
16976
16977         if (wq->queue_id == 0xFFFF) {
16978                 status = -ENXIO;
16979                 goto out;
16980         }
16981
16982         wq->db_format = LPFC_DB_LIST_FORMAT;
16983         if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
16984                 if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16985                         wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
16986                                                &wq_create->u.response);
16987                         if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
16988                             (wq->db_format != LPFC_DB_RING_FORMAT)) {
16989                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16990                                                 "3265 WQ[%d] doorbell format "
16991                                                 "not supported: x%x\n",
16992                                                 wq->queue_id, wq->db_format);
16993                                 status = -EINVAL;
16994                                 goto out;
16995                         }
16996                         pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
16997                                             &wq_create->u.response);
16998                         bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
16999                                                                    pci_barset);
17000                         if (!bar_memmap_p) {
17001                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17002                                                 "3263 WQ[%d] failed to memmap "
17003                                                 "pci barset:x%x\n",
17004                                                 wq->queue_id, pci_barset);
17005                                 status = -ENOMEM;
17006                                 goto out;
17007                         }
17008                         db_offset = wq_create->u.response.doorbell_offset;
17009                         if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
17010                             (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
17011                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17012                                                 "3252 WQ[%d] doorbell offset "
17013                                                 "not supported: x%x\n",
17014                                                 wq->queue_id, db_offset);
17015                                 status = -EINVAL;
17016                                 goto out;
17017                         }
17018                         wq->db_regaddr = bar_memmap_p + db_offset;
17019                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17020                                         "3264 WQ[%d]: barset:x%x, offset:x%x, "
17021                                         "format:x%x\n", wq->queue_id,
17022                                         pci_barset, db_offset, wq->db_format);
17023                 } else
17024                         wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17025         } else {
17026                 /* Check if DPP was honored by the firmware */
17027                 wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
17028                                     &wq_create->u.response_1);
17029                 if (wq->dpp_enable) {
17030                         pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
17031                                             &wq_create->u.response_1);
17032                         bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17033                                                                    pci_barset);
17034                         if (!bar_memmap_p) {
17035                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17036                                                 "3267 WQ[%d] failed to memmap "
17037                                                 "pci barset:x%x\n",
17038                                                 wq->queue_id, pci_barset);
17039                                 status = -ENOMEM;
17040                                 goto out;
17041                         }
17042                         db_offset = wq_create->u.response_1.doorbell_offset;
17043                         wq->db_regaddr = bar_memmap_p + db_offset;
17044                         wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
17045                                             &wq_create->u.response_1);
17046                         dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
17047                                             &wq_create->u.response_1);
17048                         bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17049                                                                    dpp_barset);
17050                         if (!bar_memmap_p) {
17051                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17052                                                 "3268 WQ[%d] failed to memmap "
17053                                                 "pci barset:x%x\n",
17054                                                 wq->queue_id, dpp_barset);
17055                                 status = -ENOMEM;
17056                                 goto out;
17057                         }
17058                         dpp_offset = wq_create->u.response_1.dpp_offset;
17059                         wq->dpp_regaddr = bar_memmap_p + dpp_offset;
17060                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17061                                         "3271 WQ[%d]: barset:x%x, offset:x%x, "
17062                                         "dpp_id:x%x dpp_barset:x%x "
17063                                         "dpp_offset:x%x\n",
17064                                         wq->queue_id, pci_barset, db_offset,
17065                                         wq->dpp_id, dpp_barset, dpp_offset);
17066
17067 #ifdef CONFIG_X86
17068                         /* Enable combined writes for DPP aperture */
17069                         pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
17070                         rc = set_memory_wc(pg_addr, 1);
17071                         if (rc) {
17072                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17073                                         "3272 Cannot setup Combined "
17074                                         "Write on WQ[%d] - disable DPP\n",
17075                                         wq->queue_id);
17076                                 phba->cfg_enable_dpp = 0;
17077                         }
17078 #else
17079                         phba->cfg_enable_dpp = 0;
17080 #endif
17081                 } else
17082                         wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17083         }
17084         wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
17085         if (wq->pring == NULL) {
17086                 status = -ENOMEM;
17087                 goto out;
17088         }
17089         wq->type = LPFC_WQ;
17090         wq->assoc_qid = cq->queue_id;
17091         wq->subtype = subtype;
17092         wq->host_index = 0;
17093         wq->hba_index = 0;
17094         wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
17095
17096         /* link the wq onto the parent cq child list */
17097         list_add_tail(&wq->list, &cq->child_list);
17098 out:
17099         mempool_free(mbox, phba->mbox_mem_pool);
17100         return status;
17101 }
17102
17103 /**
17104  * lpfc_rq_create - Create a Receive Queue on the HBA
17105  * @phba: HBA structure that indicates port to create a queue on.
17106  * @hrq: The queue structure to use to create the header receive queue.
17107  * @drq: The queue structure to use to create the data receive queue.
17108  * @cq: The completion queue to bind this work queue to.
17109  * @subtype: The subtype of the work queue indicating its functionality.
17110  *
17111  * This function creates a receive buffer queue pair , as detailed in @hrq and
17112  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17113  * to the HBA.
17114  *
17115  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17116  * struct is used to get the entry count that is necessary to determine the
17117  * number of pages to use for this queue. The @cq is used to indicate which
17118  * completion queue to bind received buffers that are posted to these queues to.
17119  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17120  * receive queue pair. This function is asynchronous and will wait for the
17121  * mailbox command to finish before continuing.
17122  *
17123  * On success this function will return a zero. If unable to allocate enough
17124  * memory this function will return -ENOMEM. If the queue create mailbox command
17125  * fails this function will return -ENXIO.
17126  **/
17127 int
17128 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17129                struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
17130 {
17131         struct lpfc_mbx_rq_create *rq_create;
17132         struct lpfc_dmabuf *dmabuf;
17133         LPFC_MBOXQ_t *mbox;
17134         int rc, length, status = 0;
17135         uint32_t shdr_status, shdr_add_status;
17136         union lpfc_sli4_cfg_shdr *shdr;
17137         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17138         void __iomem *bar_memmap_p;
17139         uint32_t db_offset;
17140         uint16_t pci_barset;
17141
17142         /* sanity check on queue memory */
17143         if (!hrq || !drq || !cq)
17144                 return -ENODEV;
17145         if (!phba->sli4_hba.pc_sli4_params.supported)
17146                 hw_page_size = SLI4_PAGE_SIZE;
17147
17148         if (hrq->entry_count != drq->entry_count)
17149                 return -EINVAL;
17150         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17151         if (!mbox)
17152                 return -ENOMEM;
17153         length = (sizeof(struct lpfc_mbx_rq_create) -
17154                   sizeof(struct lpfc_sli4_cfg_mhdr));
17155         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17156                          LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17157                          length, LPFC_SLI4_MBX_EMBED);
17158         rq_create = &mbox->u.mqe.un.rq_create;
17159         shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17160         bf_set(lpfc_mbox_hdr_version, &shdr->request,
17161                phba->sli4_hba.pc_sli4_params.rqv);
17162         if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17163                 bf_set(lpfc_rq_context_rqe_count_1,
17164                        &rq_create->u.request.context,
17165                        hrq->entry_count);
17166                 rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
17167                 bf_set(lpfc_rq_context_rqe_size,
17168                        &rq_create->u.request.context,
17169                        LPFC_RQE_SIZE_8);
17170                 bf_set(lpfc_rq_context_page_size,
17171                        &rq_create->u.request.context,
17172                        LPFC_RQ_PAGE_SIZE_4096);
17173         } else {
17174                 switch (hrq->entry_count) {
17175                 default:
17176                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17177                                         "2535 Unsupported RQ count. (%d)\n",
17178                                         hrq->entry_count);
17179                         if (hrq->entry_count < 512) {
17180                                 status = -EINVAL;
17181                                 goto out;
17182                         }
17183                         fallthrough;    /* otherwise default to smallest count */
17184                 case 512:
17185                         bf_set(lpfc_rq_context_rqe_count,
17186                                &rq_create->u.request.context,
17187                                LPFC_RQ_RING_SIZE_512);
17188                         break;
17189                 case 1024:
17190                         bf_set(lpfc_rq_context_rqe_count,
17191                                &rq_create->u.request.context,
17192                                LPFC_RQ_RING_SIZE_1024);
17193                         break;
17194                 case 2048:
17195                         bf_set(lpfc_rq_context_rqe_count,
17196                                &rq_create->u.request.context,
17197                                LPFC_RQ_RING_SIZE_2048);
17198                         break;
17199                 case 4096:
17200                         bf_set(lpfc_rq_context_rqe_count,
17201                                &rq_create->u.request.context,
17202                                LPFC_RQ_RING_SIZE_4096);
17203                         break;
17204                 }
17205                 bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
17206                        LPFC_HDR_BUF_SIZE);
17207         }
17208         bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17209                cq->queue_id);
17210         bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17211                hrq->page_count);
17212         list_for_each_entry(dmabuf, &hrq->page_list, list) {
17213                 memset(dmabuf->virt, 0, hw_page_size);
17214                 rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17215                                         putPaddrLow(dmabuf->phys);
17216                 rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17217                                         putPaddrHigh(dmabuf->phys);
17218         }
17219         if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17220                 bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17221
17222         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17223         /* The IOCTL status is embedded in the mailbox subheader. */
17224         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17225         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17226         if (shdr_status || shdr_add_status || rc) {
17227                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17228                                 "2504 RQ_CREATE mailbox failed with "
17229                                 "status x%x add_status x%x, mbx status x%x\n",
17230                                 shdr_status, shdr_add_status, rc);
17231                 status = -ENXIO;
17232                 goto out;
17233         }
17234         hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17235         if (hrq->queue_id == 0xFFFF) {
17236                 status = -ENXIO;
17237                 goto out;
17238         }
17239
17240         if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
17241                 hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
17242                                         &rq_create->u.response);
17243                 if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
17244                     (hrq->db_format != LPFC_DB_RING_FORMAT)) {
17245                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17246                                         "3262 RQ [%d] doorbell format not "
17247                                         "supported: x%x\n", hrq->queue_id,
17248                                         hrq->db_format);
17249                         status = -EINVAL;
17250                         goto out;
17251                 }
17252
17253                 pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
17254                                     &rq_create->u.response);
17255                 bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
17256                 if (!bar_memmap_p) {
17257                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17258                                         "3269 RQ[%d] failed to memmap pci "
17259                                         "barset:x%x\n", hrq->queue_id,
17260                                         pci_barset);
17261                         status = -ENOMEM;
17262                         goto out;
17263                 }
17264
17265                 db_offset = rq_create->u.response.doorbell_offset;
17266                 if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
17267                     (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
17268                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17269                                         "3270 RQ[%d] doorbell offset not "
17270                                         "supported: x%x\n", hrq->queue_id,
17271                                         db_offset);
17272                         status = -EINVAL;
17273                         goto out;
17274                 }
17275                 hrq->db_regaddr = bar_memmap_p + db_offset;
17276                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17277                                 "3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
17278                                 "format:x%x\n", hrq->queue_id, pci_barset,
17279                                 db_offset, hrq->db_format);
17280         } else {
17281                 hrq->db_format = LPFC_DB_RING_FORMAT;
17282                 hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17283         }
17284         hrq->type = LPFC_HRQ;
17285         hrq->assoc_qid = cq->queue_id;
17286         hrq->subtype = subtype;
17287         hrq->host_index = 0;
17288         hrq->hba_index = 0;
17289         hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17290
17291         /* now create the data queue */
17292         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17293                          LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17294                          length, LPFC_SLI4_MBX_EMBED);
17295         bf_set(lpfc_mbox_hdr_version, &shdr->request,
17296                phba->sli4_hba.pc_sli4_params.rqv);
17297         if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17298                 bf_set(lpfc_rq_context_rqe_count_1,
17299                        &rq_create->u.request.context, hrq->entry_count);
17300                 if (subtype == LPFC_NVMET)
17301                         rq_create->u.request.context.buffer_size =
17302                                 LPFC_NVMET_DATA_BUF_SIZE;
17303                 else
17304                         rq_create->u.request.context.buffer_size =
17305                                 LPFC_DATA_BUF_SIZE;
17306                 bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
17307                        LPFC_RQE_SIZE_8);
17308                 bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
17309                        (PAGE_SIZE/SLI4_PAGE_SIZE));
17310         } else {
17311                 switch (drq->entry_count) {
17312                 default:
17313                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17314                                         "2536 Unsupported RQ count. (%d)\n",
17315                                         drq->entry_count);
17316                         if (drq->entry_count < 512) {
17317                                 status = -EINVAL;
17318                                 goto out;
17319                         }
17320                         fallthrough;    /* otherwise default to smallest count */
17321                 case 512:
17322                         bf_set(lpfc_rq_context_rqe_count,
17323                                &rq_create->u.request.context,
17324                                LPFC_RQ_RING_SIZE_512);
17325                         break;
17326                 case 1024:
17327                         bf_set(lpfc_rq_context_rqe_count,
17328                                &rq_create->u.request.context,
17329                                LPFC_RQ_RING_SIZE_1024);
17330                         break;
17331                 case 2048:
17332                         bf_set(lpfc_rq_context_rqe_count,
17333                                &rq_create->u.request.context,
17334                                LPFC_RQ_RING_SIZE_2048);
17335                         break;
17336                 case 4096:
17337                         bf_set(lpfc_rq_context_rqe_count,
17338                                &rq_create->u.request.context,
17339                                LPFC_RQ_RING_SIZE_4096);
17340                         break;
17341                 }
17342                 if (subtype == LPFC_NVMET)
17343                         bf_set(lpfc_rq_context_buf_size,
17344                                &rq_create->u.request.context,
17345                                LPFC_NVMET_DATA_BUF_SIZE);
17346                 else
17347                         bf_set(lpfc_rq_context_buf_size,
17348                                &rq_create->u.request.context,
17349                                LPFC_DATA_BUF_SIZE);
17350         }
17351         bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17352                cq->queue_id);
17353         bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17354                drq->page_count);
17355         list_for_each_entry(dmabuf, &drq->page_list, list) {
17356                 rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17357                                         putPaddrLow(dmabuf->phys);
17358                 rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17359                                         putPaddrHigh(dmabuf->phys);
17360         }
17361         if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17362                 bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17363         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17364         /* The IOCTL status is embedded in the mailbox subheader. */
17365         shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17366         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17367         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17368         if (shdr_status || shdr_add_status || rc) {
17369                 status = -ENXIO;
17370                 goto out;
17371         }
17372         drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17373         if (drq->queue_id == 0xFFFF) {
17374                 status = -ENXIO;
17375                 goto out;
17376         }
17377         drq->type = LPFC_DRQ;
17378         drq->assoc_qid = cq->queue_id;
17379         drq->subtype = subtype;
17380         drq->host_index = 0;
17381         drq->hba_index = 0;
17382         drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17383
17384         /* link the header and data RQs onto the parent cq child list */
17385         list_add_tail(&hrq->list, &cq->child_list);
17386         list_add_tail(&drq->list, &cq->child_list);
17387
17388 out:
17389         mempool_free(mbox, phba->mbox_mem_pool);
17390         return status;
17391 }
17392
17393 /**
17394  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
17395  * @phba: HBA structure that indicates port to create a queue on.
17396  * @hrqp: The queue structure array to use to create the header receive queues.
17397  * @drqp: The queue structure array to use to create the data receive queues.
17398  * @cqp: The completion queue array to bind these receive queues to.
17399  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
17400  *
17401  * This function creates a receive buffer queue pair , as detailed in @hrq and
17402  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17403  * to the HBA.
17404  *
17405  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17406  * struct is used to get the entry count that is necessary to determine the
17407  * number of pages to use for this queue. The @cq is used to indicate which
17408  * completion queue to bind received buffers that are posted to these queues to.
17409  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17410  * receive queue pair. This function is asynchronous and will wait for the
17411  * mailbox command to finish before continuing.
17412  *
17413  * On success this function will return a zero. If unable to allocate enough
17414  * memory this function will return -ENOMEM. If the queue create mailbox command
17415  * fails this function will return -ENXIO.
17416  **/
17417 int
17418 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
17419                 struct lpfc_queue **drqp, struct lpfc_queue **cqp,
17420                 uint32_t subtype)
17421 {
17422         struct lpfc_queue *hrq, *drq, *cq;
17423         struct lpfc_mbx_rq_create_v2 *rq_create;
17424         struct lpfc_dmabuf *dmabuf;
17425         LPFC_MBOXQ_t *mbox;
17426         int rc, length, alloclen, status = 0;
17427         int cnt, idx, numrq, page_idx = 0;
17428         uint32_t shdr_status, shdr_add_status;
17429         union lpfc_sli4_cfg_shdr *shdr;
17430         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17431
17432         numrq = phba->cfg_nvmet_mrq;
17433         /* sanity check on array memory */
17434         if (!hrqp || !drqp || !cqp || !numrq)
17435                 return -ENODEV;
17436         if (!phba->sli4_hba.pc_sli4_params.supported)
17437                 hw_page_size = SLI4_PAGE_SIZE;
17438
17439         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17440         if (!mbox)
17441                 return -ENOMEM;
17442
17443         length = sizeof(struct lpfc_mbx_rq_create_v2);
17444         length += ((2 * numrq * hrqp[0]->page_count) *
17445                    sizeof(struct dma_address));
17446
17447         alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17448                                     LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
17449                                     LPFC_SLI4_MBX_NEMBED);
17450         if (alloclen < length) {
17451                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17452                                 "3099 Allocated DMA memory size (%d) is "
17453                                 "less than the requested DMA memory size "
17454                                 "(%d)\n", alloclen, length);
17455                 status = -ENOMEM;
17456                 goto out;
17457         }
17458
17459
17460
17461         rq_create = mbox->sge_array->addr[0];
17462         shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
17463
17464         bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
17465         cnt = 0;
17466
17467         for (idx = 0; idx < numrq; idx++) {
17468                 hrq = hrqp[idx];
17469                 drq = drqp[idx];
17470                 cq  = cqp[idx];
17471
17472                 /* sanity check on queue memory */
17473                 if (!hrq || !drq || !cq) {
17474                         status = -ENODEV;
17475                         goto out;
17476                 }
17477
17478                 if (hrq->entry_count != drq->entry_count) {
17479                         status = -EINVAL;
17480                         goto out;
17481                 }
17482
17483                 if (idx == 0) {
17484                         bf_set(lpfc_mbx_rq_create_num_pages,
17485                                &rq_create->u.request,
17486                                hrq->page_count);
17487                         bf_set(lpfc_mbx_rq_create_rq_cnt,
17488                                &rq_create->u.request, (numrq * 2));
17489                         bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
17490                                1);
17491                         bf_set(lpfc_rq_context_base_cq,
17492                                &rq_create->u.request.context,
17493                                cq->queue_id);
17494                         bf_set(lpfc_rq_context_data_size,
17495                                &rq_create->u.request.context,
17496                                LPFC_NVMET_DATA_BUF_SIZE);
17497                         bf_set(lpfc_rq_context_hdr_size,
17498                                &rq_create->u.request.context,
17499                                LPFC_HDR_BUF_SIZE);
17500                         bf_set(lpfc_rq_context_rqe_count_1,
17501                                &rq_create->u.request.context,
17502                                hrq->entry_count);
17503                         bf_set(lpfc_rq_context_rqe_size,
17504                                &rq_create->u.request.context,
17505                                LPFC_RQE_SIZE_8);
17506                         bf_set(lpfc_rq_context_page_size,
17507                                &rq_create->u.request.context,
17508                                (PAGE_SIZE/SLI4_PAGE_SIZE));
17509                 }
17510                 rc = 0;
17511                 list_for_each_entry(dmabuf, &hrq->page_list, list) {
17512                         memset(dmabuf->virt, 0, hw_page_size);
17513                         cnt = page_idx + dmabuf->buffer_tag;
17514                         rq_create->u.request.page[cnt].addr_lo =
17515                                         putPaddrLow(dmabuf->phys);
17516                         rq_create->u.request.page[cnt].addr_hi =
17517                                         putPaddrHigh(dmabuf->phys);
17518                         rc++;
17519                 }
17520                 page_idx += rc;
17521
17522                 rc = 0;
17523                 list_for_each_entry(dmabuf, &drq->page_list, list) {
17524                         memset(dmabuf->virt, 0, hw_page_size);
17525                         cnt = page_idx + dmabuf->buffer_tag;
17526                         rq_create->u.request.page[cnt].addr_lo =
17527                                         putPaddrLow(dmabuf->phys);
17528                         rq_create->u.request.page[cnt].addr_hi =
17529                                         putPaddrHigh(dmabuf->phys);
17530                         rc++;
17531                 }
17532                 page_idx += rc;
17533
17534                 hrq->db_format = LPFC_DB_RING_FORMAT;
17535                 hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17536                 hrq->type = LPFC_HRQ;
17537                 hrq->assoc_qid = cq->queue_id;
17538                 hrq->subtype = subtype;
17539                 hrq->host_index = 0;
17540                 hrq->hba_index = 0;
17541                 hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17542
17543                 drq->db_format = LPFC_DB_RING_FORMAT;
17544                 drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17545                 drq->type = LPFC_DRQ;
17546                 drq->assoc_qid = cq->queue_id;
17547                 drq->subtype = subtype;
17548                 drq->host_index = 0;
17549                 drq->hba_index = 0;
17550                 drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17551
17552                 list_add_tail(&hrq->list, &cq->child_list);
17553                 list_add_tail(&drq->list, &cq->child_list);
17554         }
17555
17556         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17557         /* The IOCTL status is embedded in the mailbox subheader. */
17558         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17559         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17560         if (shdr_status || shdr_add_status || rc) {
17561                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17562                                 "3120 RQ_CREATE mailbox failed with "
17563                                 "status x%x add_status x%x, mbx status x%x\n",
17564                                 shdr_status, shdr_add_status, rc);
17565                 status = -ENXIO;
17566                 goto out;
17567         }
17568         rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17569         if (rc == 0xFFFF) {
17570                 status = -ENXIO;
17571                 goto out;
17572         }
17573
17574         /* Initialize all RQs with associated queue id */
17575         for (idx = 0; idx < numrq; idx++) {
17576                 hrq = hrqp[idx];
17577                 hrq->queue_id = rc + (2 * idx);
17578                 drq = drqp[idx];
17579                 drq->queue_id = rc + (2 * idx) + 1;
17580         }
17581
17582 out:
17583         lpfc_sli4_mbox_cmd_free(phba, mbox);
17584         return status;
17585 }
17586
17587 /**
17588  * lpfc_eq_destroy - Destroy an event Queue on the HBA
17589  * @phba: HBA structure that indicates port to destroy a queue on.
17590  * @eq: The queue structure associated with the queue to destroy.
17591  *
17592  * This function destroys a queue, as detailed in @eq by sending an mailbox
17593  * command, specific to the type of queue, to the HBA.
17594  *
17595  * The @eq struct is used to get the queue ID of the queue to destroy.
17596  *
17597  * On success this function will return a zero. If the queue destroy mailbox
17598  * command fails this function will return -ENXIO.
17599  **/
17600 int
17601 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
17602 {
17603         LPFC_MBOXQ_t *mbox;
17604         int rc, length, status = 0;
17605         uint32_t shdr_status, shdr_add_status;
17606         union lpfc_sli4_cfg_shdr *shdr;
17607
17608         /* sanity check on queue memory */
17609         if (!eq)
17610                 return -ENODEV;
17611
17612         mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
17613         if (!mbox)
17614                 return -ENOMEM;
17615         length = (sizeof(struct lpfc_mbx_eq_destroy) -
17616                   sizeof(struct lpfc_sli4_cfg_mhdr));
17617         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17618                          LPFC_MBOX_OPCODE_EQ_DESTROY,
17619                          length, LPFC_SLI4_MBX_EMBED);
17620         bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
17621                eq->queue_id);
17622         mbox->vport = eq->phba->pport;
17623         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17624
17625         rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
17626         /* The IOCTL status is embedded in the mailbox subheader. */
17627         shdr = (union lpfc_sli4_cfg_shdr *)
17628                 &mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
17629         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17630         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17631         if (shdr_status || shdr_add_status || rc) {
17632                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17633                                 "2505 EQ_DESTROY mailbox failed with "
17634                                 "status x%x add_status x%x, mbx status x%x\n",
17635                                 shdr_status, shdr_add_status, rc);
17636                 status = -ENXIO;
17637         }
17638
17639         /* Remove eq from any list */
17640         list_del_init(&eq->list);
17641         mempool_free(mbox, eq->phba->mbox_mem_pool);
17642         return status;
17643 }
17644
17645 /**
17646  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
17647  * @phba: HBA structure that indicates port to destroy a queue on.
17648  * @cq: The queue structure associated with the queue to destroy.
17649  *
17650  * This function destroys a queue, as detailed in @cq by sending an mailbox
17651  * command, specific to the type of queue, to the HBA.
17652  *
17653  * The @cq struct is used to get the queue ID of the queue to destroy.
17654  *
17655  * On success this function will return a zero. If the queue destroy mailbox
17656  * command fails this function will return -ENXIO.
17657  **/
17658 int
17659 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
17660 {
17661         LPFC_MBOXQ_t *mbox;
17662         int rc, length, status = 0;
17663         uint32_t shdr_status, shdr_add_status;
17664         union lpfc_sli4_cfg_shdr *shdr;
17665
17666         /* sanity check on queue memory */
17667         if (!cq)
17668                 return -ENODEV;
17669         mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
17670         if (!mbox)
17671                 return -ENOMEM;
17672         length = (sizeof(struct lpfc_mbx_cq_destroy) -
17673                   sizeof(struct lpfc_sli4_cfg_mhdr));
17674         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17675                          LPFC_MBOX_OPCODE_CQ_DESTROY,
17676                          length, LPFC_SLI4_MBX_EMBED);
17677         bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
17678                cq->queue_id);
17679         mbox->vport = cq->phba->pport;
17680         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17681         rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
17682         /* The IOCTL status is embedded in the mailbox subheader. */
17683         shdr = (union lpfc_sli4_cfg_shdr *)
17684                 &mbox->u.mqe.un.wq_create.header.cfg_shdr;
17685         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17686         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17687         if (shdr_status || shdr_add_status || rc) {
17688                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17689                                 "2506 CQ_DESTROY mailbox failed with "
17690                                 "status x%x add_status x%x, mbx status x%x\n",
17691                                 shdr_status, shdr_add_status, rc);
17692                 status = -ENXIO;
17693         }
17694         /* Remove cq from any list */
17695         list_del_init(&cq->list);
17696         mempool_free(mbox, cq->phba->mbox_mem_pool);
17697         return status;
17698 }
17699
17700 /**
17701  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
17702  * @phba: HBA structure that indicates port to destroy a queue on.
17703  * @mq: The queue structure associated with the queue to destroy.
17704  *
17705  * This function destroys a queue, as detailed in @mq by sending an mailbox
17706  * command, specific to the type of queue, to the HBA.
17707  *
17708  * The @mq struct is used to get the queue ID of the queue to destroy.
17709  *
17710  * On success this function will return a zero. If the queue destroy mailbox
17711  * command fails this function will return -ENXIO.
17712  **/
17713 int
17714 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
17715 {
17716         LPFC_MBOXQ_t *mbox;
17717         int rc, length, status = 0;
17718         uint32_t shdr_status, shdr_add_status;
17719         union lpfc_sli4_cfg_shdr *shdr;
17720
17721         /* sanity check on queue memory */
17722         if (!mq)
17723                 return -ENODEV;
17724         mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
17725         if (!mbox)
17726                 return -ENOMEM;
17727         length = (sizeof(struct lpfc_mbx_mq_destroy) -
17728                   sizeof(struct lpfc_sli4_cfg_mhdr));
17729         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17730                          LPFC_MBOX_OPCODE_MQ_DESTROY,
17731                          length, LPFC_SLI4_MBX_EMBED);
17732         bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
17733                mq->queue_id);
17734         mbox->vport = mq->phba->pport;
17735         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17736         rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
17737         /* The IOCTL status is embedded in the mailbox subheader. */
17738         shdr = (union lpfc_sli4_cfg_shdr *)
17739                 &mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
17740         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17741         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17742         if (shdr_status || shdr_add_status || rc) {
17743                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17744                                 "2507 MQ_DESTROY mailbox failed with "
17745                                 "status x%x add_status x%x, mbx status x%x\n",
17746                                 shdr_status, shdr_add_status, rc);
17747                 status = -ENXIO;
17748         }
17749         /* Remove mq from any list */
17750         list_del_init(&mq->list);
17751         mempool_free(mbox, mq->phba->mbox_mem_pool);
17752         return status;
17753 }
17754
17755 /**
17756  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
17757  * @phba: HBA structure that indicates port to destroy a queue on.
17758  * @wq: The queue structure associated with the queue to destroy.
17759  *
17760  * This function destroys a queue, as detailed in @wq by sending an mailbox
17761  * command, specific to the type of queue, to the HBA.
17762  *
17763  * The @wq struct is used to get the queue ID of the queue to destroy.
17764  *
17765  * On success this function will return a zero. If the queue destroy mailbox
17766  * command fails this function will return -ENXIO.
17767  **/
17768 int
17769 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
17770 {
17771         LPFC_MBOXQ_t *mbox;
17772         int rc, length, status = 0;
17773         uint32_t shdr_status, shdr_add_status;
17774         union lpfc_sli4_cfg_shdr *shdr;
17775
17776         /* sanity check on queue memory */
17777         if (!wq)
17778                 return -ENODEV;
17779         mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
17780         if (!mbox)
17781                 return -ENOMEM;
17782         length = (sizeof(struct lpfc_mbx_wq_destroy) -
17783                   sizeof(struct lpfc_sli4_cfg_mhdr));
17784         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17785                          LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
17786                          length, LPFC_SLI4_MBX_EMBED);
17787         bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
17788                wq->queue_id);
17789         mbox->vport = wq->phba->pport;
17790         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17791         rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
17792         shdr = (union lpfc_sli4_cfg_shdr *)
17793                 &mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
17794         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17795         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17796         if (shdr_status || shdr_add_status || rc) {
17797                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17798                                 "2508 WQ_DESTROY mailbox failed with "
17799                                 "status x%x add_status x%x, mbx status x%x\n",
17800                                 shdr_status, shdr_add_status, rc);
17801                 status = -ENXIO;
17802         }
17803         /* Remove wq from any list */
17804         list_del_init(&wq->list);
17805         kfree(wq->pring);
17806         wq->pring = NULL;
17807         mempool_free(mbox, wq->phba->mbox_mem_pool);
17808         return status;
17809 }
17810
17811 /**
17812  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
17813  * @phba: HBA structure that indicates port to destroy a queue on.
17814  * @hrq: The queue structure associated with the queue to destroy.
17815  * @drq: The queue structure associated with the queue to destroy.
17816  *
17817  * This function destroys a queue, as detailed in @rq by sending an mailbox
17818  * command, specific to the type of queue, to the HBA.
17819  *
17820  * The @rq struct is used to get the queue ID of the queue to destroy.
17821  *
17822  * On success this function will return a zero. If the queue destroy mailbox
17823  * command fails this function will return -ENXIO.
17824  **/
17825 int
17826 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17827                 struct lpfc_queue *drq)
17828 {
17829         LPFC_MBOXQ_t *mbox;
17830         int rc, length, status = 0;
17831         uint32_t shdr_status, shdr_add_status;
17832         union lpfc_sli4_cfg_shdr *shdr;
17833
17834         /* sanity check on queue memory */
17835         if (!hrq || !drq)
17836                 return -ENODEV;
17837         mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
17838         if (!mbox)
17839                 return -ENOMEM;
17840         length = (sizeof(struct lpfc_mbx_rq_destroy) -
17841                   sizeof(struct lpfc_sli4_cfg_mhdr));
17842         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17843                          LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
17844                          length, LPFC_SLI4_MBX_EMBED);
17845         bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17846                hrq->queue_id);
17847         mbox->vport = hrq->phba->pport;
17848         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17849         rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
17850         /* The IOCTL status is embedded in the mailbox subheader. */
17851         shdr = (union lpfc_sli4_cfg_shdr *)
17852                 &mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17853         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17854         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17855         if (shdr_status || shdr_add_status || rc) {
17856                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17857                                 "2509 RQ_DESTROY mailbox failed with "
17858                                 "status x%x add_status x%x, mbx status x%x\n",
17859                                 shdr_status, shdr_add_status, rc);
17860                 mempool_free(mbox, hrq->phba->mbox_mem_pool);
17861                 return -ENXIO;
17862         }
17863         bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17864                drq->queue_id);
17865         rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
17866         shdr = (union lpfc_sli4_cfg_shdr *)
17867                 &mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17868         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17869         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17870         if (shdr_status || shdr_add_status || rc) {
17871                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17872                                 "2510 RQ_DESTROY mailbox failed with "
17873                                 "status x%x add_status x%x, mbx status x%x\n",
17874                                 shdr_status, shdr_add_status, rc);
17875                 status = -ENXIO;
17876         }
17877         list_del_init(&hrq->list);
17878         list_del_init(&drq->list);
17879         mempool_free(mbox, hrq->phba->mbox_mem_pool);
17880         return status;
17881 }
17882
17883 /**
17884  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
17885  * @phba: The virtual port for which this call being executed.
17886  * @pdma_phys_addr0: Physical address of the 1st SGL page.
17887  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
17888  * @xritag: the xritag that ties this io to the SGL pages.
17889  *
17890  * This routine will post the sgl pages for the IO that has the xritag
17891  * that is in the iocbq structure. The xritag is assigned during iocbq
17892  * creation and persists for as long as the driver is loaded.
17893  * if the caller has fewer than 256 scatter gather segments to map then
17894  * pdma_phys_addr1 should be 0.
17895  * If the caller needs to map more than 256 scatter gather segment then
17896  * pdma_phys_addr1 should be a valid physical address.
17897  * physical address for SGLs must be 64 byte aligned.
17898  * If you are going to map 2 SGL's then the first one must have 256 entries
17899  * the second sgl can have between 1 and 256 entries.
17900  *
17901  * Return codes:
17902  *      0 - Success
17903  *      -ENXIO, -ENOMEM - Failure
17904  **/
17905 int
17906 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
17907                 dma_addr_t pdma_phys_addr0,
17908                 dma_addr_t pdma_phys_addr1,
17909                 uint16_t xritag)
17910 {
17911         struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
17912         LPFC_MBOXQ_t *mbox;
17913         int rc;
17914         uint32_t shdr_status, shdr_add_status;
17915         uint32_t mbox_tmo;
17916         union lpfc_sli4_cfg_shdr *shdr;
17917
17918         if (xritag == NO_XRI) {
17919                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17920                                 "0364 Invalid param:\n");
17921                 return -EINVAL;
17922         }
17923
17924         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17925         if (!mbox)
17926                 return -ENOMEM;
17927
17928         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17929                         LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17930                         sizeof(struct lpfc_mbx_post_sgl_pages) -
17931                         sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
17932
17933         post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
17934                                 &mbox->u.mqe.un.post_sgl_pages;
17935         bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
17936         bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
17937
17938         post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo =
17939                                 cpu_to_le32(putPaddrLow(pdma_phys_addr0));
17940         post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
17941                                 cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
17942
17943         post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo =
17944                                 cpu_to_le32(putPaddrLow(pdma_phys_addr1));
17945         post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
17946                                 cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
17947         if (!phba->sli4_hba.intr_enable)
17948                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17949         else {
17950                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17951                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17952         }
17953         /* The IOCTL status is embedded in the mailbox subheader. */
17954         shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
17955         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17956         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17957         if (!phba->sli4_hba.intr_enable)
17958                 mempool_free(mbox, phba->mbox_mem_pool);
17959         else if (rc != MBX_TIMEOUT)
17960                 mempool_free(mbox, phba->mbox_mem_pool);
17961         if (shdr_status || shdr_add_status || rc) {
17962                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17963                                 "2511 POST_SGL mailbox failed with "
17964                                 "status x%x add_status x%x, mbx status x%x\n",
17965                                 shdr_status, shdr_add_status, rc);
17966         }
17967         return 0;
17968 }
17969
17970 /**
17971  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
17972  * @phba: pointer to lpfc hba data structure.
17973  *
17974  * This routine is invoked to post rpi header templates to the
17975  * HBA consistent with the SLI-4 interface spec.  This routine
17976  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
17977  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
17978  *
17979  * Returns
17980  *      A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
17981  *      LPFC_RPI_ALLOC_ERROR if no rpis are available.
17982  **/
17983 static uint16_t
17984 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
17985 {
17986         unsigned long xri;
17987
17988         /*
17989          * Fetch the next logical xri.  Because this index is logical,
17990          * the driver starts at 0 each time.
17991          */
17992         spin_lock_irq(&phba->hbalock);
17993         xri = find_next_zero_bit(phba->sli4_hba.xri_bmask,
17994                                  phba->sli4_hba.max_cfg_param.max_xri, 0);
17995         if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
17996                 spin_unlock_irq(&phba->hbalock);
17997                 return NO_XRI;
17998         } else {
17999                 set_bit(xri, phba->sli4_hba.xri_bmask);
18000                 phba->sli4_hba.max_cfg_param.xri_used++;
18001         }
18002         spin_unlock_irq(&phba->hbalock);
18003         return xri;
18004 }
18005
18006 /**
18007  * __lpfc_sli4_free_xri - Release an xri for reuse.
18008  * @phba: pointer to lpfc hba data structure.
18009  * @xri: xri to release.
18010  *
18011  * This routine is invoked to release an xri to the pool of
18012  * available rpis maintained by the driver.
18013  **/
18014 static void
18015 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18016 {
18017         if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
18018                 phba->sli4_hba.max_cfg_param.xri_used--;
18019         }
18020 }
18021
18022 /**
18023  * lpfc_sli4_free_xri - Release an xri for reuse.
18024  * @phba: pointer to lpfc hba data structure.
18025  * @xri: xri to release.
18026  *
18027  * This routine is invoked to release an xri to the pool of
18028  * available rpis maintained by the driver.
18029  **/
18030 void
18031 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18032 {
18033         spin_lock_irq(&phba->hbalock);
18034         __lpfc_sli4_free_xri(phba, xri);
18035         spin_unlock_irq(&phba->hbalock);
18036 }
18037
18038 /**
18039  * lpfc_sli4_next_xritag - Get an xritag for the io
18040  * @phba: Pointer to HBA context object.
18041  *
18042  * This function gets an xritag for the iocb. If there is no unused xritag
18043  * it will return 0xffff.
18044  * The function returns the allocated xritag if successful, else returns zero.
18045  * Zero is not a valid xritag.
18046  * The caller is not required to hold any lock.
18047  **/
18048 uint16_t
18049 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
18050 {
18051         uint16_t xri_index;
18052
18053         xri_index = lpfc_sli4_alloc_xri(phba);
18054         if (xri_index == NO_XRI)
18055                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18056                                 "2004 Failed to allocate XRI.last XRITAG is %d"
18057                                 " Max XRI is %d, Used XRI is %d\n",
18058                                 xri_index,
18059                                 phba->sli4_hba.max_cfg_param.max_xri,
18060                                 phba->sli4_hba.max_cfg_param.xri_used);
18061         return xri_index;
18062 }
18063
18064 /**
18065  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
18066  * @phba: pointer to lpfc hba data structure.
18067  * @post_sgl_list: pointer to els sgl entry list.
18068  * @post_cnt: number of els sgl entries on the list.
18069  *
18070  * This routine is invoked to post a block of driver's sgl pages to the
18071  * HBA using non-embedded mailbox command. No Lock is held. This routine
18072  * is only called when the driver is loading and after all IO has been
18073  * stopped.
18074  **/
18075 static int
18076 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
18077                             struct list_head *post_sgl_list,
18078                             int post_cnt)
18079 {
18080         struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
18081         struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18082         struct sgl_page_pairs *sgl_pg_pairs;
18083         void *viraddr;
18084         LPFC_MBOXQ_t *mbox;
18085         uint32_t reqlen, alloclen, pg_pairs;
18086         uint32_t mbox_tmo;
18087         uint16_t xritag_start = 0;
18088         int rc = 0;
18089         uint32_t shdr_status, shdr_add_status;
18090         union lpfc_sli4_cfg_shdr *shdr;
18091
18092         reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
18093                  sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18094         if (reqlen > SLI4_PAGE_SIZE) {
18095                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18096                                 "2559 Block sgl registration required DMA "
18097                                 "size (%d) great than a page\n", reqlen);
18098                 return -ENOMEM;
18099         }
18100
18101         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18102         if (!mbox)
18103                 return -ENOMEM;
18104
18105         /* Allocate DMA memory and set up the non-embedded mailbox command */
18106         alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18107                          LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
18108                          LPFC_SLI4_MBX_NEMBED);
18109
18110         if (alloclen < reqlen) {
18111                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18112                                 "0285 Allocated DMA memory size (%d) is "
18113                                 "less than the requested DMA memory "
18114                                 "size (%d)\n", alloclen, reqlen);
18115                 lpfc_sli4_mbox_cmd_free(phba, mbox);
18116                 return -ENOMEM;
18117         }
18118         /* Set up the SGL pages in the non-embedded DMA pages */
18119         viraddr = mbox->sge_array->addr[0];
18120         sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18121         sgl_pg_pairs = &sgl->sgl_pg_pairs;
18122
18123         pg_pairs = 0;
18124         list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
18125                 /* Set up the sge entry */
18126                 sgl_pg_pairs->sgl_pg0_addr_lo =
18127                                 cpu_to_le32(putPaddrLow(sglq_entry->phys));
18128                 sgl_pg_pairs->sgl_pg0_addr_hi =
18129                                 cpu_to_le32(putPaddrHigh(sglq_entry->phys));
18130                 sgl_pg_pairs->sgl_pg1_addr_lo =
18131                                 cpu_to_le32(putPaddrLow(0));
18132                 sgl_pg_pairs->sgl_pg1_addr_hi =
18133                                 cpu_to_le32(putPaddrHigh(0));
18134
18135                 /* Keep the first xritag on the list */
18136                 if (pg_pairs == 0)
18137                         xritag_start = sglq_entry->sli4_xritag;
18138                 sgl_pg_pairs++;
18139                 pg_pairs++;
18140         }
18141
18142         /* Complete initialization and perform endian conversion. */
18143         bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18144         bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
18145         sgl->word0 = cpu_to_le32(sgl->word0);
18146
18147         if (!phba->sli4_hba.intr_enable)
18148                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18149         else {
18150                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18151                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18152         }
18153         shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
18154         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18155         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18156         if (!phba->sli4_hba.intr_enable)
18157                 lpfc_sli4_mbox_cmd_free(phba, mbox);
18158         else if (rc != MBX_TIMEOUT)
18159                 lpfc_sli4_mbox_cmd_free(phba, mbox);
18160         if (shdr_status || shdr_add_status || rc) {
18161                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18162                                 "2513 POST_SGL_BLOCK mailbox command failed "
18163                                 "status x%x add_status x%x mbx status x%x\n",
18164                                 shdr_status, shdr_add_status, rc);
18165                 rc = -ENXIO;
18166         }
18167         return rc;
18168 }
18169
18170 /**
18171  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
18172  * @phba: pointer to lpfc hba data structure.
18173  * @nblist: pointer to nvme buffer list.
18174  * @count: number of scsi buffers on the list.
18175  *
18176  * This routine is invoked to post a block of @count scsi sgl pages from a
18177  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
18178  * No Lock is held.
18179  *
18180  **/
18181 static int
18182 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
18183                             int count)
18184 {
18185         struct lpfc_io_buf *lpfc_ncmd;
18186         struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18187         struct sgl_page_pairs *sgl_pg_pairs;
18188         void *viraddr;
18189         LPFC_MBOXQ_t *mbox;
18190         uint32_t reqlen, alloclen, pg_pairs;
18191         uint32_t mbox_tmo;
18192         uint16_t xritag_start = 0;
18193         int rc = 0;
18194         uint32_t shdr_status, shdr_add_status;
18195         dma_addr_t pdma_phys_bpl1;
18196         union lpfc_sli4_cfg_shdr *shdr;
18197
18198         /* Calculate the requested length of the dma memory */
18199         reqlen = count * sizeof(struct sgl_page_pairs) +
18200                  sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18201         if (reqlen > SLI4_PAGE_SIZE) {
18202                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
18203                                 "6118 Block sgl registration required DMA "
18204                                 "size (%d) great than a page\n", reqlen);
18205                 return -ENOMEM;
18206         }
18207         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18208         if (!mbox) {
18209                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18210                                 "6119 Failed to allocate mbox cmd memory\n");
18211                 return -ENOMEM;
18212         }
18213
18214         /* Allocate DMA memory and set up the non-embedded mailbox command */
18215         alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18216                                     LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
18217                                     reqlen, LPFC_SLI4_MBX_NEMBED);
18218
18219         if (alloclen < reqlen) {
18220                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18221                                 "6120 Allocated DMA memory size (%d) is "
18222                                 "less than the requested DMA memory "
18223                                 "size (%d)\n", alloclen, reqlen);
18224                 lpfc_sli4_mbox_cmd_free(phba, mbox);
18225                 return -ENOMEM;
18226         }
18227
18228         /* Get the first SGE entry from the non-embedded DMA memory */
18229         viraddr = mbox->sge_array->addr[0];
18230
18231         /* Set up the SGL pages in the non-embedded DMA pages */
18232         sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18233         sgl_pg_pairs = &sgl->sgl_pg_pairs;
18234
18235         pg_pairs = 0;
18236         list_for_each_entry(lpfc_ncmd, nblist, list) {
18237                 /* Set up the sge entry */
18238                 sgl_pg_pairs->sgl_pg0_addr_lo =
18239                         cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
18240                 sgl_pg_pairs->sgl_pg0_addr_hi =
18241                         cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
18242                 if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
18243                         pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
18244                                                 SGL_PAGE_SIZE;
18245                 else
18246                         pdma_phys_bpl1 = 0;
18247                 sgl_pg_pairs->sgl_pg1_addr_lo =
18248                         cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
18249                 sgl_pg_pairs->sgl_pg1_addr_hi =
18250                         cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
18251                 /* Keep the first xritag on the list */
18252                 if (pg_pairs == 0)
18253                         xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
18254                 sgl_pg_pairs++;
18255                 pg_pairs++;
18256         }
18257         bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18258         bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
18259         /* Perform endian conversion if necessary */
18260         sgl->word0 = cpu_to_le32(sgl->word0);
18261
18262         if (!phba->sli4_hba.intr_enable) {
18263                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18264         } else {
18265                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18266                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18267         }
18268         shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
18269         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18270         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18271         if (!phba->sli4_hba.intr_enable)
18272                 lpfc_sli4_mbox_cmd_free(phba, mbox);
18273         else if (rc != MBX_TIMEOUT)
18274                 lpfc_sli4_mbox_cmd_free(phba, mbox);
18275         if (shdr_status || shdr_add_status || rc) {
18276                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18277                                 "6125 POST_SGL_BLOCK mailbox command failed "
18278                                 "status x%x add_status x%x mbx status x%x\n",
18279                                 shdr_status, shdr_add_status, rc);
18280                 rc = -ENXIO;
18281         }
18282         return rc;
18283 }
18284
18285 /**
18286  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
18287  * @phba: pointer to lpfc hba data structure.
18288  * @post_nblist: pointer to the nvme buffer list.
18289  * @sb_count: number of nvme buffers.
18290  *
18291  * This routine walks a list of nvme buffers that was passed in. It attempts
18292  * to construct blocks of nvme buffer sgls which contains contiguous xris and
18293  * uses the non-embedded SGL block post mailbox commands to post to the port.
18294  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
18295  * embedded SGL post mailbox command for posting. The @post_nblist passed in
18296  * must be local list, thus no lock is needed when manipulate the list.
18297  *
18298  * Returns: 0 = failure, non-zero number of successfully posted buffers.
18299  **/
18300 int
18301 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
18302                            struct list_head *post_nblist, int sb_count)
18303 {
18304         struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
18305         int status, sgl_size;
18306         int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
18307         dma_addr_t pdma_phys_sgl1;
18308         int last_xritag = NO_XRI;
18309         int cur_xritag;
18310         LIST_HEAD(prep_nblist);
18311         LIST_HEAD(blck_nblist);
18312         LIST_HEAD(nvme_nblist);
18313
18314         /* sanity check */
18315         if (sb_count <= 0)
18316                 return -EINVAL;
18317
18318         sgl_size = phba->cfg_sg_dma_buf_size;
18319         list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
18320                 list_del_init(&lpfc_ncmd->list);
18321                 block_cnt++;
18322                 if ((last_xritag != NO_XRI) &&
18323                     (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
18324                         /* a hole in xri block, form a sgl posting block */
18325                         list_splice_init(&prep_nblist, &blck_nblist);
18326                         post_cnt = block_cnt - 1;
18327                         /* prepare list for next posting block */
18328                         list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18329                         block_cnt = 1;
18330                 } else {
18331                         /* prepare list for next posting block */
18332                         list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18333                         /* enough sgls for non-embed sgl mbox command */
18334                         if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
18335                                 list_splice_init(&prep_nblist, &blck_nblist);
18336                                 post_cnt = block_cnt;
18337                                 block_cnt = 0;
18338                         }
18339                 }
18340                 num_posting++;
18341                 last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18342
18343                 /* end of repost sgl list condition for NVME buffers */
18344                 if (num_posting == sb_count) {
18345                         if (post_cnt == 0) {
18346                                 /* last sgl posting block */
18347                                 list_splice_init(&prep_nblist, &blck_nblist);
18348                                 post_cnt = block_cnt;
18349                         } else if (block_cnt == 1) {
18350                                 /* last single sgl with non-contiguous xri */
18351                                 if (sgl_size > SGL_PAGE_SIZE)
18352                                         pdma_phys_sgl1 =
18353                                                 lpfc_ncmd->dma_phys_sgl +
18354                                                 SGL_PAGE_SIZE;
18355                                 else
18356                                         pdma_phys_sgl1 = 0;
18357                                 cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18358                                 status = lpfc_sli4_post_sgl(
18359                                                 phba, lpfc_ncmd->dma_phys_sgl,
18360                                                 pdma_phys_sgl1, cur_xritag);
18361                                 if (status) {
18362                                         /* Post error.  Buffer unavailable. */
18363                                         lpfc_ncmd->flags |=
18364                                                 LPFC_SBUF_NOT_POSTED;
18365                                 } else {
18366                                         /* Post success. Bffer available. */
18367                                         lpfc_ncmd->flags &=
18368                                                 ~LPFC_SBUF_NOT_POSTED;
18369                                         lpfc_ncmd->status = IOSTAT_SUCCESS;
18370                                         num_posted++;
18371                                 }
18372                                 /* success, put on NVME buffer sgl list */
18373                                 list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18374                         }
18375                 }
18376
18377                 /* continue until a nembed page worth of sgls */
18378                 if (post_cnt == 0)
18379                         continue;
18380
18381                 /* post block of NVME buffer list sgls */
18382                 status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
18383                                                      post_cnt);
18384
18385                 /* don't reset xirtag due to hole in xri block */
18386                 if (block_cnt == 0)
18387                         last_xritag = NO_XRI;
18388
18389                 /* reset NVME buffer post count for next round of posting */
18390                 post_cnt = 0;
18391
18392                 /* put posted NVME buffer-sgl posted on NVME buffer sgl list */
18393                 while (!list_empty(&blck_nblist)) {
18394                         list_remove_head(&blck_nblist, lpfc_ncmd,
18395                                          struct lpfc_io_buf, list);
18396                         if (status) {
18397                                 /* Post error.  Mark buffer unavailable. */
18398                                 lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
18399                         } else {
18400                                 /* Post success, Mark buffer available. */
18401                                 lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
18402                                 lpfc_ncmd->status = IOSTAT_SUCCESS;
18403                                 num_posted++;
18404                         }
18405                         list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18406                 }
18407         }
18408         /* Push NVME buffers with sgl posted to the available list */
18409         lpfc_io_buf_replenish(phba, &nvme_nblist);
18410
18411         return num_posted;
18412 }
18413
18414 /**
18415  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
18416  * @phba: pointer to lpfc_hba struct that the frame was received on
18417  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18418  *
18419  * This function checks the fields in the @fc_hdr to see if the FC frame is a
18420  * valid type of frame that the LPFC driver will handle. This function will
18421  * return a zero if the frame is a valid frame or a non zero value when the
18422  * frame does not pass the check.
18423  **/
18424 static int
18425 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
18426 {
18427         /*  make rctl_names static to save stack space */
18428         struct fc_vft_header *fc_vft_hdr;
18429         uint32_t *header = (uint32_t *) fc_hdr;
18430
18431 #define FC_RCTL_MDS_DIAGS       0xF4
18432
18433         switch (fc_hdr->fh_r_ctl) {
18434         case FC_RCTL_DD_UNCAT:          /* uncategorized information */
18435         case FC_RCTL_DD_SOL_DATA:       /* solicited data */
18436         case FC_RCTL_DD_UNSOL_CTL:      /* unsolicited control */
18437         case FC_RCTL_DD_SOL_CTL:        /* solicited control or reply */
18438         case FC_RCTL_DD_UNSOL_DATA:     /* unsolicited data */
18439         case FC_RCTL_DD_DATA_DESC:      /* data descriptor */
18440         case FC_RCTL_DD_UNSOL_CMD:      /* unsolicited command */
18441         case FC_RCTL_DD_CMD_STATUS:     /* command status */
18442         case FC_RCTL_ELS_REQ:   /* extended link services request */
18443         case FC_RCTL_ELS_REP:   /* extended link services reply */
18444         case FC_RCTL_ELS4_REQ:  /* FC-4 ELS request */
18445         case FC_RCTL_ELS4_REP:  /* FC-4 ELS reply */
18446         case FC_RCTL_BA_NOP:    /* basic link service NOP */
18447         case FC_RCTL_BA_ABTS:   /* basic link service abort */
18448         case FC_RCTL_BA_RMC:    /* remove connection */
18449         case FC_RCTL_BA_ACC:    /* basic accept */
18450         case FC_RCTL_BA_RJT:    /* basic reject */
18451         case FC_RCTL_BA_PRMT:
18452         case FC_RCTL_ACK_1:     /* acknowledge_1 */
18453         case FC_RCTL_ACK_0:     /* acknowledge_0 */
18454         case FC_RCTL_P_RJT:     /* port reject */
18455         case FC_RCTL_F_RJT:     /* fabric reject */
18456         case FC_RCTL_P_BSY:     /* port busy */
18457         case FC_RCTL_F_BSY:     /* fabric busy to data frame */
18458         case FC_RCTL_F_BSYL:    /* fabric busy to link control frame */
18459         case FC_RCTL_LCR:       /* link credit reset */
18460         case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
18461         case FC_RCTL_END:       /* end */
18462                 break;
18463         case FC_RCTL_VFTH:      /* Virtual Fabric tagging Header */
18464                 fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18465                 fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
18466                 return lpfc_fc_frame_check(phba, fc_hdr);
18467         default:
18468                 goto drop;
18469         }
18470
18471         switch (fc_hdr->fh_type) {
18472         case FC_TYPE_BLS:
18473         case FC_TYPE_ELS:
18474         case FC_TYPE_FCP:
18475         case FC_TYPE_CT:
18476         case FC_TYPE_NVME:
18477                 break;
18478         case FC_TYPE_IP:
18479         case FC_TYPE_ILS:
18480         default:
18481                 goto drop;
18482         }
18483
18484         lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
18485                         "2538 Received frame rctl:x%x, type:x%x, "
18486                         "frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
18487                         fc_hdr->fh_r_ctl, fc_hdr->fh_type,
18488                         be32_to_cpu(header[0]), be32_to_cpu(header[1]),
18489                         be32_to_cpu(header[2]), be32_to_cpu(header[3]),
18490                         be32_to_cpu(header[4]), be32_to_cpu(header[5]),
18491                         be32_to_cpu(header[6]));
18492         return 0;
18493 drop:
18494         lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
18495                         "2539 Dropped frame rctl:x%x type:x%x\n",
18496                         fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18497         return 1;
18498 }
18499
18500 /**
18501  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
18502  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18503  *
18504  * This function processes the FC header to retrieve the VFI from the VF
18505  * header, if one exists. This function will return the VFI if one exists
18506  * or 0 if no VSAN Header exists.
18507  **/
18508 static uint32_t
18509 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
18510 {
18511         struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18512
18513         if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
18514                 return 0;
18515         return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
18516 }
18517
18518 /**
18519  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
18520  * @phba: Pointer to the HBA structure to search for the vport on
18521  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18522  * @fcfi: The FC Fabric ID that the frame came from
18523  * @did: Destination ID to match against
18524  *
18525  * This function searches the @phba for a vport that matches the content of the
18526  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
18527  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
18528  * returns the matching vport pointer or NULL if unable to match frame to a
18529  * vport.
18530  **/
18531 static struct lpfc_vport *
18532 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
18533                        uint16_t fcfi, uint32_t did)
18534 {
18535         struct lpfc_vport **vports;
18536         struct lpfc_vport *vport = NULL;
18537         int i;
18538
18539         if (did == Fabric_DID)
18540                 return phba->pport;
18541         if ((phba->pport->fc_flag & FC_PT2PT) &&
18542                 !(phba->link_state == LPFC_HBA_READY))
18543                 return phba->pport;
18544
18545         vports = lpfc_create_vport_work_array(phba);
18546         if (vports != NULL) {
18547                 for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
18548                         if (phba->fcf.fcfi == fcfi &&
18549                             vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
18550                             vports[i]->fc_myDID == did) {
18551                                 vport = vports[i];
18552                                 break;
18553                         }
18554                 }
18555         }
18556         lpfc_destroy_vport_work_array(phba, vports);
18557         return vport;
18558 }
18559
18560 /**
18561  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
18562  * @vport: The vport to work on.
18563  *
18564  * This function updates the receive sequence time stamp for this vport. The
18565  * receive sequence time stamp indicates the time that the last frame of the
18566  * the sequence that has been idle for the longest amount of time was received.
18567  * the driver uses this time stamp to indicate if any received sequences have
18568  * timed out.
18569  **/
18570 static void
18571 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
18572 {
18573         struct lpfc_dmabuf *h_buf;
18574         struct hbq_dmabuf *dmabuf = NULL;
18575
18576         /* get the oldest sequence on the rcv list */
18577         h_buf = list_get_first(&vport->rcv_buffer_list,
18578                                struct lpfc_dmabuf, list);
18579         if (!h_buf)
18580                 return;
18581         dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18582         vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
18583 }
18584
18585 /**
18586  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
18587  * @vport: The vport that the received sequences were sent to.
18588  *
18589  * This function cleans up all outstanding received sequences. This is called
18590  * by the driver when a link event or user action invalidates all the received
18591  * sequences.
18592  **/
18593 void
18594 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
18595 {
18596         struct lpfc_dmabuf *h_buf, *hnext;
18597         struct lpfc_dmabuf *d_buf, *dnext;
18598         struct hbq_dmabuf *dmabuf = NULL;
18599
18600         /* start with the oldest sequence on the rcv list */
18601         list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18602                 dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18603                 list_del_init(&dmabuf->hbuf.list);
18604                 list_for_each_entry_safe(d_buf, dnext,
18605                                          &dmabuf->dbuf.list, list) {
18606                         list_del_init(&d_buf->list);
18607                         lpfc_in_buf_free(vport->phba, d_buf);
18608                 }
18609                 lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18610         }
18611 }
18612
18613 /**
18614  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
18615  * @vport: The vport that the received sequences were sent to.
18616  *
18617  * This function determines whether any received sequences have timed out by
18618  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
18619  * indicates that there is at least one timed out sequence this routine will
18620  * go through the received sequences one at a time from most inactive to most
18621  * active to determine which ones need to be cleaned up. Once it has determined
18622  * that a sequence needs to be cleaned up it will simply free up the resources
18623  * without sending an abort.
18624  **/
18625 void
18626 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
18627 {
18628         struct lpfc_dmabuf *h_buf, *hnext;
18629         struct lpfc_dmabuf *d_buf, *dnext;
18630         struct hbq_dmabuf *dmabuf = NULL;
18631         unsigned long timeout;
18632         int abort_count = 0;
18633
18634         timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18635                    vport->rcv_buffer_time_stamp);
18636         if (list_empty(&vport->rcv_buffer_list) ||
18637             time_before(jiffies, timeout))
18638                 return;
18639         /* start with the oldest sequence on the rcv list */
18640         list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18641                 dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18642                 timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18643                            dmabuf->time_stamp);
18644                 if (time_before(jiffies, timeout))
18645                         break;
18646                 abort_count++;
18647                 list_del_init(&dmabuf->hbuf.list);
18648                 list_for_each_entry_safe(d_buf, dnext,
18649                                          &dmabuf->dbuf.list, list) {
18650                         list_del_init(&d_buf->list);
18651                         lpfc_in_buf_free(vport->phba, d_buf);
18652                 }
18653                 lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18654         }
18655         if (abort_count)
18656                 lpfc_update_rcv_time_stamp(vport);
18657 }
18658
18659 /**
18660  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
18661  * @vport: pointer to a vitural port
18662  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
18663  *
18664  * This function searches through the existing incomplete sequences that have
18665  * been sent to this @vport. If the frame matches one of the incomplete
18666  * sequences then the dbuf in the @dmabuf is added to the list of frames that
18667  * make up that sequence. If no sequence is found that matches this frame then
18668  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
18669  * This function returns a pointer to the first dmabuf in the sequence list that
18670  * the frame was linked to.
18671  **/
18672 static struct hbq_dmabuf *
18673 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18674 {
18675         struct fc_frame_header *new_hdr;
18676         struct fc_frame_header *temp_hdr;
18677         struct lpfc_dmabuf *d_buf;
18678         struct lpfc_dmabuf *h_buf;
18679         struct hbq_dmabuf *seq_dmabuf = NULL;
18680         struct hbq_dmabuf *temp_dmabuf = NULL;
18681         uint8_t found = 0;
18682
18683         INIT_LIST_HEAD(&dmabuf->dbuf.list);
18684         dmabuf->time_stamp = jiffies;
18685         new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18686
18687         /* Use the hdr_buf to find the sequence that this frame belongs to */
18688         list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18689                 temp_hdr = (struct fc_frame_header *)h_buf->virt;
18690                 if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18691                     (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18692                     (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18693                         continue;
18694                 /* found a pending sequence that matches this frame */
18695                 seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18696                 break;
18697         }
18698         if (!seq_dmabuf) {
18699                 /*
18700                  * This indicates first frame received for this sequence.
18701                  * Queue the buffer on the vport's rcv_buffer_list.
18702                  */
18703                 list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18704                 lpfc_update_rcv_time_stamp(vport);
18705                 return dmabuf;
18706         }
18707         temp_hdr = seq_dmabuf->hbuf.virt;
18708         if (be16_to_cpu(new_hdr->fh_seq_cnt) <
18709                 be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18710                 list_del_init(&seq_dmabuf->hbuf.list);
18711                 list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18712                 list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18713                 lpfc_update_rcv_time_stamp(vport);
18714                 return dmabuf;
18715         }
18716         /* move this sequence to the tail to indicate a young sequence */
18717         list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
18718         seq_dmabuf->time_stamp = jiffies;
18719         lpfc_update_rcv_time_stamp(vport);
18720         if (list_empty(&seq_dmabuf->dbuf.list)) {
18721                 list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18722                 return seq_dmabuf;
18723         }
18724         /* find the correct place in the sequence to insert this frame */
18725         d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
18726         while (!found) {
18727                 temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18728                 temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
18729                 /*
18730                  * If the frame's sequence count is greater than the frame on
18731                  * the list then insert the frame right after this frame
18732                  */
18733                 if (be16_to_cpu(new_hdr->fh_seq_cnt) >
18734                         be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18735                         list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
18736                         found = 1;
18737                         break;
18738                 }
18739
18740                 if (&d_buf->list == &seq_dmabuf->dbuf.list)
18741                         break;
18742                 d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
18743         }
18744
18745         if (found)
18746                 return seq_dmabuf;
18747         return NULL;
18748 }
18749
18750 /**
18751  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
18752  * @vport: pointer to a vitural port
18753  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18754  *
18755  * This function tries to abort from the partially assembed sequence, described
18756  * by the information from basic abbort @dmabuf. It checks to see whether such
18757  * partially assembled sequence held by the driver. If so, it shall free up all
18758  * the frames from the partially assembled sequence.
18759  *
18760  * Return
18761  * true  -- if there is matching partially assembled sequence present and all
18762  *          the frames freed with the sequence;
18763  * false -- if there is no matching partially assembled sequence present so
18764  *          nothing got aborted in the lower layer driver
18765  **/
18766 static bool
18767 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
18768                             struct hbq_dmabuf *dmabuf)
18769 {
18770         struct fc_frame_header *new_hdr;
18771         struct fc_frame_header *temp_hdr;
18772         struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
18773         struct hbq_dmabuf *seq_dmabuf = NULL;
18774
18775         /* Use the hdr_buf to find the sequence that matches this frame */
18776         INIT_LIST_HEAD(&dmabuf->dbuf.list);
18777         INIT_LIST_HEAD(&dmabuf->hbuf.list);
18778         new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18779         list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18780                 temp_hdr = (struct fc_frame_header *)h_buf->virt;
18781                 if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18782                     (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18783                     (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18784                         continue;
18785                 /* found a pending sequence that matches this frame */
18786                 seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18787                 break;
18788         }
18789
18790         /* Free up all the frames from the partially assembled sequence */
18791         if (seq_dmabuf) {
18792                 list_for_each_entry_safe(d_buf, n_buf,
18793                                          &seq_dmabuf->dbuf.list, list) {
18794                         list_del_init(&d_buf->list);
18795                         lpfc_in_buf_free(vport->phba, d_buf);
18796                 }
18797                 return true;
18798         }
18799         return false;
18800 }
18801
18802 /**
18803  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
18804  * @vport: pointer to a vitural port
18805  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18806  *
18807  * This function tries to abort from the assembed sequence from upper level
18808  * protocol, described by the information from basic abbort @dmabuf. It
18809  * checks to see whether such pending context exists at upper level protocol.
18810  * If so, it shall clean up the pending context.
18811  *
18812  * Return
18813  * true  -- if there is matching pending context of the sequence cleaned
18814  *          at ulp;
18815  * false -- if there is no matching pending context of the sequence present
18816  *          at ulp.
18817  **/
18818 static bool
18819 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18820 {
18821         struct lpfc_hba *phba = vport->phba;
18822         int handled;
18823
18824         /* Accepting abort at ulp with SLI4 only */
18825         if (phba->sli_rev < LPFC_SLI_REV4)
18826                 return false;
18827
18828         /* Register all caring upper level protocols to attend abort */
18829         handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
18830         if (handled)
18831                 return true;
18832
18833         return false;
18834 }
18835
18836 /**
18837  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
18838  * @phba: Pointer to HBA context object.
18839  * @cmd_iocbq: pointer to the command iocbq structure.
18840  * @rsp_iocbq: pointer to the response iocbq structure.
18841  *
18842  * This function handles the sequence abort response iocb command complete
18843  * event. It properly releases the memory allocated to the sequence abort
18844  * accept iocb.
18845  **/
18846 static void
18847 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
18848                              struct lpfc_iocbq *cmd_iocbq,
18849                              struct lpfc_iocbq *rsp_iocbq)
18850 {
18851         struct lpfc_nodelist *ndlp;
18852
18853         if (cmd_iocbq) {
18854                 ndlp = (struct lpfc_nodelist *)cmd_iocbq->context1;
18855                 lpfc_nlp_put(ndlp);
18856                 lpfc_sli_release_iocbq(phba, cmd_iocbq);
18857         }
18858
18859         /* Failure means BLS ABORT RSP did not get delivered to remote node*/
18860         if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
18861                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18862                         "3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
18863                         rsp_iocbq->iocb.ulpStatus,
18864                         rsp_iocbq->iocb.un.ulpWord[4]);
18865 }
18866
18867 /**
18868  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
18869  * @phba: Pointer to HBA context object.
18870  * @xri: xri id in transaction.
18871  *
18872  * This function validates the xri maps to the known range of XRIs allocated an
18873  * used by the driver.
18874  **/
18875 uint16_t
18876 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
18877                       uint16_t xri)
18878 {
18879         uint16_t i;
18880
18881         for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
18882                 if (xri == phba->sli4_hba.xri_ids[i])
18883                         return i;
18884         }
18885         return NO_XRI;
18886 }
18887
18888 /**
18889  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
18890  * @vport: pointer to a virtual port.
18891  * @fc_hdr: pointer to a FC frame header.
18892  * @aborted: was the partially assembled receive sequence successfully aborted
18893  *
18894  * This function sends a basic response to a previous unsol sequence abort
18895  * event after aborting the sequence handling.
18896  **/
18897 void
18898 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
18899                         struct fc_frame_header *fc_hdr, bool aborted)
18900 {
18901         struct lpfc_hba *phba = vport->phba;
18902         struct lpfc_iocbq *ctiocb = NULL;
18903         struct lpfc_nodelist *ndlp;
18904         uint16_t oxid, rxid, xri, lxri;
18905         uint32_t sid, fctl;
18906         IOCB_t *icmd;
18907         int rc;
18908
18909         if (!lpfc_is_link_up(phba))
18910                 return;
18911
18912         sid = sli4_sid_from_fc_hdr(fc_hdr);
18913         oxid = be16_to_cpu(fc_hdr->fh_ox_id);
18914         rxid = be16_to_cpu(fc_hdr->fh_rx_id);
18915
18916         ndlp = lpfc_findnode_did(vport, sid);
18917         if (!ndlp) {
18918                 ndlp = lpfc_nlp_init(vport, sid);
18919                 if (!ndlp) {
18920                         lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
18921                                          "1268 Failed to allocate ndlp for "
18922                                          "oxid:x%x SID:x%x\n", oxid, sid);
18923                         return;
18924                 }
18925                 /* Put ndlp onto pport node list */
18926                 lpfc_enqueue_node(vport, ndlp);
18927         }
18928
18929         /* Allocate buffer for rsp iocb */
18930         ctiocb = lpfc_sli_get_iocbq(phba);
18931         if (!ctiocb)
18932                 return;
18933
18934         /* Extract the F_CTL field from FC_HDR */
18935         fctl = sli4_fctl_from_fc_hdr(fc_hdr);
18936
18937         icmd = &ctiocb->iocb;
18938         icmd->un.xseq64.bdl.bdeSize = 0;
18939         icmd->un.xseq64.bdl.ulpIoTag32 = 0;
18940         icmd->un.xseq64.w5.hcsw.Dfctl = 0;
18941         icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_ACC;
18942         icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_BLS;
18943
18944         /* Fill in the rest of iocb fields */
18945         icmd->ulpCommand = CMD_XMIT_BLS_RSP64_CX;
18946         icmd->ulpBdeCount = 0;
18947         icmd->ulpLe = 1;
18948         icmd->ulpClass = CLASS3;
18949         icmd->ulpContext = phba->sli4_hba.rpi_ids[ndlp->nlp_rpi];
18950         ctiocb->context1 = lpfc_nlp_get(ndlp);
18951         if (!ctiocb->context1) {
18952                 lpfc_sli_release_iocbq(phba, ctiocb);
18953                 return;
18954         }
18955
18956         ctiocb->vport = phba->pport;
18957         ctiocb->iocb_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
18958         ctiocb->sli4_lxritag = NO_XRI;
18959         ctiocb->sli4_xritag = NO_XRI;
18960
18961         if (fctl & FC_FC_EX_CTX)
18962                 /* Exchange responder sent the abort so we
18963                  * own the oxid.
18964                  */
18965                 xri = oxid;
18966         else
18967                 xri = rxid;
18968         lxri = lpfc_sli4_xri_inrange(phba, xri);
18969         if (lxri != NO_XRI)
18970                 lpfc_set_rrq_active(phba, ndlp, lxri,
18971                         (xri == oxid) ? rxid : oxid, 0);
18972         /* For BA_ABTS from exchange responder, if the logical xri with
18973          * the oxid maps to the FCP XRI range, the port no longer has
18974          * that exchange context, send a BLS_RJT. Override the IOCB for
18975          * a BA_RJT.
18976          */
18977         if ((fctl & FC_FC_EX_CTX) &&
18978             (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
18979                 icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
18980                 bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
18981                 bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
18982                 bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
18983         }
18984
18985         /* If BA_ABTS failed to abort a partially assembled receive sequence,
18986          * the driver no longer has that exchange, send a BLS_RJT. Override
18987          * the IOCB for a BA_RJT.
18988          */
18989         if (aborted == false) {
18990                 icmd->un.xseq64.w5.hcsw.Rctl = FC_RCTL_BA_RJT;
18991                 bf_set(lpfc_vndr_code, &icmd->un.bls_rsp, 0);
18992                 bf_set(lpfc_rsn_expln, &icmd->un.bls_rsp, FC_BA_RJT_INV_XID);
18993                 bf_set(lpfc_rsn_code, &icmd->un.bls_rsp, FC_BA_RJT_UNABLE);
18994         }
18995
18996         if (fctl & FC_FC_EX_CTX) {
18997                 /* ABTS sent by responder to CT exchange, construction
18998                  * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
18999                  * field and RX_ID from ABTS for RX_ID field.
19000                  */
19001                 bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_RSP);
19002         } else {
19003                 /* ABTS sent by initiator to CT exchange, construction
19004                  * of BA_ACC will need to allocate a new XRI as for the
19005                  * XRI_TAG field.
19006                  */
19007                 bf_set(lpfc_abts_orig, &icmd->un.bls_rsp, LPFC_ABTS_UNSOL_INT);
19008         }
19009         bf_set(lpfc_abts_rxid, &icmd->un.bls_rsp, rxid);
19010         bf_set(lpfc_abts_oxid, &icmd->un.bls_rsp, oxid);
19011
19012         /* Xmit CT abts response on exchange <xid> */
19013         lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
19014                          "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
19015                          icmd->un.xseq64.w5.hcsw.Rctl, oxid, phba->link_state);
19016
19017         rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
19018         if (rc == IOCB_ERROR) {
19019                 lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19020                                  "2925 Failed to issue CT ABTS RSP x%x on "
19021                                  "xri x%x, Data x%x\n",
19022                                  icmd->un.xseq64.w5.hcsw.Rctl, oxid,
19023                                  phba->link_state);
19024                 lpfc_nlp_put(ndlp);
19025                 ctiocb->context1 = NULL;
19026                 lpfc_sli_release_iocbq(phba, ctiocb);
19027         }
19028 }
19029
19030 /**
19031  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
19032  * @vport: Pointer to the vport on which this sequence was received
19033  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19034  *
19035  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
19036  * receive sequence is only partially assembed by the driver, it shall abort
19037  * the partially assembled frames for the sequence. Otherwise, if the
19038  * unsolicited receive sequence has been completely assembled and passed to
19039  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
19040  * unsolicited sequence has been aborted. After that, it will issue a basic
19041  * accept to accept the abort.
19042  **/
19043 static void
19044 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
19045                              struct hbq_dmabuf *dmabuf)
19046 {
19047         struct lpfc_hba *phba = vport->phba;
19048         struct fc_frame_header fc_hdr;
19049         uint32_t fctl;
19050         bool aborted;
19051
19052         /* Make a copy of fc_hdr before the dmabuf being released */
19053         memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
19054         fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
19055
19056         if (fctl & FC_FC_EX_CTX) {
19057                 /* ABTS by responder to exchange, no cleanup needed */
19058                 aborted = true;
19059         } else {
19060                 /* ABTS by initiator to exchange, need to do cleanup */
19061                 aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
19062                 if (aborted == false)
19063                         aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
19064         }
19065         lpfc_in_buf_free(phba, &dmabuf->dbuf);
19066
19067         if (phba->nvmet_support) {
19068                 lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
19069                 return;
19070         }
19071
19072         /* Respond with BA_ACC or BA_RJT accordingly */
19073         lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
19074 }
19075
19076 /**
19077  * lpfc_seq_complete - Indicates if a sequence is complete
19078  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19079  *
19080  * This function checks the sequence, starting with the frame described by
19081  * @dmabuf, to see if all the frames associated with this sequence are present.
19082  * the frames associated with this sequence are linked to the @dmabuf using the
19083  * dbuf list. This function looks for two major things. 1) That the first frame
19084  * has a sequence count of zero. 2) There is a frame with last frame of sequence
19085  * set. 3) That there are no holes in the sequence count. The function will
19086  * return 1 when the sequence is complete, otherwise it will return 0.
19087  **/
19088 static int
19089 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
19090 {
19091         struct fc_frame_header *hdr;
19092         struct lpfc_dmabuf *d_buf;
19093         struct hbq_dmabuf *seq_dmabuf;
19094         uint32_t fctl;
19095         int seq_count = 0;
19096
19097         hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19098         /* make sure first fame of sequence has a sequence count of zero */
19099         if (hdr->fh_seq_cnt != seq_count)
19100                 return 0;
19101         fctl = (hdr->fh_f_ctl[0] << 16 |
19102                 hdr->fh_f_ctl[1] << 8 |
19103                 hdr->fh_f_ctl[2]);
19104         /* If last frame of sequence we can return success. */
19105         if (fctl & FC_FC_END_SEQ)
19106                 return 1;
19107         list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
19108                 seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19109                 hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19110                 /* If there is a hole in the sequence count then fail. */
19111                 if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
19112                         return 0;
19113                 fctl = (hdr->fh_f_ctl[0] << 16 |
19114                         hdr->fh_f_ctl[1] << 8 |
19115                         hdr->fh_f_ctl[2]);
19116                 /* If last frame of sequence we can return success. */
19117                 if (fctl & FC_FC_END_SEQ)
19118                         return 1;
19119         }
19120         return 0;
19121 }
19122
19123 /**
19124  * lpfc_prep_seq - Prep sequence for ULP processing
19125  * @vport: Pointer to the vport on which this sequence was received
19126  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
19127  *
19128  * This function takes a sequence, described by a list of frames, and creates
19129  * a list of iocbq structures to describe the sequence. This iocbq list will be
19130  * used to issue to the generic unsolicited sequence handler. This routine
19131  * returns a pointer to the first iocbq in the list. If the function is unable
19132  * to allocate an iocbq then it throw out the received frames that were not
19133  * able to be described and return a pointer to the first iocbq. If unable to
19134  * allocate any iocbqs (including the first) this function will return NULL.
19135  **/
19136 static struct lpfc_iocbq *
19137 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
19138 {
19139         struct hbq_dmabuf *hbq_buf;
19140         struct lpfc_dmabuf *d_buf, *n_buf;
19141         struct lpfc_iocbq *first_iocbq, *iocbq;
19142         struct fc_frame_header *fc_hdr;
19143         uint32_t sid;
19144         uint32_t len, tot_len;
19145         struct ulp_bde64 *pbde;
19146
19147         fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19148         /* remove from receive buffer list */
19149         list_del_init(&seq_dmabuf->hbuf.list);
19150         lpfc_update_rcv_time_stamp(vport);
19151         /* get the Remote Port's SID */
19152         sid = sli4_sid_from_fc_hdr(fc_hdr);
19153         tot_len = 0;
19154         /* Get an iocbq struct to fill in. */
19155         first_iocbq = lpfc_sli_get_iocbq(vport->phba);
19156         if (first_iocbq) {
19157                 /* Initialize the first IOCB. */
19158                 first_iocbq->iocb.unsli3.rcvsli3.acc_len = 0;
19159                 first_iocbq->iocb.ulpStatus = IOSTAT_SUCCESS;
19160                 first_iocbq->vport = vport;
19161
19162                 /* Check FC Header to see what TYPE of frame we are rcv'ing */
19163                 if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
19164                         first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_ELS64_CX;
19165                         first_iocbq->iocb.un.rcvels.parmRo =
19166                                 sli4_did_from_fc_hdr(fc_hdr);
19167                         first_iocbq->iocb.ulpPU = PARM_NPIV_DID;
19168                 } else
19169                         first_iocbq->iocb.ulpCommand = CMD_IOCB_RCV_SEQ64_CX;
19170                 first_iocbq->iocb.ulpContext = NO_XRI;
19171                 first_iocbq->iocb.unsli3.rcvsli3.ox_id =
19172                         be16_to_cpu(fc_hdr->fh_ox_id);
19173                 /* iocbq is prepped for internal consumption.  Physical vpi. */
19174                 first_iocbq->iocb.unsli3.rcvsli3.vpi =
19175                         vport->phba->vpi_ids[vport->vpi];
19176                 /* put the first buffer into the first IOCBq */
19177                 tot_len = bf_get(lpfc_rcqe_length,
19178                                        &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
19179
19180                 first_iocbq->context2 = &seq_dmabuf->dbuf;
19181                 first_iocbq->context3 = NULL;
19182                 first_iocbq->iocb.ulpBdeCount = 1;
19183                 if (tot_len > LPFC_DATA_BUF_SIZE)
19184                         first_iocbq->iocb.un.cont64[0].tus.f.bdeSize =
19185                                                         LPFC_DATA_BUF_SIZE;
19186                 else
19187                         first_iocbq->iocb.un.cont64[0].tus.f.bdeSize = tot_len;
19188
19189                 first_iocbq->iocb.un.rcvels.remoteID = sid;
19190
19191                 first_iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
19192         }
19193         iocbq = first_iocbq;
19194         /*
19195          * Each IOCBq can have two Buffers assigned, so go through the list
19196          * of buffers for this sequence and save two buffers in each IOCBq
19197          */
19198         list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
19199                 if (!iocbq) {
19200                         lpfc_in_buf_free(vport->phba, d_buf);
19201                         continue;
19202                 }
19203                 if (!iocbq->context3) {
19204                         iocbq->context3 = d_buf;
19205                         iocbq->iocb.ulpBdeCount++;
19206                         /* We need to get the size out of the right CQE */
19207                         hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19208                         len = bf_get(lpfc_rcqe_length,
19209                                        &hbq_buf->cq_event.cqe.rcqe_cmpl);
19210                         pbde = (struct ulp_bde64 *)
19211                                         &iocbq->iocb.unsli3.sli3Words[4];
19212                         if (len > LPFC_DATA_BUF_SIZE)
19213                                 pbde->tus.f.bdeSize = LPFC_DATA_BUF_SIZE;
19214                         else
19215                                 pbde->tus.f.bdeSize = len;
19216
19217                         iocbq->iocb.unsli3.rcvsli3.acc_len += len;
19218                         tot_len += len;
19219                 } else {
19220                         iocbq = lpfc_sli_get_iocbq(vport->phba);
19221                         if (!iocbq) {
19222                                 if (first_iocbq) {
19223                                         first_iocbq->iocb.ulpStatus =
19224                                                         IOSTAT_FCP_RSP_ERROR;
19225                                         first_iocbq->iocb.un.ulpWord[4] =
19226                                                         IOERR_NO_RESOURCES;
19227                                 }
19228                                 lpfc_in_buf_free(vport->phba, d_buf);
19229                                 continue;
19230                         }
19231                         /* We need to get the size out of the right CQE */
19232                         hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19233                         len = bf_get(lpfc_rcqe_length,
19234                                        &hbq_buf->cq_event.cqe.rcqe_cmpl);
19235                         iocbq->context2 = d_buf;
19236                         iocbq->context3 = NULL;
19237                         iocbq->iocb.ulpBdeCount = 1;
19238                         if (len > LPFC_DATA_BUF_SIZE)
19239                                 iocbq->iocb.un.cont64[0].tus.f.bdeSize =
19240                                                         LPFC_DATA_BUF_SIZE;
19241                         else
19242                                 iocbq->iocb.un.cont64[0].tus.f.bdeSize = len;
19243
19244                         tot_len += len;
19245                         iocbq->iocb.unsli3.rcvsli3.acc_len = tot_len;
19246
19247                         iocbq->iocb.un.rcvels.remoteID = sid;
19248                         list_add_tail(&iocbq->list, &first_iocbq->list);
19249                 }
19250         }
19251         /* Free the sequence's header buffer */
19252         if (!first_iocbq)
19253                 lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
19254
19255         return first_iocbq;
19256 }
19257
19258 static void
19259 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
19260                           struct hbq_dmabuf *seq_dmabuf)
19261 {
19262         struct fc_frame_header *fc_hdr;
19263         struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
19264         struct lpfc_hba *phba = vport->phba;
19265
19266         fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19267         iocbq = lpfc_prep_seq(vport, seq_dmabuf);
19268         if (!iocbq) {
19269                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19270                                 "2707 Ring %d handler: Failed to allocate "
19271                                 "iocb Rctl x%x Type x%x received\n",
19272                                 LPFC_ELS_RING,
19273                                 fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19274                 return;
19275         }
19276         if (!lpfc_complete_unsol_iocb(phba,
19277                                       phba->sli4_hba.els_wq->pring,
19278                                       iocbq, fc_hdr->fh_r_ctl,
19279                                       fc_hdr->fh_type))
19280                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19281                                 "2540 Ring %d handler: unexpected Rctl "
19282                                 "x%x Type x%x received\n",
19283                                 LPFC_ELS_RING,
19284                                 fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19285
19286         /* Free iocb created in lpfc_prep_seq */
19287         list_for_each_entry_safe(curr_iocb, next_iocb,
19288                 &iocbq->list, list) {
19289                 list_del_init(&curr_iocb->list);
19290                 lpfc_sli_release_iocbq(phba, curr_iocb);
19291         }
19292         lpfc_sli_release_iocbq(phba, iocbq);
19293 }
19294
19295 static void
19296 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
19297                             struct lpfc_iocbq *rspiocb)
19298 {
19299         struct lpfc_dmabuf *pcmd = cmdiocb->context2;
19300
19301         if (pcmd && pcmd->virt)
19302                 dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19303         kfree(pcmd);
19304         lpfc_sli_release_iocbq(phba, cmdiocb);
19305         lpfc_drain_txq(phba);
19306 }
19307
19308 static void
19309 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
19310                               struct hbq_dmabuf *dmabuf)
19311 {
19312         struct fc_frame_header *fc_hdr;
19313         struct lpfc_hba *phba = vport->phba;
19314         struct lpfc_iocbq *iocbq = NULL;
19315         union  lpfc_wqe *wqe;
19316         struct lpfc_dmabuf *pcmd = NULL;
19317         uint32_t frame_len;
19318         int rc;
19319         unsigned long iflags;
19320
19321         fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19322         frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
19323
19324         /* Send the received frame back */
19325         iocbq = lpfc_sli_get_iocbq(phba);
19326         if (!iocbq) {
19327                 /* Queue cq event and wakeup worker thread to process it */
19328                 spin_lock_irqsave(&phba->hbalock, iflags);
19329                 list_add_tail(&dmabuf->cq_event.list,
19330                               &phba->sli4_hba.sp_queue_event);
19331                 phba->hba_flag |= HBA_SP_QUEUE_EVT;
19332                 spin_unlock_irqrestore(&phba->hbalock, iflags);
19333                 lpfc_worker_wake_up(phba);
19334                 return;
19335         }
19336
19337         /* Allocate buffer for command payload */
19338         pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
19339         if (pcmd)
19340                 pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
19341                                             &pcmd->phys);
19342         if (!pcmd || !pcmd->virt)
19343                 goto exit;
19344
19345         INIT_LIST_HEAD(&pcmd->list);
19346
19347         /* copyin the payload */
19348         memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
19349
19350         /* fill in BDE's for command */
19351         iocbq->iocb.un.xseq64.bdl.addrHigh = putPaddrHigh(pcmd->phys);
19352         iocbq->iocb.un.xseq64.bdl.addrLow = putPaddrLow(pcmd->phys);
19353         iocbq->iocb.un.xseq64.bdl.bdeFlags = BUFF_TYPE_BDE_64;
19354         iocbq->iocb.un.xseq64.bdl.bdeSize = frame_len;
19355
19356         iocbq->context2 = pcmd;
19357         iocbq->vport = vport;
19358         iocbq->iocb_flag &= ~LPFC_FIP_ELS_ID_MASK;
19359         iocbq->iocb_flag |= LPFC_USE_FCPWQIDX;
19360
19361         /*
19362          * Setup rest of the iocb as though it were a WQE
19363          * Build the SEND_FRAME WQE
19364          */
19365         wqe = (union lpfc_wqe *)&iocbq->iocb;
19366
19367         wqe->send_frame.frame_len = frame_len;
19368         wqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((uint32_t *)fc_hdr));
19369         wqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((uint32_t *)fc_hdr + 1));
19370         wqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((uint32_t *)fc_hdr + 2));
19371         wqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((uint32_t *)fc_hdr + 3));
19372         wqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((uint32_t *)fc_hdr + 4));
19373         wqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((uint32_t *)fc_hdr + 5));
19374
19375         iocbq->iocb.ulpCommand = CMD_SEND_FRAME;
19376         iocbq->iocb.ulpLe = 1;
19377         iocbq->iocb_cmpl = lpfc_sli4_mds_loopback_cmpl;
19378         rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
19379         if (rc == IOCB_ERROR)
19380                 goto exit;
19381
19382         lpfc_in_buf_free(phba, &dmabuf->dbuf);
19383         return;
19384
19385 exit:
19386         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
19387                         "2023 Unable to process MDS loopback frame\n");
19388         if (pcmd && pcmd->virt)
19389                 dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19390         kfree(pcmd);
19391         if (iocbq)
19392                 lpfc_sli_release_iocbq(phba, iocbq);
19393         lpfc_in_buf_free(phba, &dmabuf->dbuf);
19394 }
19395
19396 /**
19397  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
19398  * @phba: Pointer to HBA context object.
19399  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
19400  *
19401  * This function is called with no lock held. This function processes all
19402  * the received buffers and gives it to upper layers when a received buffer
19403  * indicates that it is the final frame in the sequence. The interrupt
19404  * service routine processes received buffers at interrupt contexts.
19405  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
19406  * appropriate receive function when the final frame in a sequence is received.
19407  **/
19408 void
19409 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
19410                                  struct hbq_dmabuf *dmabuf)
19411 {
19412         struct hbq_dmabuf *seq_dmabuf;
19413         struct fc_frame_header *fc_hdr;
19414         struct lpfc_vport *vport;
19415         uint32_t fcfi;
19416         uint32_t did;
19417
19418         /* Process each received buffer */
19419         fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19420
19421         if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
19422             fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
19423                 vport = phba->pport;
19424                 /* Handle MDS Loopback frames */
19425                 if  (!(phba->pport->load_flag & FC_UNLOADING))
19426                         lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19427                 else
19428                         lpfc_in_buf_free(phba, &dmabuf->dbuf);
19429                 return;
19430         }
19431
19432         /* check to see if this a valid type of frame */
19433         if (lpfc_fc_frame_check(phba, fc_hdr)) {
19434                 lpfc_in_buf_free(phba, &dmabuf->dbuf);
19435                 return;
19436         }
19437
19438         if ((bf_get(lpfc_cqe_code,
19439                     &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
19440                 fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
19441                               &dmabuf->cq_event.cqe.rcqe_cmpl);
19442         else
19443                 fcfi = bf_get(lpfc_rcqe_fcf_id,
19444                               &dmabuf->cq_event.cqe.rcqe_cmpl);
19445
19446         if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
19447                 vport = phba->pport;
19448                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
19449                                 "2023 MDS Loopback %d bytes\n",
19450                                 bf_get(lpfc_rcqe_length,
19451                                        &dmabuf->cq_event.cqe.rcqe_cmpl));
19452                 /* Handle MDS Loopback frames */
19453                 lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19454                 return;
19455         }
19456
19457         /* d_id this frame is directed to */
19458         did = sli4_did_from_fc_hdr(fc_hdr);
19459
19460         vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
19461         if (!vport) {
19462                 /* throw out the frame */
19463                 lpfc_in_buf_free(phba, &dmabuf->dbuf);
19464                 return;
19465         }
19466
19467         /* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
19468         if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
19469                 (did != Fabric_DID)) {
19470                 /*
19471                  * Throw out the frame if we are not pt2pt.
19472                  * The pt2pt protocol allows for discovery frames
19473                  * to be received without a registered VPI.
19474                  */
19475                 if (!(vport->fc_flag & FC_PT2PT) ||
19476                         (phba->link_state == LPFC_HBA_READY)) {
19477                         lpfc_in_buf_free(phba, &dmabuf->dbuf);
19478                         return;
19479                 }
19480         }
19481
19482         /* Handle the basic abort sequence (BA_ABTS) event */
19483         if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
19484                 lpfc_sli4_handle_unsol_abort(vport, dmabuf);
19485                 return;
19486         }
19487
19488         /* Link this frame */
19489         seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
19490         if (!seq_dmabuf) {
19491                 /* unable to add frame to vport - throw it out */
19492                 lpfc_in_buf_free(phba, &dmabuf->dbuf);
19493                 return;
19494         }
19495         /* If not last frame in sequence continue processing frames. */
19496         if (!lpfc_seq_complete(seq_dmabuf))
19497                 return;
19498
19499         /* Send the complete sequence to the upper layer protocol */
19500         lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
19501 }
19502
19503 /**
19504  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
19505  * @phba: pointer to lpfc hba data structure.
19506  *
19507  * This routine is invoked to post rpi header templates to the
19508  * HBA consistent with the SLI-4 interface spec.  This routine
19509  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19510  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19511  *
19512  * This routine does not require any locks.  It's usage is expected
19513  * to be driver load or reset recovery when the driver is
19514  * sequential.
19515  *
19516  * Return codes
19517  *      0 - successful
19518  *      -EIO - The mailbox failed to complete successfully.
19519  *      When this error occurs, the driver is not guaranteed
19520  *      to have any rpi regions posted to the device and
19521  *      must either attempt to repost the regions or take a
19522  *      fatal error.
19523  **/
19524 int
19525 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
19526 {
19527         struct lpfc_rpi_hdr *rpi_page;
19528         uint32_t rc = 0;
19529         uint16_t lrpi = 0;
19530
19531         /* SLI4 ports that support extents do not require RPI headers. */
19532         if (!phba->sli4_hba.rpi_hdrs_in_use)
19533                 goto exit;
19534         if (phba->sli4_hba.extents_in_use)
19535                 return -EIO;
19536
19537         list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
19538                 /*
19539                  * Assign the rpi headers a physical rpi only if the driver
19540                  * has not initialized those resources.  A port reset only
19541                  * needs the headers posted.
19542                  */
19543                 if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
19544                     LPFC_RPI_RSRC_RDY)
19545                         rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19546
19547                 rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
19548                 if (rc != MBX_SUCCESS) {
19549                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19550                                         "2008 Error %d posting all rpi "
19551                                         "headers\n", rc);
19552                         rc = -EIO;
19553                         break;
19554                 }
19555         }
19556
19557  exit:
19558         bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
19559                LPFC_RPI_RSRC_RDY);
19560         return rc;
19561 }
19562
19563 /**
19564  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
19565  * @phba: pointer to lpfc hba data structure.
19566  * @rpi_page:  pointer to the rpi memory region.
19567  *
19568  * This routine is invoked to post a single rpi header to the
19569  * HBA consistent with the SLI-4 interface spec.  This memory region
19570  * maps up to 64 rpi context regions.
19571  *
19572  * Return codes
19573  *      0 - successful
19574  *      -ENOMEM - No available memory
19575  *      -EIO - The mailbox failed to complete successfully.
19576  **/
19577 int
19578 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
19579 {
19580         LPFC_MBOXQ_t *mboxq;
19581         struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
19582         uint32_t rc = 0;
19583         uint32_t shdr_status, shdr_add_status;
19584         union lpfc_sli4_cfg_shdr *shdr;
19585
19586         /* SLI4 ports that support extents do not require RPI headers. */
19587         if (!phba->sli4_hba.rpi_hdrs_in_use)
19588                 return rc;
19589         if (phba->sli4_hba.extents_in_use)
19590                 return -EIO;
19591
19592         /* The port is notified of the header region via a mailbox command. */
19593         mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19594         if (!mboxq) {
19595                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19596                                 "2001 Unable to allocate memory for issuing "
19597                                 "SLI_CONFIG_SPECIAL mailbox command\n");
19598                 return -ENOMEM;
19599         }
19600
19601         /* Post all rpi memory regions to the port. */
19602         hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
19603         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19604                          LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
19605                          sizeof(struct lpfc_mbx_post_hdr_tmpl) -
19606                          sizeof(struct lpfc_sli4_cfg_mhdr),
19607                          LPFC_SLI4_MBX_EMBED);
19608
19609
19610         /* Post the physical rpi to the port for this rpi header. */
19611         bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
19612                rpi_page->start_rpi);
19613         bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
19614                hdr_tmpl, rpi_page->page_count);
19615
19616         hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
19617         hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
19618         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19619         shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
19620         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19621         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19622         mempool_free(mboxq, phba->mbox_mem_pool);
19623         if (shdr_status || shdr_add_status || rc) {
19624                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19625                                 "2514 POST_RPI_HDR mailbox failed with "
19626                                 "status x%x add_status x%x, mbx status x%x\n",
19627                                 shdr_status, shdr_add_status, rc);
19628                 rc = -ENXIO;
19629         } else {
19630                 /*
19631                  * The next_rpi stores the next logical module-64 rpi value used
19632                  * to post physical rpis in subsequent rpi postings.
19633                  */
19634                 spin_lock_irq(&phba->hbalock);
19635                 phba->sli4_hba.next_rpi = rpi_page->next_rpi;
19636                 spin_unlock_irq(&phba->hbalock);
19637         }
19638         return rc;
19639 }
19640
19641 /**
19642  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
19643  * @phba: pointer to lpfc hba data structure.
19644  *
19645  * This routine is invoked to post rpi header templates to the
19646  * HBA consistent with the SLI-4 interface spec.  This routine
19647  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19648  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19649  *
19650  * Returns
19651  *      A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
19652  *      LPFC_RPI_ALLOC_ERROR if no rpis are available.
19653  **/
19654 int
19655 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
19656 {
19657         unsigned long rpi;
19658         uint16_t max_rpi, rpi_limit;
19659         uint16_t rpi_remaining, lrpi = 0;
19660         struct lpfc_rpi_hdr *rpi_hdr;
19661         unsigned long iflag;
19662
19663         /*
19664          * Fetch the next logical rpi.  Because this index is logical,
19665          * the  driver starts at 0 each time.
19666          */
19667         spin_lock_irqsave(&phba->hbalock, iflag);
19668         max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
19669         rpi_limit = phba->sli4_hba.next_rpi;
19670
19671         rpi = find_next_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit, 0);
19672         if (rpi >= rpi_limit)
19673                 rpi = LPFC_RPI_ALLOC_ERROR;
19674         else {
19675                 set_bit(rpi, phba->sli4_hba.rpi_bmask);
19676                 phba->sli4_hba.max_cfg_param.rpi_used++;
19677                 phba->sli4_hba.rpi_count++;
19678         }
19679         lpfc_printf_log(phba, KERN_INFO,
19680                         LOG_NODE | LOG_DISCOVERY,
19681                         "0001 Allocated rpi:x%x max:x%x lim:x%x\n",
19682                         (int) rpi, max_rpi, rpi_limit);
19683
19684         /*
19685          * Don't try to allocate more rpi header regions if the device limit
19686          * has been exhausted.
19687          */
19688         if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
19689             (phba->sli4_hba.rpi_count >= max_rpi)) {
19690                 spin_unlock_irqrestore(&phba->hbalock, iflag);
19691                 return rpi;
19692         }
19693
19694         /*
19695          * RPI header postings are not required for SLI4 ports capable of
19696          * extents.
19697          */
19698         if (!phba->sli4_hba.rpi_hdrs_in_use) {
19699                 spin_unlock_irqrestore(&phba->hbalock, iflag);
19700                 return rpi;
19701         }
19702
19703         /*
19704          * If the driver is running low on rpi resources, allocate another
19705          * page now.  Note that the next_rpi value is used because
19706          * it represents how many are actually in use whereas max_rpi notes
19707          * how many are supported max by the device.
19708          */
19709         rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
19710         spin_unlock_irqrestore(&phba->hbalock, iflag);
19711         if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
19712                 rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
19713                 if (!rpi_hdr) {
19714                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19715                                         "2002 Error Could not grow rpi "
19716                                         "count\n");
19717                 } else {
19718                         lrpi = rpi_hdr->start_rpi;
19719                         rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19720                         lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
19721                 }
19722         }
19723
19724         return rpi;
19725 }
19726
19727 /**
19728  * __lpfc_sli4_free_rpi - Release an rpi for reuse.
19729  * @phba: pointer to lpfc hba data structure.
19730  * @rpi: rpi to free
19731  *
19732  * This routine is invoked to release an rpi to the pool of
19733  * available rpis maintained by the driver.
19734  **/
19735 static void
19736 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19737 {
19738         /*
19739          * if the rpi value indicates a prior unreg has already
19740          * been done, skip the unreg.
19741          */
19742         if (rpi == LPFC_RPI_ALLOC_ERROR)
19743                 return;
19744
19745         if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
19746                 phba->sli4_hba.rpi_count--;
19747                 phba->sli4_hba.max_cfg_param.rpi_used--;
19748         } else {
19749                 lpfc_printf_log(phba, KERN_INFO,
19750                                 LOG_NODE | LOG_DISCOVERY,
19751                                 "2016 rpi %x not inuse\n",
19752                                 rpi);
19753         }
19754 }
19755
19756 /**
19757  * lpfc_sli4_free_rpi - Release an rpi for reuse.
19758  * @phba: pointer to lpfc hba data structure.
19759  * @rpi: rpi to free
19760  *
19761  * This routine is invoked to release an rpi to the pool of
19762  * available rpis maintained by the driver.
19763  **/
19764 void
19765 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19766 {
19767         spin_lock_irq(&phba->hbalock);
19768         __lpfc_sli4_free_rpi(phba, rpi);
19769         spin_unlock_irq(&phba->hbalock);
19770 }
19771
19772 /**
19773  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
19774  * @phba: pointer to lpfc hba data structure.
19775  *
19776  * This routine is invoked to remove the memory region that
19777  * provided rpi via a bitmask.
19778  **/
19779 void
19780 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
19781 {
19782         kfree(phba->sli4_hba.rpi_bmask);
19783         kfree(phba->sli4_hba.rpi_ids);
19784         bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
19785 }
19786
19787 /**
19788  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
19789  * @ndlp: pointer to lpfc nodelist data structure.
19790  * @cmpl: completion call-back.
19791  * @arg: data to load as MBox 'caller buffer information'
19792  *
19793  * This routine is invoked to remove the memory region that
19794  * provided rpi via a bitmask.
19795  **/
19796 int
19797 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
19798         void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *), void *arg)
19799 {
19800         LPFC_MBOXQ_t *mboxq;
19801         struct lpfc_hba *phba = ndlp->phba;
19802         int rc;
19803
19804         /* The port is notified of the header region via a mailbox command. */
19805         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19806         if (!mboxq)
19807                 return -ENOMEM;
19808
19809         /* If cmpl assigned, then this nlp_get pairs with
19810          * lpfc_mbx_cmpl_resume_rpi.
19811          *
19812          * Else cmpl is NULL, then this nlp_get pairs with
19813          * lpfc_sli_def_mbox_cmpl.
19814          */
19815         if (!lpfc_nlp_get(ndlp)) {
19816                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19817                                 "2122 %s: Failed to get nlp ref\n",
19818                                 __func__);
19819                 mempool_free(mboxq, phba->mbox_mem_pool);
19820                 return -EIO;
19821         }
19822
19823         /* Post all rpi memory regions to the port. */
19824         lpfc_resume_rpi(mboxq, ndlp);
19825         if (cmpl) {
19826                 mboxq->mbox_cmpl = cmpl;
19827                 mboxq->ctx_buf = arg;
19828         } else
19829                 mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19830         mboxq->ctx_ndlp = ndlp;
19831         mboxq->vport = ndlp->vport;
19832         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19833         if (rc == MBX_NOT_FINISHED) {
19834                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19835                                 "2010 Resume RPI Mailbox failed "
19836                                 "status %d, mbxStatus x%x\n", rc,
19837                                 bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19838                 lpfc_nlp_put(ndlp);
19839                 mempool_free(mboxq, phba->mbox_mem_pool);
19840                 return -EIO;
19841         }
19842         return 0;
19843 }
19844
19845 /**
19846  * lpfc_sli4_init_vpi - Initialize a vpi with the port
19847  * @vport: Pointer to the vport for which the vpi is being initialized
19848  *
19849  * This routine is invoked to activate a vpi with the port.
19850  *
19851  * Returns:
19852  *    0 success
19853  *    -Evalue otherwise
19854  **/
19855 int
19856 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
19857 {
19858         LPFC_MBOXQ_t *mboxq;
19859         int rc = 0;
19860         int retval = MBX_SUCCESS;
19861         uint32_t mbox_tmo;
19862         struct lpfc_hba *phba = vport->phba;
19863         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19864         if (!mboxq)
19865                 return -ENOMEM;
19866         lpfc_init_vpi(phba, mboxq, vport->vpi);
19867         mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
19868         rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
19869         if (rc != MBX_SUCCESS) {
19870                 lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19871                                 "2022 INIT VPI Mailbox failed "
19872                                 "status %d, mbxStatus x%x\n", rc,
19873                                 bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19874                 retval = -EIO;
19875         }
19876         if (rc != MBX_TIMEOUT)
19877                 mempool_free(mboxq, vport->phba->mbox_mem_pool);
19878
19879         return retval;
19880 }
19881
19882 /**
19883  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
19884  * @phba: pointer to lpfc hba data structure.
19885  * @mboxq: Pointer to mailbox object.
19886  *
19887  * This routine is invoked to manually add a single FCF record. The caller
19888  * must pass a completely initialized FCF_Record.  This routine takes
19889  * care of the nonembedded mailbox operations.
19890  **/
19891 static void
19892 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
19893 {
19894         void *virt_addr;
19895         union lpfc_sli4_cfg_shdr *shdr;
19896         uint32_t shdr_status, shdr_add_status;
19897
19898         virt_addr = mboxq->sge_array->addr[0];
19899         /* The IOCTL status is embedded in the mailbox subheader. */
19900         shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
19901         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19902         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19903
19904         if ((shdr_status || shdr_add_status) &&
19905                 (shdr_status != STATUS_FCF_IN_USE))
19906                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19907                         "2558 ADD_FCF_RECORD mailbox failed with "
19908                         "status x%x add_status x%x\n",
19909                         shdr_status, shdr_add_status);
19910
19911         lpfc_sli4_mbox_cmd_free(phba, mboxq);
19912 }
19913
19914 /**
19915  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
19916  * @phba: pointer to lpfc hba data structure.
19917  * @fcf_record:  pointer to the initialized fcf record to add.
19918  *
19919  * This routine is invoked to manually add a single FCF record. The caller
19920  * must pass a completely initialized FCF_Record.  This routine takes
19921  * care of the nonembedded mailbox operations.
19922  **/
19923 int
19924 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
19925 {
19926         int rc = 0;
19927         LPFC_MBOXQ_t *mboxq;
19928         uint8_t *bytep;
19929         void *virt_addr;
19930         struct lpfc_mbx_sge sge;
19931         uint32_t alloc_len, req_len;
19932         uint32_t fcfindex;
19933
19934         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19935         if (!mboxq) {
19936                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19937                         "2009 Failed to allocate mbox for ADD_FCF cmd\n");
19938                 return -ENOMEM;
19939         }
19940
19941         req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
19942                   sizeof(uint32_t);
19943
19944         /* Allocate DMA memory and set up the non-embedded mailbox command */
19945         alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19946                                      LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
19947                                      req_len, LPFC_SLI4_MBX_NEMBED);
19948         if (alloc_len < req_len) {
19949                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19950                         "2523 Allocated DMA memory size (x%x) is "
19951                         "less than the requested DMA memory "
19952                         "size (x%x)\n", alloc_len, req_len);
19953                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
19954                 return -ENOMEM;
19955         }
19956
19957         /*
19958          * Get the first SGE entry from the non-embedded DMA memory.  This
19959          * routine only uses a single SGE.
19960          */
19961         lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
19962         virt_addr = mboxq->sge_array->addr[0];
19963         /*
19964          * Configure the FCF record for FCFI 0.  This is the driver's
19965          * hardcoded default and gets used in nonFIP mode.
19966          */
19967         fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
19968         bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
19969         lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
19970
19971         /*
19972          * Copy the fcf_index and the FCF Record Data. The data starts after
19973          * the FCoE header plus word10. The data copy needs to be endian
19974          * correct.
19975          */
19976         bytep += sizeof(uint32_t);
19977         lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
19978         mboxq->vport = phba->pport;
19979         mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
19980         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19981         if (rc == MBX_NOT_FINISHED) {
19982                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19983                         "2515 ADD_FCF_RECORD mailbox failed with "
19984                         "status 0x%x\n", rc);
19985                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
19986                 rc = -EIO;
19987         } else
19988                 rc = 0;
19989
19990         return rc;
19991 }
19992
19993 /**
19994  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
19995  * @phba: pointer to lpfc hba data structure.
19996  * @fcf_record:  pointer to the fcf record to write the default data.
19997  * @fcf_index: FCF table entry index.
19998  *
19999  * This routine is invoked to build the driver's default FCF record.  The
20000  * values used are hardcoded.  This routine handles memory initialization.
20001  *
20002  **/
20003 void
20004 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
20005                                 struct fcf_record *fcf_record,
20006                                 uint16_t fcf_index)
20007 {
20008         memset(fcf_record, 0, sizeof(struct fcf_record));
20009         fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
20010         fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
20011         fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
20012         bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
20013         bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
20014         bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
20015         bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
20016         bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
20017         bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
20018         bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
20019         bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
20020         bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
20021         bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
20022         bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
20023         bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
20024         bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
20025                 LPFC_FCF_FPMA | LPFC_FCF_SPMA);
20026         /* Set the VLAN bit map */
20027         if (phba->valid_vlan) {
20028                 fcf_record->vlan_bitmap[phba->vlan_id / 8]
20029                         = 1 << (phba->vlan_id % 8);
20030         }
20031 }
20032
20033 /**
20034  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
20035  * @phba: pointer to lpfc hba data structure.
20036  * @fcf_index: FCF table entry offset.
20037  *
20038  * This routine is invoked to scan the entire FCF table by reading FCF
20039  * record and processing it one at a time starting from the @fcf_index
20040  * for initial FCF discovery or fast FCF failover rediscovery.
20041  *
20042  * Return 0 if the mailbox command is submitted successfully, none 0
20043  * otherwise.
20044  **/
20045 int
20046 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20047 {
20048         int rc = 0, error;
20049         LPFC_MBOXQ_t *mboxq;
20050
20051         phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
20052         phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
20053         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20054         if (!mboxq) {
20055                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20056                                 "2000 Failed to allocate mbox for "
20057                                 "READ_FCF cmd\n");
20058                 error = -ENOMEM;
20059                 goto fail_fcf_scan;
20060         }
20061         /* Construct the read FCF record mailbox command */
20062         rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20063         if (rc) {
20064                 error = -EINVAL;
20065                 goto fail_fcf_scan;
20066         }
20067         /* Issue the mailbox command asynchronously */
20068         mboxq->vport = phba->pport;
20069         mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
20070
20071         spin_lock_irq(&phba->hbalock);
20072         phba->hba_flag |= FCF_TS_INPROG;
20073         spin_unlock_irq(&phba->hbalock);
20074
20075         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20076         if (rc == MBX_NOT_FINISHED)
20077                 error = -EIO;
20078         else {
20079                 /* Reset eligible FCF count for new scan */
20080                 if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
20081                         phba->fcf.eligible_fcf_cnt = 0;
20082                 error = 0;
20083         }
20084 fail_fcf_scan:
20085         if (error) {
20086                 if (mboxq)
20087                         lpfc_sli4_mbox_cmd_free(phba, mboxq);
20088                 /* FCF scan failed, clear FCF_TS_INPROG flag */
20089                 spin_lock_irq(&phba->hbalock);
20090                 phba->hba_flag &= ~FCF_TS_INPROG;
20091                 spin_unlock_irq(&phba->hbalock);
20092         }
20093         return error;
20094 }
20095
20096 /**
20097  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
20098  * @phba: pointer to lpfc hba data structure.
20099  * @fcf_index: FCF table entry offset.
20100  *
20101  * This routine is invoked to read an FCF record indicated by @fcf_index
20102  * and to use it for FLOGI roundrobin FCF failover.
20103  *
20104  * Return 0 if the mailbox command is submitted successfully, none 0
20105  * otherwise.
20106  **/
20107 int
20108 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20109 {
20110         int rc = 0, error;
20111         LPFC_MBOXQ_t *mboxq;
20112
20113         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20114         if (!mboxq) {
20115                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20116                                 "2763 Failed to allocate mbox for "
20117                                 "READ_FCF cmd\n");
20118                 error = -ENOMEM;
20119                 goto fail_fcf_read;
20120         }
20121         /* Construct the read FCF record mailbox command */
20122         rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20123         if (rc) {
20124                 error = -EINVAL;
20125                 goto fail_fcf_read;
20126         }
20127         /* Issue the mailbox command asynchronously */
20128         mboxq->vport = phba->pport;
20129         mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
20130         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20131         if (rc == MBX_NOT_FINISHED)
20132                 error = -EIO;
20133         else
20134                 error = 0;
20135
20136 fail_fcf_read:
20137         if (error && mboxq)
20138                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
20139         return error;
20140 }
20141
20142 /**
20143  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
20144  * @phba: pointer to lpfc hba data structure.
20145  * @fcf_index: FCF table entry offset.
20146  *
20147  * This routine is invoked to read an FCF record indicated by @fcf_index to
20148  * determine whether it's eligible for FLOGI roundrobin failover list.
20149  *
20150  * Return 0 if the mailbox command is submitted successfully, none 0
20151  * otherwise.
20152  **/
20153 int
20154 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20155 {
20156         int rc = 0, error;
20157         LPFC_MBOXQ_t *mboxq;
20158
20159         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20160         if (!mboxq) {
20161                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20162                                 "2758 Failed to allocate mbox for "
20163                                 "READ_FCF cmd\n");
20164                                 error = -ENOMEM;
20165                                 goto fail_fcf_read;
20166         }
20167         /* Construct the read FCF record mailbox command */
20168         rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20169         if (rc) {
20170                 error = -EINVAL;
20171                 goto fail_fcf_read;
20172         }
20173         /* Issue the mailbox command asynchronously */
20174         mboxq->vport = phba->pport;
20175         mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
20176         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20177         if (rc == MBX_NOT_FINISHED)
20178                 error = -EIO;
20179         else
20180                 error = 0;
20181
20182 fail_fcf_read:
20183         if (error && mboxq)
20184                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
20185         return error;
20186 }
20187
20188 /**
20189  * lpfc_check_next_fcf_pri_level
20190  * @phba: pointer to the lpfc_hba struct for this port.
20191  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
20192  * routine when the rr_bmask is empty. The FCF indecies are put into the
20193  * rr_bmask based on their priority level. Starting from the highest priority
20194  * to the lowest. The most likely FCF candidate will be in the highest
20195  * priority group. When this routine is called it searches the fcf_pri list for
20196  * next lowest priority group and repopulates the rr_bmask with only those
20197  * fcf_indexes.
20198  * returns:
20199  * 1=success 0=failure
20200  **/
20201 static int
20202 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
20203 {
20204         uint16_t next_fcf_pri;
20205         uint16_t last_index;
20206         struct lpfc_fcf_pri *fcf_pri;
20207         int rc;
20208         int ret = 0;
20209
20210         last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20211                         LPFC_SLI4_FCF_TBL_INDX_MAX);
20212         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20213                         "3060 Last IDX %d\n", last_index);
20214
20215         /* Verify the priority list has 2 or more entries */
20216         spin_lock_irq(&phba->hbalock);
20217         if (list_empty(&phba->fcf.fcf_pri_list) ||
20218             list_is_singular(&phba->fcf.fcf_pri_list)) {
20219                 spin_unlock_irq(&phba->hbalock);
20220                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20221                         "3061 Last IDX %d\n", last_index);
20222                 return 0; /* Empty rr list */
20223         }
20224         spin_unlock_irq(&phba->hbalock);
20225
20226         next_fcf_pri = 0;
20227         /*
20228          * Clear the rr_bmask and set all of the bits that are at this
20229          * priority.
20230          */
20231         memset(phba->fcf.fcf_rr_bmask, 0,
20232                         sizeof(*phba->fcf.fcf_rr_bmask));
20233         spin_lock_irq(&phba->hbalock);
20234         list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20235                 if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
20236                         continue;
20237                 /*
20238                  * the 1st priority that has not FLOGI failed
20239                  * will be the highest.
20240                  */
20241                 if (!next_fcf_pri)
20242                         next_fcf_pri = fcf_pri->fcf_rec.priority;
20243                 spin_unlock_irq(&phba->hbalock);
20244                 if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20245                         rc = lpfc_sli4_fcf_rr_index_set(phba,
20246                                                 fcf_pri->fcf_rec.fcf_index);
20247                         if (rc)
20248                                 return 0;
20249                 }
20250                 spin_lock_irq(&phba->hbalock);
20251         }
20252         /*
20253          * if next_fcf_pri was not set above and the list is not empty then
20254          * we have failed flogis on all of them. So reset flogi failed
20255          * and start at the beginning.
20256          */
20257         if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
20258                 list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20259                         fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
20260                         /*
20261                          * the 1st priority that has not FLOGI failed
20262                          * will be the highest.
20263                          */
20264                         if (!next_fcf_pri)
20265                                 next_fcf_pri = fcf_pri->fcf_rec.priority;
20266                         spin_unlock_irq(&phba->hbalock);
20267                         if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20268                                 rc = lpfc_sli4_fcf_rr_index_set(phba,
20269                                                 fcf_pri->fcf_rec.fcf_index);
20270                                 if (rc)
20271                                         return 0;
20272                         }
20273                         spin_lock_irq(&phba->hbalock);
20274                 }
20275         } else
20276                 ret = 1;
20277         spin_unlock_irq(&phba->hbalock);
20278
20279         return ret;
20280 }
20281 /**
20282  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
20283  * @phba: pointer to lpfc hba data structure.
20284  *
20285  * This routine is to get the next eligible FCF record index in a round
20286  * robin fashion. If the next eligible FCF record index equals to the
20287  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
20288  * shall be returned, otherwise, the next eligible FCF record's index
20289  * shall be returned.
20290  **/
20291 uint16_t
20292 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
20293 {
20294         uint16_t next_fcf_index;
20295
20296 initial_priority:
20297         /* Search start from next bit of currently registered FCF index */
20298         next_fcf_index = phba->fcf.current_rec.fcf_indx;
20299
20300 next_priority:
20301         /* Determine the next fcf index to check */
20302         next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
20303         next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
20304                                        LPFC_SLI4_FCF_TBL_INDX_MAX,
20305                                        next_fcf_index);
20306
20307         /* Wrap around condition on phba->fcf.fcf_rr_bmask */
20308         if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20309                 /*
20310                  * If we have wrapped then we need to clear the bits that
20311                  * have been tested so that we can detect when we should
20312                  * change the priority level.
20313                  */
20314                 next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
20315                                                LPFC_SLI4_FCF_TBL_INDX_MAX, 0);
20316         }
20317
20318
20319         /* Check roundrobin failover list empty condition */
20320         if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
20321                 next_fcf_index == phba->fcf.current_rec.fcf_indx) {
20322                 /*
20323                  * If next fcf index is not found check if there are lower
20324                  * Priority level fcf's in the fcf_priority list.
20325                  * Set up the rr_bmask with all of the avaiable fcf bits
20326                  * at that level and continue the selection process.
20327                  */
20328                 if (lpfc_check_next_fcf_pri_level(phba))
20329                         goto initial_priority;
20330                 lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
20331                                 "2844 No roundrobin failover FCF available\n");
20332
20333                 return LPFC_FCOE_FCF_NEXT_NONE;
20334         }
20335
20336         if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
20337                 phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
20338                 LPFC_FCF_FLOGI_FAILED) {
20339                 if (list_is_singular(&phba->fcf.fcf_pri_list))
20340                         return LPFC_FCOE_FCF_NEXT_NONE;
20341
20342                 goto next_priority;
20343         }
20344
20345         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20346                         "2845 Get next roundrobin failover FCF (x%x)\n",
20347                         next_fcf_index);
20348
20349         return next_fcf_index;
20350 }
20351
20352 /**
20353  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
20354  * @phba: pointer to lpfc hba data structure.
20355  * @fcf_index: index into the FCF table to 'set'
20356  *
20357  * This routine sets the FCF record index in to the eligible bmask for
20358  * roundrobin failover search. It checks to make sure that the index
20359  * does not go beyond the range of the driver allocated bmask dimension
20360  * before setting the bit.
20361  *
20362  * Returns 0 if the index bit successfully set, otherwise, it returns
20363  * -EINVAL.
20364  **/
20365 int
20366 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
20367 {
20368         if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20369                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20370                                 "2610 FCF (x%x) reached driver's book "
20371                                 "keeping dimension:x%x\n",
20372                                 fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20373                 return -EINVAL;
20374         }
20375         /* Set the eligible FCF record index bmask */
20376         set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20377
20378         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20379                         "2790 Set FCF (x%x) to roundrobin FCF failover "
20380                         "bmask\n", fcf_index);
20381
20382         return 0;
20383 }
20384
20385 /**
20386  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
20387  * @phba: pointer to lpfc hba data structure.
20388  * @fcf_index: index into the FCF table to 'clear'
20389  *
20390  * This routine clears the FCF record index from the eligible bmask for
20391  * roundrobin failover search. It checks to make sure that the index
20392  * does not go beyond the range of the driver allocated bmask dimension
20393  * before clearing the bit.
20394  **/
20395 void
20396 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
20397 {
20398         struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
20399         if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20400                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20401                                 "2762 FCF (x%x) reached driver's book "
20402                                 "keeping dimension:x%x\n",
20403                                 fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20404                 return;
20405         }
20406         /* Clear the eligible FCF record index bmask */
20407         spin_lock_irq(&phba->hbalock);
20408         list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
20409                                  list) {
20410                 if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
20411                         list_del_init(&fcf_pri->list);
20412                         break;
20413                 }
20414         }
20415         spin_unlock_irq(&phba->hbalock);
20416         clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20417
20418         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20419                         "2791 Clear FCF (x%x) from roundrobin failover "
20420                         "bmask\n", fcf_index);
20421 }
20422
20423 /**
20424  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
20425  * @phba: pointer to lpfc hba data structure.
20426  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
20427  *
20428  * This routine is the completion routine for the rediscover FCF table mailbox
20429  * command. If the mailbox command returned failure, it will try to stop the
20430  * FCF rediscover wait timer.
20431  **/
20432 static void
20433 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
20434 {
20435         struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20436         uint32_t shdr_status, shdr_add_status;
20437
20438         redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20439
20440         shdr_status = bf_get(lpfc_mbox_hdr_status,
20441                              &redisc_fcf->header.cfg_shdr.response);
20442         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20443                              &redisc_fcf->header.cfg_shdr.response);
20444         if (shdr_status || shdr_add_status) {
20445                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20446                                 "2746 Requesting for FCF rediscovery failed "
20447                                 "status x%x add_status x%x\n",
20448                                 shdr_status, shdr_add_status);
20449                 if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
20450                         spin_lock_irq(&phba->hbalock);
20451                         phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
20452                         spin_unlock_irq(&phba->hbalock);
20453                         /*
20454                          * CVL event triggered FCF rediscover request failed,
20455                          * last resort to re-try current registered FCF entry.
20456                          */
20457                         lpfc_retry_pport_discovery(phba);
20458                 } else {
20459                         spin_lock_irq(&phba->hbalock);
20460                         phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
20461                         spin_unlock_irq(&phba->hbalock);
20462                         /*
20463                          * DEAD FCF event triggered FCF rediscover request
20464                          * failed, last resort to fail over as a link down
20465                          * to FCF registration.
20466                          */
20467                         lpfc_sli4_fcf_dead_failthrough(phba);
20468                 }
20469         } else {
20470                 lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20471                                 "2775 Start FCF rediscover quiescent timer\n");
20472                 /*
20473                  * Start FCF rediscovery wait timer for pending FCF
20474                  * before rescan FCF record table.
20475                  */
20476                 lpfc_fcf_redisc_wait_start_timer(phba);
20477         }
20478
20479         mempool_free(mbox, phba->mbox_mem_pool);
20480 }
20481
20482 /**
20483  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
20484  * @phba: pointer to lpfc hba data structure.
20485  *
20486  * This routine is invoked to request for rediscovery of the entire FCF table
20487  * by the port.
20488  **/
20489 int
20490 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
20491 {
20492         LPFC_MBOXQ_t *mbox;
20493         struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20494         int rc, length;
20495
20496         /* Cancel retry delay timers to all vports before FCF rediscover */
20497         lpfc_cancel_all_vport_retry_delay_timer(phba);
20498
20499         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20500         if (!mbox) {
20501                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20502                                 "2745 Failed to allocate mbox for "
20503                                 "requesting FCF rediscover.\n");
20504                 return -ENOMEM;
20505         }
20506
20507         length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
20508                   sizeof(struct lpfc_sli4_cfg_mhdr));
20509         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
20510                          LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
20511                          length, LPFC_SLI4_MBX_EMBED);
20512
20513         redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20514         /* Set count to 0 for invalidating the entire FCF database */
20515         bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
20516
20517         /* Issue the mailbox command asynchronously */
20518         mbox->vport = phba->pport;
20519         mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
20520         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
20521
20522         if (rc == MBX_NOT_FINISHED) {
20523                 mempool_free(mbox, phba->mbox_mem_pool);
20524                 return -EIO;
20525         }
20526         return 0;
20527 }
20528
20529 /**
20530  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
20531  * @phba: pointer to lpfc hba data structure.
20532  *
20533  * This function is the failover routine as a last resort to the FCF DEAD
20534  * event when driver failed to perform fast FCF failover.
20535  **/
20536 void
20537 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
20538 {
20539         uint32_t link_state;
20540
20541         /*
20542          * Last resort as FCF DEAD event failover will treat this as
20543          * a link down, but save the link state because we don't want
20544          * it to be changed to Link Down unless it is already down.
20545          */
20546         link_state = phba->link_state;
20547         lpfc_linkdown(phba);
20548         phba->link_state = link_state;
20549
20550         /* Unregister FCF if no devices connected to it */
20551         lpfc_unregister_unused_fcf(phba);
20552 }
20553
20554 /**
20555  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
20556  * @phba: pointer to lpfc hba data structure.
20557  * @rgn23_data: pointer to configure region 23 data.
20558  *
20559  * This function gets SLI3 port configure region 23 data through memory dump
20560  * mailbox command. When it successfully retrieves data, the size of the data
20561  * will be returned, otherwise, 0 will be returned.
20562  **/
20563 static uint32_t
20564 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20565 {
20566         LPFC_MBOXQ_t *pmb = NULL;
20567         MAILBOX_t *mb;
20568         uint32_t offset = 0;
20569         int rc;
20570
20571         if (!rgn23_data)
20572                 return 0;
20573
20574         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20575         if (!pmb) {
20576                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20577                                 "2600 failed to allocate mailbox memory\n");
20578                 return 0;
20579         }
20580         mb = &pmb->u.mb;
20581
20582         do {
20583                 lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
20584                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
20585
20586                 if (rc != MBX_SUCCESS) {
20587                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20588                                         "2601 failed to read config "
20589                                         "region 23, rc 0x%x Status 0x%x\n",
20590                                         rc, mb->mbxStatus);
20591                         mb->un.varDmp.word_cnt = 0;
20592                 }
20593                 /*
20594                  * dump mem may return a zero when finished or we got a
20595                  * mailbox error, either way we are done.
20596                  */
20597                 if (mb->un.varDmp.word_cnt == 0)
20598                         break;
20599
20600                 if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
20601                         mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
20602
20603                 lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
20604                                        rgn23_data + offset,
20605                                        mb->un.varDmp.word_cnt);
20606                 offset += mb->un.varDmp.word_cnt;
20607         } while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
20608
20609         mempool_free(pmb, phba->mbox_mem_pool);
20610         return offset;
20611 }
20612
20613 /**
20614  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
20615  * @phba: pointer to lpfc hba data structure.
20616  * @rgn23_data: pointer to configure region 23 data.
20617  *
20618  * This function gets SLI4 port configure region 23 data through memory dump
20619  * mailbox command. When it successfully retrieves data, the size of the data
20620  * will be returned, otherwise, 0 will be returned.
20621  **/
20622 static uint32_t
20623 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20624 {
20625         LPFC_MBOXQ_t *mboxq = NULL;
20626         struct lpfc_dmabuf *mp = NULL;
20627         struct lpfc_mqe *mqe;
20628         uint32_t data_length = 0;
20629         int rc;
20630
20631         if (!rgn23_data)
20632                 return 0;
20633
20634         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20635         if (!mboxq) {
20636                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20637                                 "3105 failed to allocate mailbox memory\n");
20638                 return 0;
20639         }
20640
20641         if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
20642                 goto out;
20643         mqe = &mboxq->u.mqe;
20644         mp = (struct lpfc_dmabuf *)mboxq->ctx_buf;
20645         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
20646         if (rc)
20647                 goto out;
20648         data_length = mqe->un.mb_words[5];
20649         if (data_length == 0)
20650                 goto out;
20651         if (data_length > DMP_RGN23_SIZE) {
20652                 data_length = 0;
20653                 goto out;
20654         }
20655         lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
20656 out:
20657         mempool_free(mboxq, phba->mbox_mem_pool);
20658         if (mp) {
20659                 lpfc_mbuf_free(phba, mp->virt, mp->phys);
20660                 kfree(mp);
20661         }
20662         return data_length;
20663 }
20664
20665 /**
20666  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
20667  * @phba: pointer to lpfc hba data structure.
20668  *
20669  * This function read region 23 and parse TLV for port status to
20670  * decide if the user disaled the port. If the TLV indicates the
20671  * port is disabled, the hba_flag is set accordingly.
20672  **/
20673 void
20674 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
20675 {
20676         uint8_t *rgn23_data = NULL;
20677         uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
20678         uint32_t offset = 0;
20679
20680         /* Get adapter Region 23 data */
20681         rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
20682         if (!rgn23_data)
20683                 goto out;
20684
20685         if (phba->sli_rev < LPFC_SLI_REV4)
20686                 data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
20687         else {
20688                 if_type = bf_get(lpfc_sli_intf_if_type,
20689                                  &phba->sli4_hba.sli_intf);
20690                 if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
20691                         goto out;
20692                 data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
20693         }
20694
20695         if (!data_size)
20696                 goto out;
20697
20698         /* Check the region signature first */
20699         if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
20700                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20701                         "2619 Config region 23 has bad signature\n");
20702                         goto out;
20703         }
20704         offset += 4;
20705
20706         /* Check the data structure version */
20707         if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
20708                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20709                         "2620 Config region 23 has bad version\n");
20710                 goto out;
20711         }
20712         offset += 4;
20713
20714         /* Parse TLV entries in the region */
20715         while (offset < data_size) {
20716                 if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
20717                         break;
20718                 /*
20719                  * If the TLV is not driver specific TLV or driver id is
20720                  * not linux driver id, skip the record.
20721                  */
20722                 if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
20723                     (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
20724                     (rgn23_data[offset + 3] != 0)) {
20725                         offset += rgn23_data[offset + 1] * 4 + 4;
20726                         continue;
20727                 }
20728
20729                 /* Driver found a driver specific TLV in the config region */
20730                 sub_tlv_len = rgn23_data[offset + 1] * 4;
20731                 offset += 4;
20732                 tlv_offset = 0;
20733
20734                 /*
20735                  * Search for configured port state sub-TLV.
20736                  */
20737                 while ((offset < data_size) &&
20738                         (tlv_offset < sub_tlv_len)) {
20739                         if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
20740                                 offset += 4;
20741                                 tlv_offset += 4;
20742                                 break;
20743                         }
20744                         if (rgn23_data[offset] != PORT_STE_TYPE) {
20745                                 offset += rgn23_data[offset + 1] * 4 + 4;
20746                                 tlv_offset += rgn23_data[offset + 1] * 4 + 4;
20747                                 continue;
20748                         }
20749
20750                         /* This HBA contains PORT_STE configured */
20751                         if (!rgn23_data[offset + 2])
20752                                 phba->hba_flag |= LINK_DISABLED;
20753
20754                         goto out;
20755                 }
20756         }
20757
20758 out:
20759         kfree(rgn23_data);
20760         return;
20761 }
20762
20763 /**
20764  * lpfc_log_fw_write_cmpl - logs firmware write completion status
20765  * @phba: pointer to lpfc hba data structure
20766  * @shdr_status: wr_object rsp's status field
20767  * @shdr_add_status: wr_object rsp's add_status field
20768  * @shdr_add_status_2: wr_object rsp's add_status_2 field
20769  * @shdr_change_status: wr_object rsp's change_status field
20770  * @shdr_csf: wr_object rsp's csf bit
20771  *
20772  * This routine is intended to be called after a firmware write completes.
20773  * It will log next action items to be performed by the user to instantiate
20774  * the newly downloaded firmware or reason for incompatibility.
20775  **/
20776 static void
20777 lpfc_log_fw_write_cmpl(struct lpfc_hba *phba, u32 shdr_status,
20778                        u32 shdr_add_status, u32 shdr_add_status_2,
20779                        u32 shdr_change_status, u32 shdr_csf)
20780 {
20781         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20782                         "4198 %s: flash_id x%02x, asic_rev x%02x, "
20783                         "status x%02x, add_status x%02x, add_status_2 x%02x, "
20784                         "change_status x%02x, csf %01x\n", __func__,
20785                         phba->sli4_hba.flash_id, phba->sli4_hba.asic_rev,
20786                         shdr_status, shdr_add_status, shdr_add_status_2,
20787                         shdr_change_status, shdr_csf);
20788
20789         if (shdr_add_status == LPFC_ADD_STATUS_INCOMPAT_OBJ) {
20790                 switch (shdr_add_status_2) {
20791                 case LPFC_ADD_STATUS_2_INCOMPAT_FLASH:
20792                         lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20793                                         "4199 Firmware write failed: "
20794                                         "image incompatible with flash x%02x\n",
20795                                         phba->sli4_hba.flash_id);
20796                         break;
20797                 case LPFC_ADD_STATUS_2_INCORRECT_ASIC:
20798                         lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20799                                         "4200 Firmware write failed: "
20800                                         "image incompatible with ASIC "
20801                                         "architecture x%02x\n",
20802                                         phba->sli4_hba.asic_rev);
20803                         break;
20804                 default:
20805                         lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20806                                         "4210 Firmware write failed: "
20807                                         "add_status_2 x%02x\n",
20808                                         shdr_add_status_2);
20809                         break;
20810                 }
20811         } else if (!shdr_status && !shdr_add_status) {
20812                 if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
20813                     shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
20814                         if (shdr_csf)
20815                                 shdr_change_status =
20816                                                    LPFC_CHANGE_STATUS_PCI_RESET;
20817                 }
20818
20819                 switch (shdr_change_status) {
20820                 case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
20821                         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20822                                         "3198 Firmware write complete: System "
20823                                         "reboot required to instantiate\n");
20824                         break;
20825                 case (LPFC_CHANGE_STATUS_FW_RESET):
20826                         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20827                                         "3199 Firmware write complete: "
20828                                         "Firmware reset required to "
20829                                         "instantiate\n");
20830                         break;
20831                 case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
20832                         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20833                                         "3200 Firmware write complete: Port "
20834                                         "Migration or PCI Reset required to "
20835                                         "instantiate\n");
20836                         break;
20837                 case (LPFC_CHANGE_STATUS_PCI_RESET):
20838                         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20839                                         "3201 Firmware write complete: PCI "
20840                                         "Reset required to instantiate\n");
20841                         break;
20842                 default:
20843                         break;
20844                 }
20845         }
20846 }
20847
20848 /**
20849  * lpfc_wr_object - write an object to the firmware
20850  * @phba: HBA structure that indicates port to create a queue on.
20851  * @dmabuf_list: list of dmabufs to write to the port.
20852  * @size: the total byte value of the objects to write to the port.
20853  * @offset: the current offset to be used to start the transfer.
20854  *
20855  * This routine will create a wr_object mailbox command to send to the port.
20856  * the mailbox command will be constructed using the dma buffers described in
20857  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
20858  * BDEs that the imbedded mailbox can support. The @offset variable will be
20859  * used to indicate the starting offset of the transfer and will also return
20860  * the offset after the write object mailbox has completed. @size is used to
20861  * determine the end of the object and whether the eof bit should be set.
20862  *
20863  * Return 0 is successful and offset will contain the the new offset to use
20864  * for the next write.
20865  * Return negative value for error cases.
20866  **/
20867 int
20868 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
20869                uint32_t size, uint32_t *offset)
20870 {
20871         struct lpfc_mbx_wr_object *wr_object;
20872         LPFC_MBOXQ_t *mbox;
20873         int rc = 0, i = 0;
20874         uint32_t shdr_status, shdr_add_status, shdr_add_status_2;
20875         uint32_t shdr_change_status = 0, shdr_csf = 0;
20876         uint32_t mbox_tmo;
20877         struct lpfc_dmabuf *dmabuf;
20878         uint32_t written = 0;
20879         bool check_change_status = false;
20880
20881         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20882         if (!mbox)
20883                 return -ENOMEM;
20884
20885         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
20886                         LPFC_MBOX_OPCODE_WRITE_OBJECT,
20887                         sizeof(struct lpfc_mbx_wr_object) -
20888                         sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
20889
20890         wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
20891         wr_object->u.request.write_offset = *offset;
20892         sprintf((uint8_t *)wr_object->u.request.object_name, "/");
20893         wr_object->u.request.object_name[0] =
20894                 cpu_to_le32(wr_object->u.request.object_name[0]);
20895         bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
20896         list_for_each_entry(dmabuf, dmabuf_list, list) {
20897                 if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
20898                         break;
20899                 wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
20900                 wr_object->u.request.bde[i].addrHigh =
20901                         putPaddrHigh(dmabuf->phys);
20902                 if (written + SLI4_PAGE_SIZE >= size) {
20903                         wr_object->u.request.bde[i].tus.f.bdeSize =
20904                                 (size - written);
20905                         written += (size - written);
20906                         bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
20907                         bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
20908                         check_change_status = true;
20909                 } else {
20910                         wr_object->u.request.bde[i].tus.f.bdeSize =
20911                                 SLI4_PAGE_SIZE;
20912                         written += SLI4_PAGE_SIZE;
20913                 }
20914                 i++;
20915         }
20916         wr_object->u.request.bde_count = i;
20917         bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
20918         if (!phba->sli4_hba.intr_enable)
20919                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
20920         else {
20921                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
20922                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
20923         }
20924         /* The IOCTL status is embedded in the mailbox subheader. */
20925         shdr_status = bf_get(lpfc_mbox_hdr_status,
20926                              &wr_object->header.cfg_shdr.response);
20927         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20928                                  &wr_object->header.cfg_shdr.response);
20929         shdr_add_status_2 = bf_get(lpfc_mbox_hdr_add_status_2,
20930                                    &wr_object->header.cfg_shdr.response);
20931         if (check_change_status) {
20932                 shdr_change_status = bf_get(lpfc_wr_object_change_status,
20933                                             &wr_object->u.response);
20934                 shdr_csf = bf_get(lpfc_wr_object_csf,
20935                                   &wr_object->u.response);
20936         }
20937
20938         if (!phba->sli4_hba.intr_enable)
20939                 mempool_free(mbox, phba->mbox_mem_pool);
20940         else if (rc != MBX_TIMEOUT)
20941                 mempool_free(mbox, phba->mbox_mem_pool);
20942         if (shdr_status || shdr_add_status || shdr_add_status_2 || rc) {
20943                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20944                                 "3025 Write Object mailbox failed with "
20945                                 "status x%x add_status x%x, add_status_2 x%x, "
20946                                 "mbx status x%x\n",
20947                                 shdr_status, shdr_add_status, shdr_add_status_2,
20948                                 rc);
20949                 rc = -ENXIO;
20950                 *offset = shdr_add_status;
20951         } else {
20952                 *offset += wr_object->u.response.actual_write_length;
20953         }
20954
20955         if (rc || check_change_status)
20956                 lpfc_log_fw_write_cmpl(phba, shdr_status, shdr_add_status,
20957                                        shdr_add_status_2, shdr_change_status,
20958                                        shdr_csf);
20959         return rc;
20960 }
20961
20962 /**
20963  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
20964  * @vport: pointer to vport data structure.
20965  *
20966  * This function iterate through the mailboxq and clean up all REG_LOGIN
20967  * and REG_VPI mailbox commands associated with the vport. This function
20968  * is called when driver want to restart discovery of the vport due to
20969  * a Clear Virtual Link event.
20970  **/
20971 void
20972 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
20973 {
20974         struct lpfc_hba *phba = vport->phba;
20975         LPFC_MBOXQ_t *mb, *nextmb;
20976         struct lpfc_dmabuf *mp;
20977         struct lpfc_nodelist *ndlp;
20978         struct lpfc_nodelist *act_mbx_ndlp = NULL;
20979         LIST_HEAD(mbox_cmd_list);
20980         uint8_t restart_loop;
20981
20982         /* Clean up internally queued mailbox commands with the vport */
20983         spin_lock_irq(&phba->hbalock);
20984         list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
20985                 if (mb->vport != vport)
20986                         continue;
20987
20988                 if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
20989                         (mb->u.mb.mbxCommand != MBX_REG_VPI))
20990                         continue;
20991
20992                 list_move_tail(&mb->list, &mbox_cmd_list);
20993         }
20994         /* Clean up active mailbox command with the vport */
20995         mb = phba->sli.mbox_active;
20996         if (mb && (mb->vport == vport)) {
20997                 if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
20998                         (mb->u.mb.mbxCommand == MBX_REG_VPI))
20999                         mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21000                 if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21001                         act_mbx_ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
21002                         /* Put reference count for delayed processing */
21003                         act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
21004                         /* Unregister the RPI when mailbox complete */
21005                         mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21006                 }
21007         }
21008         /* Cleanup any mailbox completions which are not yet processed */
21009         do {
21010                 restart_loop = 0;
21011                 list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
21012                         /*
21013                          * If this mailox is already processed or it is
21014                          * for another vport ignore it.
21015                          */
21016                         if ((mb->vport != vport) ||
21017                                 (mb->mbox_flag & LPFC_MBX_IMED_UNREG))
21018                                 continue;
21019
21020                         if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21021                                 (mb->u.mb.mbxCommand != MBX_REG_VPI))
21022                                 continue;
21023
21024                         mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21025                         if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21026                                 ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
21027                                 /* Unregister the RPI when mailbox complete */
21028                                 mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21029                                 restart_loop = 1;
21030                                 spin_unlock_irq(&phba->hbalock);
21031                                 spin_lock(&ndlp->lock);
21032                                 ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21033                                 spin_unlock(&ndlp->lock);
21034                                 spin_lock_irq(&phba->hbalock);
21035                                 break;
21036                         }
21037                 }
21038         } while (restart_loop);
21039
21040         spin_unlock_irq(&phba->hbalock);
21041
21042         /* Release the cleaned-up mailbox commands */
21043         while (!list_empty(&mbox_cmd_list)) {
21044                 list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
21045                 if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21046                         mp = (struct lpfc_dmabuf *)(mb->ctx_buf);
21047                         if (mp) {
21048                                 __lpfc_mbuf_free(phba, mp->virt, mp->phys);
21049                                 kfree(mp);
21050                         }
21051                         mb->ctx_buf = NULL;
21052                         ndlp = (struct lpfc_nodelist *)mb->ctx_ndlp;
21053                         mb->ctx_ndlp = NULL;
21054                         if (ndlp) {
21055                                 spin_lock(&ndlp->lock);
21056                                 ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21057                                 spin_unlock(&ndlp->lock);
21058                                 lpfc_nlp_put(ndlp);
21059                         }
21060                 }
21061                 mempool_free(mb, phba->mbox_mem_pool);
21062         }
21063
21064         /* Release the ndlp with the cleaned-up active mailbox command */
21065         if (act_mbx_ndlp) {
21066                 spin_lock(&act_mbx_ndlp->lock);
21067                 act_mbx_ndlp->nlp_flag &= ~NLP_IGNR_REG_CMPL;
21068                 spin_unlock(&act_mbx_ndlp->lock);
21069                 lpfc_nlp_put(act_mbx_ndlp);
21070         }
21071 }
21072
21073 /**
21074  * lpfc_drain_txq - Drain the txq
21075  * @phba: Pointer to HBA context object.
21076  *
21077  * This function attempt to submit IOCBs on the txq
21078  * to the adapter.  For SLI4 adapters, the txq contains
21079  * ELS IOCBs that have been deferred because the there
21080  * are no SGLs.  This congestion can occur with large
21081  * vport counts during node discovery.
21082  **/
21083
21084 uint32_t
21085 lpfc_drain_txq(struct lpfc_hba *phba)
21086 {
21087         LIST_HEAD(completions);
21088         struct lpfc_sli_ring *pring;
21089         struct lpfc_iocbq *piocbq = NULL;
21090         unsigned long iflags = 0;
21091         char *fail_msg = NULL;
21092         struct lpfc_sglq *sglq;
21093         union lpfc_wqe128 wqe;
21094         uint32_t txq_cnt = 0;
21095         struct lpfc_queue *wq;
21096
21097         if (phba->link_flag & LS_MDS_LOOPBACK) {
21098                 /* MDS WQE are posted only to first WQ*/
21099                 wq = phba->sli4_hba.hdwq[0].io_wq;
21100                 if (unlikely(!wq))
21101                         return 0;
21102                 pring = wq->pring;
21103         } else {
21104                 wq = phba->sli4_hba.els_wq;
21105                 if (unlikely(!wq))
21106                         return 0;
21107                 pring = lpfc_phba_elsring(phba);
21108         }
21109
21110         if (unlikely(!pring) || list_empty(&pring->txq))
21111                 return 0;
21112
21113         spin_lock_irqsave(&pring->ring_lock, iflags);
21114         list_for_each_entry(piocbq, &pring->txq, list) {
21115                 txq_cnt++;
21116         }
21117
21118         if (txq_cnt > pring->txq_max)
21119                 pring->txq_max = txq_cnt;
21120
21121         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21122
21123         while (!list_empty(&pring->txq)) {
21124                 spin_lock_irqsave(&pring->ring_lock, iflags);
21125
21126                 piocbq = lpfc_sli_ringtx_get(phba, pring);
21127                 if (!piocbq) {
21128                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21129                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21130                                 "2823 txq empty and txq_cnt is %d\n ",
21131                                 txq_cnt);
21132                         break;
21133                 }
21134                 sglq = __lpfc_sli_get_els_sglq(phba, piocbq);
21135                 if (!sglq) {
21136                         __lpfc_sli_ringtx_put(phba, pring, piocbq);
21137                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21138                         break;
21139                 }
21140                 txq_cnt--;
21141
21142                 /* The xri and iocb resources secured,
21143                  * attempt to issue request
21144                  */
21145                 piocbq->sli4_lxritag = sglq->sli4_lxritag;
21146                 piocbq->sli4_xritag = sglq->sli4_xritag;
21147                 if (NO_XRI == lpfc_sli4_bpl2sgl(phba, piocbq, sglq))
21148                         fail_msg = "to convert bpl to sgl";
21149                 else if (lpfc_sli4_iocb2wqe(phba, piocbq, &wqe))
21150                         fail_msg = "to convert iocb to wqe";
21151                 else if (lpfc_sli4_wq_put(wq, &wqe))
21152                         fail_msg = " - Wq is full";
21153                 else
21154                         lpfc_sli_ringtxcmpl_put(phba, pring, piocbq);
21155
21156                 if (fail_msg) {
21157                         /* Failed means we can't issue and need to cancel */
21158                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21159                                         "2822 IOCB failed %s iotag 0x%x "
21160                                         "xri 0x%x\n",
21161                                         fail_msg,
21162                                         piocbq->iotag, piocbq->sli4_xritag);
21163                         list_add_tail(&piocbq->list, &completions);
21164                         fail_msg = NULL;
21165                 }
21166                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
21167         }
21168
21169         /* Cancel all the IOCBs that cannot be issued */
21170         lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
21171                                 IOERR_SLI_ABORTED);
21172
21173         return txq_cnt;
21174 }
21175
21176 /**
21177  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
21178  * @phba: Pointer to HBA context object.
21179  * @pwqeq: Pointer to command WQE.
21180  * @sglq: Pointer to the scatter gather queue object.
21181  *
21182  * This routine converts the bpl or bde that is in the WQE
21183  * to a sgl list for the sli4 hardware. The physical address
21184  * of the bpl/bde is converted back to a virtual address.
21185  * If the WQE contains a BPL then the list of BDE's is
21186  * converted to sli4_sge's. If the WQE contains a single
21187  * BDE then it is converted to a single sli_sge.
21188  * The WQE is still in cpu endianness so the contents of
21189  * the bpl can be used without byte swapping.
21190  *
21191  * Returns valid XRI = Success, NO_XRI = Failure.
21192  */
21193 static uint16_t
21194 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
21195                  struct lpfc_sglq *sglq)
21196 {
21197         uint16_t xritag = NO_XRI;
21198         struct ulp_bde64 *bpl = NULL;
21199         struct ulp_bde64 bde;
21200         struct sli4_sge *sgl  = NULL;
21201         struct lpfc_dmabuf *dmabuf;
21202         union lpfc_wqe128 *wqe;
21203         int numBdes = 0;
21204         int i = 0;
21205         uint32_t offset = 0; /* accumulated offset in the sg request list */
21206         int inbound = 0; /* number of sg reply entries inbound from firmware */
21207         uint32_t cmd;
21208
21209         if (!pwqeq || !sglq)
21210                 return xritag;
21211
21212         sgl  = (struct sli4_sge *)sglq->sgl;
21213         wqe = &pwqeq->wqe;
21214         pwqeq->iocb.ulpIoTag = pwqeq->iotag;
21215
21216         cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
21217         if (cmd == CMD_XMIT_BLS_RSP64_WQE)
21218                 return sglq->sli4_xritag;
21219         numBdes = pwqeq->rsvd2;
21220         if (numBdes) {
21221                 /* The addrHigh and addrLow fields within the WQE
21222                  * have not been byteswapped yet so there is no
21223                  * need to swap them back.
21224                  */
21225                 if (pwqeq->context3)
21226                         dmabuf = (struct lpfc_dmabuf *)pwqeq->context3;
21227                 else
21228                         return xritag;
21229
21230                 bpl  = (struct ulp_bde64 *)dmabuf->virt;
21231                 if (!bpl)
21232                         return xritag;
21233
21234                 for (i = 0; i < numBdes; i++) {
21235                         /* Should already be byte swapped. */
21236                         sgl->addr_hi = bpl->addrHigh;
21237                         sgl->addr_lo = bpl->addrLow;
21238
21239                         sgl->word2 = le32_to_cpu(sgl->word2);
21240                         if ((i+1) == numBdes)
21241                                 bf_set(lpfc_sli4_sge_last, sgl, 1);
21242                         else
21243                                 bf_set(lpfc_sli4_sge_last, sgl, 0);
21244                         /* swap the size field back to the cpu so we
21245                          * can assign it to the sgl.
21246                          */
21247                         bde.tus.w = le32_to_cpu(bpl->tus.w);
21248                         sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
21249                         /* The offsets in the sgl need to be accumulated
21250                          * separately for the request and reply lists.
21251                          * The request is always first, the reply follows.
21252                          */
21253                         switch (cmd) {
21254                         case CMD_GEN_REQUEST64_WQE:
21255                                 /* add up the reply sg entries */
21256                                 if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
21257                                         inbound++;
21258                                 /* first inbound? reset the offset */
21259                                 if (inbound == 1)
21260                                         offset = 0;
21261                                 bf_set(lpfc_sli4_sge_offset, sgl, offset);
21262                                 bf_set(lpfc_sli4_sge_type, sgl,
21263                                         LPFC_SGE_TYPE_DATA);
21264                                 offset += bde.tus.f.bdeSize;
21265                                 break;
21266                         case CMD_FCP_TRSP64_WQE:
21267                                 bf_set(lpfc_sli4_sge_offset, sgl, 0);
21268                                 bf_set(lpfc_sli4_sge_type, sgl,
21269                                         LPFC_SGE_TYPE_DATA);
21270                                 break;
21271                         case CMD_FCP_TSEND64_WQE:
21272                         case CMD_FCP_TRECEIVE64_WQE:
21273                                 bf_set(lpfc_sli4_sge_type, sgl,
21274                                         bpl->tus.f.bdeFlags);
21275                                 if (i < 3)
21276                                         offset = 0;
21277                                 else
21278                                         offset += bde.tus.f.bdeSize;
21279                                 bf_set(lpfc_sli4_sge_offset, sgl, offset);
21280                                 break;
21281                         }
21282                         sgl->word2 = cpu_to_le32(sgl->word2);
21283                         bpl++;
21284                         sgl++;
21285                 }
21286         } else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
21287                 /* The addrHigh and addrLow fields of the BDE have not
21288                  * been byteswapped yet so they need to be swapped
21289                  * before putting them in the sgl.
21290                  */
21291                 sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
21292                 sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
21293                 sgl->word2 = le32_to_cpu(sgl->word2);
21294                 bf_set(lpfc_sli4_sge_last, sgl, 1);
21295                 sgl->word2 = cpu_to_le32(sgl->word2);
21296                 sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
21297         }
21298         return sglq->sli4_xritag;
21299 }
21300
21301 /**
21302  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
21303  * @phba: Pointer to HBA context object.
21304  * @qp: Pointer to HDW queue.
21305  * @pwqe: Pointer to command WQE.
21306  **/
21307 int
21308 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21309                     struct lpfc_iocbq *pwqe)
21310 {
21311         union lpfc_wqe128 *wqe = &pwqe->wqe;
21312         struct lpfc_async_xchg_ctx *ctxp;
21313         struct lpfc_queue *wq;
21314         struct lpfc_sglq *sglq;
21315         struct lpfc_sli_ring *pring;
21316         unsigned long iflags;
21317         uint32_t ret = 0;
21318
21319         /* NVME_LS and NVME_LS ABTS requests. */
21320         if (pwqe->iocb_flag & LPFC_IO_NVME_LS) {
21321                 pring =  phba->sli4_hba.nvmels_wq->pring;
21322                 lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21323                                           qp, wq_access);
21324                 sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
21325                 if (!sglq) {
21326                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21327                         return WQE_BUSY;
21328                 }
21329                 pwqe->sli4_lxritag = sglq->sli4_lxritag;
21330                 pwqe->sli4_xritag = sglq->sli4_xritag;
21331                 if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
21332                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21333                         return WQE_ERROR;
21334                 }
21335                 bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21336                        pwqe->sli4_xritag);
21337                 ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
21338                 if (ret) {
21339                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21340                         return ret;
21341                 }
21342
21343                 lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21344                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
21345
21346                 lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
21347                 return 0;
21348         }
21349
21350         /* NVME_FCREQ and NVME_ABTS requests */
21351         if (pwqe->iocb_flag & (LPFC_IO_NVME | LPFC_IO_FCP | LPFC_IO_CMF)) {
21352                 /* Get the IO distribution (hba_wqidx) for WQ assignment. */
21353                 wq = qp->io_wq;
21354                 pring = wq->pring;
21355
21356                 bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21357
21358                 lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21359                                           qp, wq_access);
21360                 ret = lpfc_sli4_wq_put(wq, wqe);
21361                 if (ret) {
21362                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21363                         return ret;
21364                 }
21365                 lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21366                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
21367
21368                 lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
21369                 return 0;
21370         }
21371
21372         /* NVMET requests */
21373         if (pwqe->iocb_flag & LPFC_IO_NVMET) {
21374                 /* Get the IO distribution (hba_wqidx) for WQ assignment. */
21375                 wq = qp->io_wq;
21376                 pring = wq->pring;
21377
21378                 ctxp = pwqe->context2;
21379                 sglq = ctxp->ctxbuf->sglq;
21380                 if (pwqe->sli4_xritag ==  NO_XRI) {
21381                         pwqe->sli4_lxritag = sglq->sli4_lxritag;
21382                         pwqe->sli4_xritag = sglq->sli4_xritag;
21383                 }
21384                 bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21385                        pwqe->sli4_xritag);
21386                 bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21387
21388                 lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21389                                           qp, wq_access);
21390                 ret = lpfc_sli4_wq_put(wq, wqe);
21391                 if (ret) {
21392                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21393                         return ret;
21394                 }
21395                 lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21396                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
21397
21398                 lpfc_sli4_poll_eq(qp->hba_eq, LPFC_POLL_FASTPATH);
21399                 return 0;
21400         }
21401         return WQE_ERROR;
21402 }
21403
21404 /**
21405  * lpfc_sli4_issue_abort_iotag - SLI-4 WQE init & issue for the Abort
21406  * @phba: Pointer to HBA context object.
21407  * @cmdiocb: Pointer to driver command iocb object.
21408  * @cmpl: completion function.
21409  *
21410  * Fill the appropriate fields for the abort WQE and call
21411  * internal routine lpfc_sli4_issue_wqe to send the WQE
21412  * This function is called with hbalock held and no ring_lock held.
21413  *
21414  * RETURNS 0 - SUCCESS
21415  **/
21416
21417 int
21418 lpfc_sli4_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
21419                             void *cmpl)
21420 {
21421         struct lpfc_vport *vport = cmdiocb->vport;
21422         struct lpfc_iocbq *abtsiocb = NULL;
21423         union lpfc_wqe128 *abtswqe;
21424         struct lpfc_io_buf *lpfc_cmd;
21425         int retval = IOCB_ERROR;
21426         u16 xritag = cmdiocb->sli4_xritag;
21427
21428         /*
21429          * The scsi command can not be in txq and it is in flight because the
21430          * pCmd is still pointing at the SCSI command we have to abort. There
21431          * is no need to search the txcmplq. Just send an abort to the FW.
21432          */
21433
21434         abtsiocb = __lpfc_sli_get_iocbq(phba);
21435         if (!abtsiocb)
21436                 return WQE_NORESOURCE;
21437
21438         /* Indicate the IO is being aborted by the driver. */
21439         cmdiocb->iocb_flag |= LPFC_DRIVER_ABORTED;
21440
21441         abtswqe = &abtsiocb->wqe;
21442         memset(abtswqe, 0, sizeof(*abtswqe));
21443
21444         if (!lpfc_is_link_up(phba))
21445                 bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 1);
21446         bf_set(abort_cmd_criteria, &abtswqe->abort_cmd, T_XRI_TAG);
21447         abtswqe->abort_cmd.rsrvd5 = 0;
21448         abtswqe->abort_cmd.wqe_com.abort_tag = xritag;
21449         bf_set(wqe_reqtag, &abtswqe->abort_cmd.wqe_com, abtsiocb->iotag);
21450         bf_set(wqe_cmnd, &abtswqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
21451         bf_set(wqe_xri_tag, &abtswqe->generic.wqe_com, 0);
21452         bf_set(wqe_qosd, &abtswqe->abort_cmd.wqe_com, 1);
21453         bf_set(wqe_lenloc, &abtswqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
21454         bf_set(wqe_cmd_type, &abtswqe->abort_cmd.wqe_com, OTHER_COMMAND);
21455
21456         /* ABTS WQE must go to the same WQ as the WQE to be aborted */
21457         abtsiocb->hba_wqidx = cmdiocb->hba_wqidx;
21458         abtsiocb->iocb_flag |= LPFC_USE_FCPWQIDX;
21459         if (cmdiocb->iocb_flag & LPFC_IO_FCP)
21460                 abtsiocb->iocb_flag |= LPFC_IO_FCP;
21461         if (cmdiocb->iocb_flag & LPFC_IO_NVME)
21462                 abtsiocb->iocb_flag |= LPFC_IO_NVME;
21463         if (cmdiocb->iocb_flag & LPFC_IO_FOF)
21464                 abtsiocb->iocb_flag |= LPFC_IO_FOF;
21465         abtsiocb->vport = vport;
21466         abtsiocb->wqe_cmpl = cmpl;
21467
21468         lpfc_cmd = container_of(cmdiocb, struct lpfc_io_buf, cur_iocbq);
21469         retval = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, abtsiocb);
21470
21471         lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21472                          "0359 Abort xri x%x, original iotag x%x, "
21473                          "abort cmd iotag x%x retval x%x\n",
21474                          xritag, cmdiocb->iotag, abtsiocb->iotag, retval);
21475
21476         if (retval) {
21477                 cmdiocb->iocb_flag &= ~LPFC_DRIVER_ABORTED;
21478                 __lpfc_sli_release_iocbq(phba, abtsiocb);
21479         }
21480
21481         return retval;
21482 }
21483
21484 #ifdef LPFC_MXP_STAT
21485 /**
21486  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
21487  * @phba: pointer to lpfc hba data structure.
21488  * @hwqid: belong to which HWQ.
21489  *
21490  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
21491  * 15 seconds after a test case is running.
21492  *
21493  * The user should call lpfc_debugfs_multixripools_write before running a test
21494  * case to clear stat_snapshot_taken. Then the user starts a test case. During
21495  * test case is running, stat_snapshot_taken is incremented by 1 every time when
21496  * this routine is called from heartbeat timer. When stat_snapshot_taken is
21497  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
21498  **/
21499 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
21500 {
21501         struct lpfc_sli4_hdw_queue *qp;
21502         struct lpfc_multixri_pool *multixri_pool;
21503         struct lpfc_pvt_pool *pvt_pool;
21504         struct lpfc_pbl_pool *pbl_pool;
21505         u32 txcmplq_cnt;
21506
21507         qp = &phba->sli4_hba.hdwq[hwqid];
21508         multixri_pool = qp->p_multixri_pool;
21509         if (!multixri_pool)
21510                 return;
21511
21512         if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
21513                 pvt_pool = &qp->p_multixri_pool->pvt_pool;
21514                 pbl_pool = &qp->p_multixri_pool->pbl_pool;
21515                 txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21516
21517                 multixri_pool->stat_pbl_count = pbl_pool->count;
21518                 multixri_pool->stat_pvt_count = pvt_pool->count;
21519                 multixri_pool->stat_busy_count = txcmplq_cnt;
21520         }
21521
21522         multixri_pool->stat_snapshot_taken++;
21523 }
21524 #endif
21525
21526 /**
21527  * lpfc_adjust_pvt_pool_count - Adjust private pool count
21528  * @phba: pointer to lpfc hba data structure.
21529  * @hwqid: belong to which HWQ.
21530  *
21531  * This routine moves some XRIs from private to public pool when private pool
21532  * is not busy.
21533  **/
21534 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
21535 {
21536         struct lpfc_multixri_pool *multixri_pool;
21537         u32 io_req_count;
21538         u32 prev_io_req_count;
21539
21540         multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21541         if (!multixri_pool)
21542                 return;
21543         io_req_count = multixri_pool->io_req_count;
21544         prev_io_req_count = multixri_pool->prev_io_req_count;
21545
21546         if (prev_io_req_count != io_req_count) {
21547                 /* Private pool is busy */
21548                 multixri_pool->prev_io_req_count = io_req_count;
21549         } else {
21550                 /* Private pool is not busy.
21551                  * Move XRIs from private to public pool.
21552                  */
21553                 lpfc_move_xri_pvt_to_pbl(phba, hwqid);
21554         }
21555 }
21556
21557 /**
21558  * lpfc_adjust_high_watermark - Adjust high watermark
21559  * @phba: pointer to lpfc hba data structure.
21560  * @hwqid: belong to which HWQ.
21561  *
21562  * This routine sets high watermark as number of outstanding XRIs,
21563  * but make sure the new value is between xri_limit/2 and xri_limit.
21564  **/
21565 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
21566 {
21567         u32 new_watermark;
21568         u32 watermark_max;
21569         u32 watermark_min;
21570         u32 xri_limit;
21571         u32 txcmplq_cnt;
21572         u32 abts_io_bufs;
21573         struct lpfc_multixri_pool *multixri_pool;
21574         struct lpfc_sli4_hdw_queue *qp;
21575
21576         qp = &phba->sli4_hba.hdwq[hwqid];
21577         multixri_pool = qp->p_multixri_pool;
21578         if (!multixri_pool)
21579                 return;
21580         xri_limit = multixri_pool->xri_limit;
21581
21582         watermark_max = xri_limit;
21583         watermark_min = xri_limit / 2;
21584
21585         txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21586         abts_io_bufs = qp->abts_scsi_io_bufs;
21587         abts_io_bufs += qp->abts_nvme_io_bufs;
21588
21589         new_watermark = txcmplq_cnt + abts_io_bufs;
21590         new_watermark = min(watermark_max, new_watermark);
21591         new_watermark = max(watermark_min, new_watermark);
21592         multixri_pool->pvt_pool.high_watermark = new_watermark;
21593
21594 #ifdef LPFC_MXP_STAT
21595         multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
21596                                           new_watermark);
21597 #endif
21598 }
21599
21600 /**
21601  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
21602  * @phba: pointer to lpfc hba data structure.
21603  * @hwqid: belong to which HWQ.
21604  *
21605  * This routine is called from hearbeat timer when pvt_pool is idle.
21606  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
21607  * The first step moves (all - low_watermark) amount of XRIs.
21608  * The second step moves the rest of XRIs.
21609  **/
21610 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
21611 {
21612         struct lpfc_pbl_pool *pbl_pool;
21613         struct lpfc_pvt_pool *pvt_pool;
21614         struct lpfc_sli4_hdw_queue *qp;
21615         struct lpfc_io_buf *lpfc_ncmd;
21616         struct lpfc_io_buf *lpfc_ncmd_next;
21617         unsigned long iflag;
21618         struct list_head tmp_list;
21619         u32 tmp_count;
21620
21621         qp = &phba->sli4_hba.hdwq[hwqid];
21622         pbl_pool = &qp->p_multixri_pool->pbl_pool;
21623         pvt_pool = &qp->p_multixri_pool->pvt_pool;
21624         tmp_count = 0;
21625
21626         lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
21627         lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
21628
21629         if (pvt_pool->count > pvt_pool->low_watermark) {
21630                 /* Step 1: move (all - low_watermark) from pvt_pool
21631                  * to pbl_pool
21632                  */
21633
21634                 /* Move low watermark of bufs from pvt_pool to tmp_list */
21635                 INIT_LIST_HEAD(&tmp_list);
21636                 list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21637                                          &pvt_pool->list, list) {
21638                         list_move_tail(&lpfc_ncmd->list, &tmp_list);
21639                         tmp_count++;
21640                         if (tmp_count >= pvt_pool->low_watermark)
21641                                 break;
21642                 }
21643
21644                 /* Move all bufs from pvt_pool to pbl_pool */
21645                 list_splice_init(&pvt_pool->list, &pbl_pool->list);
21646
21647                 /* Move all bufs from tmp_list to pvt_pool */
21648                 list_splice(&tmp_list, &pvt_pool->list);
21649
21650                 pbl_pool->count += (pvt_pool->count - tmp_count);
21651                 pvt_pool->count = tmp_count;
21652         } else {
21653                 /* Step 2: move the rest from pvt_pool to pbl_pool */
21654                 list_splice_init(&pvt_pool->list, &pbl_pool->list);
21655                 pbl_pool->count += pvt_pool->count;
21656                 pvt_pool->count = 0;
21657         }
21658
21659         spin_unlock(&pvt_pool->lock);
21660         spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21661 }
21662
21663 /**
21664  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21665  * @phba: pointer to lpfc hba data structure
21666  * @qp: pointer to HDW queue
21667  * @pbl_pool: specified public free XRI pool
21668  * @pvt_pool: specified private free XRI pool
21669  * @count: number of XRIs to move
21670  *
21671  * This routine tries to move some free common bufs from the specified pbl_pool
21672  * to the specified pvt_pool. It might move less than count XRIs if there's not
21673  * enough in public pool.
21674  *
21675  * Return:
21676  *   true - if XRIs are successfully moved from the specified pbl_pool to the
21677  *          specified pvt_pool
21678  *   false - if the specified pbl_pool is empty or locked by someone else
21679  **/
21680 static bool
21681 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21682                           struct lpfc_pbl_pool *pbl_pool,
21683                           struct lpfc_pvt_pool *pvt_pool, u32 count)
21684 {
21685         struct lpfc_io_buf *lpfc_ncmd;
21686         struct lpfc_io_buf *lpfc_ncmd_next;
21687         unsigned long iflag;
21688         int ret;
21689
21690         ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
21691         if (ret) {
21692                 if (pbl_pool->count) {
21693                         /* Move a batch of XRIs from public to private pool */
21694                         lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
21695                         list_for_each_entry_safe(lpfc_ncmd,
21696                                                  lpfc_ncmd_next,
21697                                                  &pbl_pool->list,
21698                                                  list) {
21699                                 list_move_tail(&lpfc_ncmd->list,
21700                                                &pvt_pool->list);
21701                                 pvt_pool->count++;
21702                                 pbl_pool->count--;
21703                                 count--;
21704                                 if (count == 0)
21705                                         break;
21706                         }
21707
21708                         spin_unlock(&pvt_pool->lock);
21709                         spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21710                         return true;
21711                 }
21712                 spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21713         }
21714
21715         return false;
21716 }
21717
21718 /**
21719  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21720  * @phba: pointer to lpfc hba data structure.
21721  * @hwqid: belong to which HWQ.
21722  * @count: number of XRIs to move
21723  *
21724  * This routine tries to find some free common bufs in one of public pools with
21725  * Round Robin method. The search always starts from local hwqid, then the next
21726  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
21727  * a batch of free common bufs are moved to private pool on hwqid.
21728  * It might move less than count XRIs if there's not enough in public pool.
21729  **/
21730 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
21731 {
21732         struct lpfc_multixri_pool *multixri_pool;
21733         struct lpfc_multixri_pool *next_multixri_pool;
21734         struct lpfc_pvt_pool *pvt_pool;
21735         struct lpfc_pbl_pool *pbl_pool;
21736         struct lpfc_sli4_hdw_queue *qp;
21737         u32 next_hwqid;
21738         u32 hwq_count;
21739         int ret;
21740
21741         qp = &phba->sli4_hba.hdwq[hwqid];
21742         multixri_pool = qp->p_multixri_pool;
21743         pvt_pool = &multixri_pool->pvt_pool;
21744         pbl_pool = &multixri_pool->pbl_pool;
21745
21746         /* Check if local pbl_pool is available */
21747         ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
21748         if (ret) {
21749 #ifdef LPFC_MXP_STAT
21750                 multixri_pool->local_pbl_hit_count++;
21751 #endif
21752                 return;
21753         }
21754
21755         hwq_count = phba->cfg_hdw_queue;
21756
21757         /* Get the next hwqid which was found last time */
21758         next_hwqid = multixri_pool->rrb_next_hwqid;
21759
21760         do {
21761                 /* Go to next hwq */
21762                 next_hwqid = (next_hwqid + 1) % hwq_count;
21763
21764                 next_multixri_pool =
21765                         phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
21766                 pbl_pool = &next_multixri_pool->pbl_pool;
21767
21768                 /* Check if the public free xri pool is available */
21769                 ret = _lpfc_move_xri_pbl_to_pvt(
21770                         phba, qp, pbl_pool, pvt_pool, count);
21771
21772                 /* Exit while-loop if success or all hwqid are checked */
21773         } while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
21774
21775         /* Starting point for the next time */
21776         multixri_pool->rrb_next_hwqid = next_hwqid;
21777
21778         if (!ret) {
21779                 /* stats: all public pools are empty*/
21780                 multixri_pool->pbl_empty_count++;
21781         }
21782
21783 #ifdef LPFC_MXP_STAT
21784         if (ret) {
21785                 if (next_hwqid == hwqid)
21786                         multixri_pool->local_pbl_hit_count++;
21787                 else
21788                         multixri_pool->other_pbl_hit_count++;
21789         }
21790 #endif
21791 }
21792
21793 /**
21794  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
21795  * @phba: pointer to lpfc hba data structure.
21796  * @hwqid: belong to which HWQ.
21797  *
21798  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
21799  * low watermark.
21800  **/
21801 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
21802 {
21803         struct lpfc_multixri_pool *multixri_pool;
21804         struct lpfc_pvt_pool *pvt_pool;
21805
21806         multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21807         pvt_pool = &multixri_pool->pvt_pool;
21808
21809         if (pvt_pool->count < pvt_pool->low_watermark)
21810                 lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21811 }
21812
21813 /**
21814  * lpfc_release_io_buf - Return one IO buf back to free pool
21815  * @phba: pointer to lpfc hba data structure.
21816  * @lpfc_ncmd: IO buf to be returned.
21817  * @qp: belong to which HWQ.
21818  *
21819  * This routine returns one IO buf back to free pool. If this is an urgent IO,
21820  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
21821  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
21822  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
21823  * lpfc_io_buf_list_put.
21824  **/
21825 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
21826                          struct lpfc_sli4_hdw_queue *qp)
21827 {
21828         unsigned long iflag;
21829         struct lpfc_pbl_pool *pbl_pool;
21830         struct lpfc_pvt_pool *pvt_pool;
21831         struct lpfc_epd_pool *epd_pool;
21832         u32 txcmplq_cnt;
21833         u32 xri_owned;
21834         u32 xri_limit;
21835         u32 abts_io_bufs;
21836
21837         /* MUST zero fields if buffer is reused by another protocol */
21838         lpfc_ncmd->nvmeCmd = NULL;
21839         lpfc_ncmd->cur_iocbq.wqe_cmpl = NULL;
21840         lpfc_ncmd->cur_iocbq.iocb_cmpl = NULL;
21841
21842         if (phba->cfg_xpsgl && !phba->nvmet_support &&
21843             !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
21844                 lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
21845
21846         if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
21847                 lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
21848
21849         if (phba->cfg_xri_rebalancing) {
21850                 if (lpfc_ncmd->expedite) {
21851                         /* Return to expedite pool */
21852                         epd_pool = &phba->epd_pool;
21853                         spin_lock_irqsave(&epd_pool->lock, iflag);
21854                         list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
21855                         epd_pool->count++;
21856                         spin_unlock_irqrestore(&epd_pool->lock, iflag);
21857                         return;
21858                 }
21859
21860                 /* Avoid invalid access if an IO sneaks in and is being rejected
21861                  * just _after_ xri pools are destroyed in lpfc_offline.
21862                  * Nothing much can be done at this point.
21863                  */
21864                 if (!qp->p_multixri_pool)
21865                         return;
21866
21867                 pbl_pool = &qp->p_multixri_pool->pbl_pool;
21868                 pvt_pool = &qp->p_multixri_pool->pvt_pool;
21869
21870                 txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21871                 abts_io_bufs = qp->abts_scsi_io_bufs;
21872                 abts_io_bufs += qp->abts_nvme_io_bufs;
21873
21874                 xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
21875                 xri_limit = qp->p_multixri_pool->xri_limit;
21876
21877 #ifdef LPFC_MXP_STAT
21878                 if (xri_owned <= xri_limit)
21879                         qp->p_multixri_pool->below_limit_count++;
21880                 else
21881                         qp->p_multixri_pool->above_limit_count++;
21882 #endif
21883
21884                 /* XRI goes to either public or private free xri pool
21885                  *     based on watermark and xri_limit
21886                  */
21887                 if ((pvt_pool->count < pvt_pool->low_watermark) ||
21888                     (xri_owned < xri_limit &&
21889                      pvt_pool->count < pvt_pool->high_watermark)) {
21890                         lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
21891                                                   qp, free_pvt_pool);
21892                         list_add_tail(&lpfc_ncmd->list,
21893                                       &pvt_pool->list);
21894                         pvt_pool->count++;
21895                         spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21896                 } else {
21897                         lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
21898                                                   qp, free_pub_pool);
21899                         list_add_tail(&lpfc_ncmd->list,
21900                                       &pbl_pool->list);
21901                         pbl_pool->count++;
21902                         spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21903                 }
21904         } else {
21905                 lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
21906                                           qp, free_xri);
21907                 list_add_tail(&lpfc_ncmd->list,
21908                               &qp->lpfc_io_buf_list_put);
21909                 qp->put_io_bufs++;
21910                 spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
21911                                        iflag);
21912         }
21913 }
21914
21915 /**
21916  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
21917  * @phba: pointer to lpfc hba data structure.
21918  * @qp: pointer to HDW queue
21919  * @pvt_pool: pointer to private pool data structure.
21920  * @ndlp: pointer to lpfc nodelist data structure.
21921  *
21922  * This routine tries to get one free IO buf from private pool.
21923  *
21924  * Return:
21925  *   pointer to one free IO buf - if private pool is not empty
21926  *   NULL - if private pool is empty
21927  **/
21928 static struct lpfc_io_buf *
21929 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
21930                                   struct lpfc_sli4_hdw_queue *qp,
21931                                   struct lpfc_pvt_pool *pvt_pool,
21932                                   struct lpfc_nodelist *ndlp)
21933 {
21934         struct lpfc_io_buf *lpfc_ncmd;
21935         struct lpfc_io_buf *lpfc_ncmd_next;
21936         unsigned long iflag;
21937
21938         lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
21939         list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21940                                  &pvt_pool->list, list) {
21941                 if (lpfc_test_rrq_active(
21942                         phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
21943                         continue;
21944                 list_del(&lpfc_ncmd->list);
21945                 pvt_pool->count--;
21946                 spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21947                 return lpfc_ncmd;
21948         }
21949         spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21950
21951         return NULL;
21952 }
21953
21954 /**
21955  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
21956  * @phba: pointer to lpfc hba data structure.
21957  *
21958  * This routine tries to get one free IO buf from expedite pool.
21959  *
21960  * Return:
21961  *   pointer to one free IO buf - if expedite pool is not empty
21962  *   NULL - if expedite pool is empty
21963  **/
21964 static struct lpfc_io_buf *
21965 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
21966 {
21967         struct lpfc_io_buf *lpfc_ncmd;
21968         struct lpfc_io_buf *lpfc_ncmd_next;
21969         unsigned long iflag;
21970         struct lpfc_epd_pool *epd_pool;
21971
21972         epd_pool = &phba->epd_pool;
21973         lpfc_ncmd = NULL;
21974
21975         spin_lock_irqsave(&epd_pool->lock, iflag);
21976         if (epd_pool->count > 0) {
21977                 list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21978                                          &epd_pool->list, list) {
21979                         list_del(&lpfc_ncmd->list);
21980                         epd_pool->count--;
21981                         break;
21982                 }
21983         }
21984         spin_unlock_irqrestore(&epd_pool->lock, iflag);
21985
21986         return lpfc_ncmd;
21987 }
21988
21989 /**
21990  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
21991  * @phba: pointer to lpfc hba data structure.
21992  * @ndlp: pointer to lpfc nodelist data structure.
21993  * @hwqid: belong to which HWQ
21994  * @expedite: 1 means this request is urgent.
21995  *
21996  * This routine will do the following actions and then return a pointer to
21997  * one free IO buf.
21998  *
21999  * 1. If private free xri count is empty, move some XRIs from public to
22000  *    private pool.
22001  * 2. Get one XRI from private free xri pool.
22002  * 3. If we fail to get one from pvt_pool and this is an expedite request,
22003  *    get one free xri from expedite pool.
22004  *
22005  * Note: ndlp is only used on SCSI side for RRQ testing.
22006  *       The caller should pass NULL for ndlp on NVME side.
22007  *
22008  * Return:
22009  *   pointer to one free IO buf - if private pool is not empty
22010  *   NULL - if private pool is empty
22011  **/
22012 static struct lpfc_io_buf *
22013 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
22014                                     struct lpfc_nodelist *ndlp,
22015                                     int hwqid, int expedite)
22016 {
22017         struct lpfc_sli4_hdw_queue *qp;
22018         struct lpfc_multixri_pool *multixri_pool;
22019         struct lpfc_pvt_pool *pvt_pool;
22020         struct lpfc_io_buf *lpfc_ncmd;
22021
22022         qp = &phba->sli4_hba.hdwq[hwqid];
22023         lpfc_ncmd = NULL;
22024         if (!qp) {
22025                 lpfc_printf_log(phba, KERN_INFO,
22026                                 LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22027                                 "5556 NULL qp for hwqid  x%x\n", hwqid);
22028                 return lpfc_ncmd;
22029         }
22030         multixri_pool = qp->p_multixri_pool;
22031         if (!multixri_pool) {
22032                 lpfc_printf_log(phba, KERN_INFO,
22033                                 LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22034                                 "5557 NULL multixri for hwqid  x%x\n", hwqid);
22035                 return lpfc_ncmd;
22036         }
22037         pvt_pool = &multixri_pool->pvt_pool;
22038         if (!pvt_pool) {
22039                 lpfc_printf_log(phba, KERN_INFO,
22040                                 LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22041                                 "5558 NULL pvt_pool for hwqid  x%x\n", hwqid);
22042                 return lpfc_ncmd;
22043         }
22044         multixri_pool->io_req_count++;
22045
22046         /* If pvt_pool is empty, move some XRIs from public to private pool */
22047         if (pvt_pool->count == 0)
22048                 lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
22049
22050         /* Get one XRI from private free xri pool */
22051         lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
22052
22053         if (lpfc_ncmd) {
22054                 lpfc_ncmd->hdwq = qp;
22055                 lpfc_ncmd->hdwq_no = hwqid;
22056         } else if (expedite) {
22057                 /* If we fail to get one from pvt_pool and this is an expedite
22058                  * request, get one free xri from expedite pool.
22059                  */
22060                 lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
22061         }
22062
22063         return lpfc_ncmd;
22064 }
22065
22066 static inline struct lpfc_io_buf *
22067 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
22068 {
22069         struct lpfc_sli4_hdw_queue *qp;
22070         struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
22071
22072         qp = &phba->sli4_hba.hdwq[idx];
22073         list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
22074                                  &qp->lpfc_io_buf_list_get, list) {
22075                 if (lpfc_test_rrq_active(phba, ndlp,
22076                                          lpfc_cmd->cur_iocbq.sli4_lxritag))
22077                         continue;
22078
22079                 if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
22080                         continue;
22081
22082                 list_del_init(&lpfc_cmd->list);
22083                 qp->get_io_bufs--;
22084                 lpfc_cmd->hdwq = qp;
22085                 lpfc_cmd->hdwq_no = idx;
22086                 return lpfc_cmd;
22087         }
22088         return NULL;
22089 }
22090
22091 /**
22092  * lpfc_get_io_buf - Get one IO buffer from free pool
22093  * @phba: The HBA for which this call is being executed.
22094  * @ndlp: pointer to lpfc nodelist data structure.
22095  * @hwqid: belong to which HWQ
22096  * @expedite: 1 means this request is urgent.
22097  *
22098  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
22099  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
22100  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
22101  *
22102  * Note: ndlp is only used on SCSI side for RRQ testing.
22103  *       The caller should pass NULL for ndlp on NVME side.
22104  *
22105  * Return codes:
22106  *   NULL - Error
22107  *   Pointer to lpfc_io_buf - Success
22108  **/
22109 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
22110                                     struct lpfc_nodelist *ndlp,
22111                                     u32 hwqid, int expedite)
22112 {
22113         struct lpfc_sli4_hdw_queue *qp;
22114         unsigned long iflag;
22115         struct lpfc_io_buf *lpfc_cmd;
22116
22117         qp = &phba->sli4_hba.hdwq[hwqid];
22118         lpfc_cmd = NULL;
22119         if (!qp) {
22120                 lpfc_printf_log(phba, KERN_WARNING,
22121                                 LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22122                                 "5555 NULL qp for hwqid  x%x\n", hwqid);
22123                 return lpfc_cmd;
22124         }
22125
22126         if (phba->cfg_xri_rebalancing)
22127                 lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
22128                         phba, ndlp, hwqid, expedite);
22129         else {
22130                 lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
22131                                           qp, alloc_xri_get);
22132                 if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
22133                         lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22134                 if (!lpfc_cmd) {
22135                         lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
22136                                           qp, alloc_xri_put);
22137                         list_splice(&qp->lpfc_io_buf_list_put,
22138                                     &qp->lpfc_io_buf_list_get);
22139                         qp->get_io_bufs += qp->put_io_bufs;
22140                         INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
22141                         qp->put_io_bufs = 0;
22142                         spin_unlock(&qp->io_buf_list_put_lock);
22143                         if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
22144                             expedite)
22145                                 lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22146                 }
22147                 spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
22148         }
22149
22150         return lpfc_cmd;
22151 }
22152
22153 /**
22154  * lpfc_read_object - Retrieve object data from HBA
22155  * @phba: The HBA for which this call is being executed.
22156  * @rdobject: Pathname of object data we want to read.
22157  * @datap: Pointer to where data will be copied to.
22158  * @datasz: size of data area
22159  *
22160  * This routine is limited to object sizes of LPFC_BPL_SIZE (1024) or less.
22161  * The data will be truncated if datasz is not large enough.
22162  * Version 1 is not supported with Embedded mbox cmd, so we must use version 0.
22163  * Returns the actual bytes read from the object.
22164  */
22165 int
22166 lpfc_read_object(struct lpfc_hba *phba, char *rdobject, uint32_t *datap,
22167                  uint32_t datasz)
22168 {
22169         struct lpfc_mbx_read_object *read_object;
22170         LPFC_MBOXQ_t *mbox;
22171         int rc, length, eof, j, byte_cnt = 0;
22172         uint32_t shdr_status, shdr_add_status;
22173         union lpfc_sli4_cfg_shdr *shdr;
22174         struct lpfc_dmabuf *pcmd;
22175         u32 rd_object_name[LPFC_MBX_OBJECT_NAME_LEN_DW] = {0};
22176
22177         /* sanity check on queue memory */
22178         if (!datap)
22179                 return -ENODEV;
22180
22181         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
22182         if (!mbox)
22183                 return -ENOMEM;
22184         length = (sizeof(struct lpfc_mbx_read_object) -
22185                   sizeof(struct lpfc_sli4_cfg_mhdr));
22186         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
22187                          LPFC_MBOX_OPCODE_READ_OBJECT,
22188                          length, LPFC_SLI4_MBX_EMBED);
22189         read_object = &mbox->u.mqe.un.read_object;
22190         shdr = (union lpfc_sli4_cfg_shdr *)&read_object->header.cfg_shdr;
22191
22192         bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_0);
22193         bf_set(lpfc_mbx_rd_object_rlen, &read_object->u.request, datasz);
22194         read_object->u.request.rd_object_offset = 0;
22195         read_object->u.request.rd_object_cnt = 1;
22196
22197         memset((void *)read_object->u.request.rd_object_name, 0,
22198                LPFC_OBJ_NAME_SZ);
22199         scnprintf((char *)rd_object_name, sizeof(rd_object_name), rdobject);
22200         for (j = 0; j < strlen(rdobject); j++)
22201                 read_object->u.request.rd_object_name[j] =
22202                         cpu_to_le32(rd_object_name[j]);
22203
22204         pcmd = kmalloc(sizeof(*pcmd), GFP_KERNEL);
22205         if (pcmd)
22206                 pcmd->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &pcmd->phys);
22207         if (!pcmd || !pcmd->virt) {
22208                 kfree(pcmd);
22209                 mempool_free(mbox, phba->mbox_mem_pool);
22210                 return -ENOMEM;
22211         }
22212         memset((void *)pcmd->virt, 0, LPFC_BPL_SIZE);
22213         read_object->u.request.rd_object_hbuf[0].pa_lo =
22214                 putPaddrLow(pcmd->phys);
22215         read_object->u.request.rd_object_hbuf[0].pa_hi =
22216                 putPaddrHigh(pcmd->phys);
22217         read_object->u.request.rd_object_hbuf[0].length = LPFC_BPL_SIZE;
22218
22219         mbox->vport = phba->pport;
22220         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
22221         mbox->ctx_buf = NULL;
22222         mbox->ctx_ndlp = NULL;
22223
22224         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
22225         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
22226         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
22227
22228         if (shdr_status == STATUS_FAILED &&
22229             shdr_add_status == ADD_STATUS_INVALID_OBJECT_NAME) {
22230                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22231                                 "4674 No port cfg file in FW.\n");
22232                 byte_cnt = -ENOENT;
22233         } else if (shdr_status || shdr_add_status || rc) {
22234                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22235                                 "2625 READ_OBJECT mailbox failed with "
22236                                 "status x%x add_status x%x, mbx status x%x\n",
22237                                 shdr_status, shdr_add_status, rc);
22238                 byte_cnt = -ENXIO;
22239         } else {
22240                 /* Success */
22241                 length = read_object->u.response.rd_object_actual_rlen;
22242                 eof = bf_get(lpfc_mbx_rd_object_eof, &read_object->u.response);
22243                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_CGN_MGMT,
22244                                 "2626 READ_OBJECT Success len %d:%d, EOF %d\n",
22245                                 length, datasz, eof);
22246
22247                 /* Detect the port config file exists but is empty */
22248                 if (!length && eof) {
22249                         byte_cnt = 0;
22250                         goto exit;
22251                 }
22252
22253                 byte_cnt = length;
22254                 lpfc_sli_pcimem_bcopy(pcmd->virt, datap, byte_cnt);
22255         }
22256
22257  exit:
22258         lpfc_mbuf_free(phba, pcmd->virt, pcmd->phys);
22259         kfree(pcmd);
22260         mempool_free(mbox, phba->mbox_mem_pool);
22261         return byte_cnt;
22262 }
22263
22264 /**
22265  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
22266  * @phba: The HBA for which this call is being executed.
22267  * @lpfc_buf: IO buf structure to append the SGL chunk
22268  *
22269  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
22270  * and will allocate an SGL chunk if the pool is empty.
22271  *
22272  * Return codes:
22273  *   NULL - Error
22274  *   Pointer to sli4_hybrid_sgl - Success
22275  **/
22276 struct sli4_hybrid_sgl *
22277 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22278 {
22279         struct sli4_hybrid_sgl *list_entry = NULL;
22280         struct sli4_hybrid_sgl *tmp = NULL;
22281         struct sli4_hybrid_sgl *allocated_sgl = NULL;
22282         struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22283         struct list_head *buf_list = &hdwq->sgl_list;
22284         unsigned long iflags;
22285
22286         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22287
22288         if (likely(!list_empty(buf_list))) {
22289                 /* break off 1 chunk from the sgl_list */
22290                 list_for_each_entry_safe(list_entry, tmp,
22291                                          buf_list, list_node) {
22292                         list_move_tail(&list_entry->list_node,
22293                                        &lpfc_buf->dma_sgl_xtra_list);
22294                         break;
22295                 }
22296         } else {
22297                 /* allocate more */
22298                 spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22299                 tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22300                                    cpu_to_node(hdwq->io_wq->chann));
22301                 if (!tmp) {
22302                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22303                                         "8353 error kmalloc memory for HDWQ "
22304                                         "%d %s\n",
22305                                         lpfc_buf->hdwq_no, __func__);
22306                         return NULL;
22307                 }
22308
22309                 tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
22310                                               GFP_ATOMIC, &tmp->dma_phys_sgl);
22311                 if (!tmp->dma_sgl) {
22312                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22313                                         "8354 error pool_alloc memory for HDWQ "
22314                                         "%d %s\n",
22315                                         lpfc_buf->hdwq_no, __func__);
22316                         kfree(tmp);
22317                         return NULL;
22318                 }
22319
22320                 spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22321                 list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
22322         }
22323
22324         allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
22325                                         struct sli4_hybrid_sgl,
22326                                         list_node);
22327
22328         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22329
22330         return allocated_sgl;
22331 }
22332
22333 /**
22334  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
22335  * @phba: The HBA for which this call is being executed.
22336  * @lpfc_buf: IO buf structure with the SGL chunk
22337  *
22338  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
22339  *
22340  * Return codes:
22341  *   0 - Success
22342  *   -EINVAL - Error
22343  **/
22344 int
22345 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22346 {
22347         int rc = 0;
22348         struct sli4_hybrid_sgl *list_entry = NULL;
22349         struct sli4_hybrid_sgl *tmp = NULL;
22350         struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22351         struct list_head *buf_list = &hdwq->sgl_list;
22352         unsigned long iflags;
22353
22354         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22355
22356         if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
22357                 list_for_each_entry_safe(list_entry, tmp,
22358                                          &lpfc_buf->dma_sgl_xtra_list,
22359                                          list_node) {
22360                         list_move_tail(&list_entry->list_node,
22361                                        buf_list);
22362                 }
22363         } else {
22364                 rc = -EINVAL;
22365         }
22366
22367         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22368         return rc;
22369 }
22370
22371 /**
22372  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
22373  * @phba: phba object
22374  * @hdwq: hdwq to cleanup sgl buff resources on
22375  *
22376  * This routine frees all SGL chunks of hdwq SGL chunk pool.
22377  *
22378  * Return codes:
22379  *   None
22380  **/
22381 void
22382 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
22383                        struct lpfc_sli4_hdw_queue *hdwq)
22384 {
22385         struct list_head *buf_list = &hdwq->sgl_list;
22386         struct sli4_hybrid_sgl *list_entry = NULL;
22387         struct sli4_hybrid_sgl *tmp = NULL;
22388         unsigned long iflags;
22389
22390         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22391
22392         /* Free sgl pool */
22393         list_for_each_entry_safe(list_entry, tmp,
22394                                  buf_list, list_node) {
22395                 dma_pool_free(phba->lpfc_sg_dma_buf_pool,
22396                               list_entry->dma_sgl,
22397                               list_entry->dma_phys_sgl);
22398                 list_del(&list_entry->list_node);
22399                 kfree(list_entry);
22400         }
22401
22402         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22403 }
22404
22405 /**
22406  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
22407  * @phba: The HBA for which this call is being executed.
22408  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
22409  *
22410  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
22411  * and will allocate an CMD/RSP buffer if the pool is empty.
22412  *
22413  * Return codes:
22414  *   NULL - Error
22415  *   Pointer to fcp_cmd_rsp_buf - Success
22416  **/
22417 struct fcp_cmd_rsp_buf *
22418 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22419                               struct lpfc_io_buf *lpfc_buf)
22420 {
22421         struct fcp_cmd_rsp_buf *list_entry = NULL;
22422         struct fcp_cmd_rsp_buf *tmp = NULL;
22423         struct fcp_cmd_rsp_buf *allocated_buf = NULL;
22424         struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22425         struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22426         unsigned long iflags;
22427
22428         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22429
22430         if (likely(!list_empty(buf_list))) {
22431                 /* break off 1 chunk from the list */
22432                 list_for_each_entry_safe(list_entry, tmp,
22433                                          buf_list,
22434                                          list_node) {
22435                         list_move_tail(&list_entry->list_node,
22436                                        &lpfc_buf->dma_cmd_rsp_list);
22437                         break;
22438                 }
22439         } else {
22440                 /* allocate more */
22441                 spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22442                 tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22443                                    cpu_to_node(hdwq->io_wq->chann));
22444                 if (!tmp) {
22445                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22446                                         "8355 error kmalloc memory for HDWQ "
22447                                         "%d %s\n",
22448                                         lpfc_buf->hdwq_no, __func__);
22449                         return NULL;
22450                 }
22451
22452                 tmp->fcp_cmnd = dma_pool_alloc(phba->lpfc_cmd_rsp_buf_pool,
22453                                                 GFP_ATOMIC,
22454                                                 &tmp->fcp_cmd_rsp_dma_handle);
22455
22456                 if (!tmp->fcp_cmnd) {
22457                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22458                                         "8356 error pool_alloc memory for HDWQ "
22459                                         "%d %s\n",
22460                                         lpfc_buf->hdwq_no, __func__);
22461                         kfree(tmp);
22462                         return NULL;
22463                 }
22464
22465                 tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
22466                                 sizeof(struct fcp_cmnd));
22467
22468                 spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22469                 list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
22470         }
22471
22472         allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
22473                                         struct fcp_cmd_rsp_buf,
22474                                         list_node);
22475
22476         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22477
22478         return allocated_buf;
22479 }
22480
22481 /**
22482  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
22483  * @phba: The HBA for which this call is being executed.
22484  * @lpfc_buf: IO buf structure with the CMD/RSP buf
22485  *
22486  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
22487  *
22488  * Return codes:
22489  *   0 - Success
22490  *   -EINVAL - Error
22491  **/
22492 int
22493 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22494                               struct lpfc_io_buf *lpfc_buf)
22495 {
22496         int rc = 0;
22497         struct fcp_cmd_rsp_buf *list_entry = NULL;
22498         struct fcp_cmd_rsp_buf *tmp = NULL;
22499         struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22500         struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22501         unsigned long iflags;
22502
22503         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22504
22505         if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
22506                 list_for_each_entry_safe(list_entry, tmp,
22507                                          &lpfc_buf->dma_cmd_rsp_list,
22508                                          list_node) {
22509                         list_move_tail(&list_entry->list_node,
22510                                        buf_list);
22511                 }
22512         } else {
22513                 rc = -EINVAL;
22514         }
22515
22516         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22517         return rc;
22518 }
22519
22520 /**
22521  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
22522  * @phba: phba object
22523  * @hdwq: hdwq to cleanup cmd rsp buff resources on
22524  *
22525  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
22526  *
22527  * Return codes:
22528  *   None
22529  **/
22530 void
22531 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22532                                struct lpfc_sli4_hdw_queue *hdwq)
22533 {
22534         struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22535         struct fcp_cmd_rsp_buf *list_entry = NULL;
22536         struct fcp_cmd_rsp_buf *tmp = NULL;
22537         unsigned long iflags;
22538
22539         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22540
22541         /* Free cmd_rsp buf pool */
22542         list_for_each_entry_safe(list_entry, tmp,
22543                                  buf_list,
22544                                  list_node) {
22545                 dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
22546                               list_entry->fcp_cmnd,
22547                               list_entry->fcp_cmd_rsp_dma_handle);
22548                 list_del(&list_entry->list_node);
22549                 kfree(list_entry);
22550         }
22551
22552         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22553 }