]> Git Repo - J-linux.git/blob - drivers/scsi/lpfc/lpfc_sli.c
Merge tag 'vfs-6.13-rc7.fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/vfs/vfs
[J-linux.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-2024 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/crash_dump.h>
38 #ifdef CONFIG_X86
39 #include <asm/set_memory.h>
40 #endif
41
42 #include "lpfc_hw4.h"
43 #include "lpfc_hw.h"
44 #include "lpfc_sli.h"
45 #include "lpfc_sli4.h"
46 #include "lpfc_nl.h"
47 #include "lpfc_disc.h"
48 #include "lpfc.h"
49 #include "lpfc_scsi.h"
50 #include "lpfc_nvme.h"
51 #include "lpfc_crtn.h"
52 #include "lpfc_logmsg.h"
53 #include "lpfc_compat.h"
54 #include "lpfc_debugfs.h"
55 #include "lpfc_vport.h"
56 #include "lpfc_version.h"
57
58 /* There are only four IOCB completion types. */
59 typedef enum _lpfc_iocb_type {
60         LPFC_UNKNOWN_IOCB,
61         LPFC_UNSOL_IOCB,
62         LPFC_SOL_IOCB,
63         LPFC_ABORT_IOCB
64 } lpfc_iocb_type;
65
66
67 /* Provide function prototypes local to this module. */
68 static int lpfc_sli_issue_mbox_s4(struct lpfc_hba *, LPFC_MBOXQ_t *,
69                                   uint32_t);
70 static int lpfc_sli4_read_rev(struct lpfc_hba *, LPFC_MBOXQ_t *,
71                               uint8_t *, uint32_t *);
72 static struct lpfc_iocbq *
73 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
74                                   struct lpfc_iocbq *rspiocbq);
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                                      enum lpfc_poll_mode poll_mode);
87 static bool lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba);
88 static bool lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba);
89 static struct lpfc_cqe *lpfc_sli4_cq_get(struct lpfc_queue *q);
90 static void __lpfc_sli4_consume_cqe(struct lpfc_hba *phba,
91                                     struct lpfc_queue *cq,
92                                     struct lpfc_cqe *cqe);
93 static uint16_t lpfc_wqe_bpl2sgl(struct lpfc_hba *phba,
94                                  struct lpfc_iocbq *pwqeq,
95                                  struct lpfc_sglq *sglq);
96
97 union lpfc_wqe128 lpfc_iread_cmd_template;
98 union lpfc_wqe128 lpfc_iwrite_cmd_template;
99 union lpfc_wqe128 lpfc_icmnd_cmd_template;
100
101 /* Setup WQE templates for IOs */
102 void lpfc_wqe_cmd_template(void)
103 {
104         union lpfc_wqe128 *wqe;
105
106         /* IREAD template */
107         wqe = &lpfc_iread_cmd_template;
108         memset(wqe, 0, sizeof(union lpfc_wqe128));
109
110         /* Word 0, 1, 2 - BDE is variable */
111
112         /* Word 3 - cmd_buff_len, payload_offset_len is zero */
113
114         /* Word 4 - total_xfer_len is variable */
115
116         /* Word 5 - is zero */
117
118         /* Word 6 - ctxt_tag, xri_tag is variable */
119
120         /* Word 7 */
121         bf_set(wqe_cmnd, &wqe->fcp_iread.wqe_com, CMD_FCP_IREAD64_WQE);
122         bf_set(wqe_pu, &wqe->fcp_iread.wqe_com, PARM_READ_CHECK);
123         bf_set(wqe_class, &wqe->fcp_iread.wqe_com, CLASS3);
124         bf_set(wqe_ct, &wqe->fcp_iread.wqe_com, SLI4_CT_RPI);
125
126         /* Word 8 - abort_tag is variable */
127
128         /* Word 9  - reqtag is variable */
129
130         /* Word 10 - dbde, wqes is variable */
131         bf_set(wqe_qosd, &wqe->fcp_iread.wqe_com, 0);
132         bf_set(wqe_iod, &wqe->fcp_iread.wqe_com, LPFC_WQE_IOD_READ);
133         bf_set(wqe_lenloc, &wqe->fcp_iread.wqe_com, LPFC_WQE_LENLOC_WORD4);
134         bf_set(wqe_dbde, &wqe->fcp_iread.wqe_com, 0);
135         bf_set(wqe_wqes, &wqe->fcp_iread.wqe_com, 1);
136
137         /* Word 11 - pbde is variable */
138         bf_set(wqe_cmd_type, &wqe->fcp_iread.wqe_com, COMMAND_DATA_IN);
139         bf_set(wqe_cqid, &wqe->fcp_iread.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
140         bf_set(wqe_pbde, &wqe->fcp_iread.wqe_com, 0);
141
142         /* Word 12 - is zero */
143
144         /* Word 13, 14, 15 - PBDE is variable */
145
146         /* IWRITE template */
147         wqe = &lpfc_iwrite_cmd_template;
148         memset(wqe, 0, sizeof(union lpfc_wqe128));
149
150         /* Word 0, 1, 2 - BDE is variable */
151
152         /* Word 3 - cmd_buff_len, payload_offset_len is zero */
153
154         /* Word 4 - total_xfer_len is variable */
155
156         /* Word 5 - initial_xfer_len is variable */
157
158         /* Word 6 - ctxt_tag, xri_tag is variable */
159
160         /* Word 7 */
161         bf_set(wqe_cmnd, &wqe->fcp_iwrite.wqe_com, CMD_FCP_IWRITE64_WQE);
162         bf_set(wqe_pu, &wqe->fcp_iwrite.wqe_com, PARM_READ_CHECK);
163         bf_set(wqe_class, &wqe->fcp_iwrite.wqe_com, CLASS3);
164         bf_set(wqe_ct, &wqe->fcp_iwrite.wqe_com, SLI4_CT_RPI);
165
166         /* Word 8 - abort_tag is variable */
167
168         /* Word 9  - reqtag is variable */
169
170         /* Word 10 - dbde, wqes is variable */
171         bf_set(wqe_qosd, &wqe->fcp_iwrite.wqe_com, 0);
172         bf_set(wqe_iod, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_IOD_WRITE);
173         bf_set(wqe_lenloc, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_LENLOC_WORD4);
174         bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
175         bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
176
177         /* Word 11 - pbde is variable */
178         bf_set(wqe_cmd_type, &wqe->fcp_iwrite.wqe_com, COMMAND_DATA_OUT);
179         bf_set(wqe_cqid, &wqe->fcp_iwrite.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
180         bf_set(wqe_pbde, &wqe->fcp_iwrite.wqe_com, 0);
181
182         /* Word 12 - is zero */
183
184         /* Word 13, 14, 15 - PBDE is variable */
185
186         /* ICMND template */
187         wqe = &lpfc_icmnd_cmd_template;
188         memset(wqe, 0, sizeof(union lpfc_wqe128));
189
190         /* Word 0, 1, 2 - BDE is variable */
191
192         /* Word 3 - payload_offset_len is variable */
193
194         /* Word 4, 5 - is zero */
195
196         /* Word 6 - ctxt_tag, xri_tag is variable */
197
198         /* Word 7 */
199         bf_set(wqe_cmnd, &wqe->fcp_icmd.wqe_com, CMD_FCP_ICMND64_WQE);
200         bf_set(wqe_pu, &wqe->fcp_icmd.wqe_com, 0);
201         bf_set(wqe_class, &wqe->fcp_icmd.wqe_com, CLASS3);
202         bf_set(wqe_ct, &wqe->fcp_icmd.wqe_com, SLI4_CT_RPI);
203
204         /* Word 8 - abort_tag is variable */
205
206         /* Word 9  - reqtag is variable */
207
208         /* Word 10 - dbde, wqes is variable */
209         bf_set(wqe_qosd, &wqe->fcp_icmd.wqe_com, 1);
210         bf_set(wqe_iod, &wqe->fcp_icmd.wqe_com, LPFC_WQE_IOD_NONE);
211         bf_set(wqe_lenloc, &wqe->fcp_icmd.wqe_com, LPFC_WQE_LENLOC_NONE);
212         bf_set(wqe_dbde, &wqe->fcp_icmd.wqe_com, 0);
213         bf_set(wqe_wqes, &wqe->fcp_icmd.wqe_com, 1);
214
215         /* Word 11 */
216         bf_set(wqe_cmd_type, &wqe->fcp_icmd.wqe_com, COMMAND_DATA_IN);
217         bf_set(wqe_cqid, &wqe->fcp_icmd.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
218         bf_set(wqe_pbde, &wqe->fcp_icmd.wqe_com, 0);
219
220         /* Word 12, 13, 14, 15 - is zero */
221 }
222
223 #if defined(CONFIG_64BIT) && defined(__LITTLE_ENDIAN)
224 /**
225  * lpfc_sli4_pcimem_bcopy - SLI4 memory copy function
226  * @srcp: Source memory pointer.
227  * @destp: Destination memory pointer.
228  * @cnt: Number of words required to be copied.
229  *       Must be a multiple of sizeof(uint64_t)
230  *
231  * This function is used for copying data between driver memory
232  * and the SLI WQ. This function also changes the endianness
233  * of each word if native endianness is different from SLI
234  * endianness. This function can be called with or without
235  * lock.
236  **/
237 static void
238 lpfc_sli4_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
239 {
240         uint64_t *src = srcp;
241         uint64_t *dest = destp;
242         int i;
243
244         for (i = 0; i < (int)cnt; i += sizeof(uint64_t))
245                 *dest++ = *src++;
246 }
247 #else
248 #define lpfc_sli4_pcimem_bcopy(a, b, c) lpfc_sli_pcimem_bcopy(a, b, c)
249 #endif
250
251 /**
252  * lpfc_sli4_wq_put - Put a Work Queue Entry on an Work Queue
253  * @q: The Work Queue to operate on.
254  * @wqe: The work Queue Entry to put on the Work queue.
255  *
256  * This routine will copy the contents of @wqe to the next available entry on
257  * the @q. This function will then ring the Work Queue Doorbell to signal the
258  * HBA to start processing the Work Queue Entry. This function returns 0 if
259  * successful. If no entries are available on @q then this function will return
260  * -ENOMEM.
261  * The caller is expected to hold the hbalock when calling this routine.
262  **/
263 static int
264 lpfc_sli4_wq_put(struct lpfc_queue *q, union lpfc_wqe128 *wqe)
265 {
266         union lpfc_wqe *temp_wqe;
267         struct lpfc_register doorbell;
268         uint32_t host_index;
269         uint32_t idx;
270         uint32_t i = 0;
271         uint8_t *tmp;
272         u32 if_type;
273
274         /* sanity check on queue memory */
275         if (unlikely(!q))
276                 return -ENOMEM;
277
278         temp_wqe = lpfc_sli4_qe(q, q->host_index);
279
280         /* If the host has not yet processed the next entry then we are done */
281         idx = ((q->host_index + 1) % q->entry_count);
282         if (idx == q->hba_index) {
283                 q->WQ_overflow++;
284                 return -EBUSY;
285         }
286         q->WQ_posted++;
287         /* set consumption flag every once in a while */
288         if (!((q->host_index + 1) % q->notify_interval))
289                 bf_set(wqe_wqec, &wqe->generic.wqe_com, 1);
290         else
291                 bf_set(wqe_wqec, &wqe->generic.wqe_com, 0);
292         if (q->phba->sli3_options & LPFC_SLI4_PHWQ_ENABLED)
293                 bf_set(wqe_wqid, &wqe->generic.wqe_com, q->queue_id);
294         lpfc_sli4_pcimem_bcopy(wqe, temp_wqe, q->entry_size);
295         if (q->dpp_enable && q->phba->cfg_enable_dpp) {
296                 /* write to DPP aperture taking advatage of Combined Writes */
297                 tmp = (uint8_t *)temp_wqe;
298 #ifdef __raw_writeq
299                 for (i = 0; i < q->entry_size; i += sizeof(uint64_t))
300                         __raw_writeq(*((uint64_t *)(tmp + i)),
301                                         q->dpp_regaddr + i);
302 #else
303                 for (i = 0; i < q->entry_size; i += sizeof(uint32_t))
304                         __raw_writel(*((uint32_t *)(tmp + i)),
305                                         q->dpp_regaddr + i);
306 #endif
307         }
308         /* ensure WQE bcopy and DPP flushed before doorbell write */
309         wmb();
310
311         /* Update the host index before invoking device */
312         host_index = q->host_index;
313
314         q->host_index = idx;
315
316         /* Ring Doorbell */
317         doorbell.word0 = 0;
318         if (q->db_format == LPFC_DB_LIST_FORMAT) {
319                 if (q->dpp_enable && q->phba->cfg_enable_dpp) {
320                         bf_set(lpfc_if6_wq_db_list_fm_num_posted, &doorbell, 1);
321                         bf_set(lpfc_if6_wq_db_list_fm_dpp, &doorbell, 1);
322                         bf_set(lpfc_if6_wq_db_list_fm_dpp_id, &doorbell,
323                             q->dpp_id);
324                         bf_set(lpfc_if6_wq_db_list_fm_id, &doorbell,
325                             q->queue_id);
326                 } else {
327                         bf_set(lpfc_wq_db_list_fm_num_posted, &doorbell, 1);
328                         bf_set(lpfc_wq_db_list_fm_id, &doorbell, q->queue_id);
329
330                         /* Leave bits <23:16> clear for if_type 6 dpp */
331                         if_type = bf_get(lpfc_sli_intf_if_type,
332                                          &q->phba->sli4_hba.sli_intf);
333                         if (if_type != LPFC_SLI_INTF_IF_TYPE_6)
334                                 bf_set(lpfc_wq_db_list_fm_index, &doorbell,
335                                        host_index);
336                 }
337         } else if (q->db_format == LPFC_DB_RING_FORMAT) {
338                 bf_set(lpfc_wq_db_ring_fm_num_posted, &doorbell, 1);
339                 bf_set(lpfc_wq_db_ring_fm_id, &doorbell, q->queue_id);
340         } else {
341                 return -EINVAL;
342         }
343         writel(doorbell.word0, q->db_regaddr);
344
345         return 0;
346 }
347
348 /**
349  * lpfc_sli4_wq_release - Updates internal hba index for WQ
350  * @q: The Work Queue to operate on.
351  * @index: The index to advance the hba index to.
352  *
353  * This routine will update the HBA index of a queue to reflect consumption of
354  * Work Queue Entries by the HBA. When the HBA indicates that it has consumed
355  * an entry the host calls this function to update the queue's internal
356  * pointers.
357  **/
358 static void
359 lpfc_sli4_wq_release(struct lpfc_queue *q, uint32_t index)
360 {
361         /* sanity check on queue memory */
362         if (unlikely(!q))
363                 return;
364
365         q->hba_index = index;
366 }
367
368 /**
369  * lpfc_sli4_mq_put - Put a Mailbox Queue Entry on an Mailbox Queue
370  * @q: The Mailbox Queue to operate on.
371  * @mqe: The Mailbox Queue Entry to put on the Work queue.
372  *
373  * This routine will copy the contents of @mqe to the next available entry on
374  * the @q. This function will then ring the Work Queue Doorbell to signal the
375  * HBA to start processing the Work Queue Entry. This function returns 0 if
376  * successful. If no entries are available on @q then this function will return
377  * -ENOMEM.
378  * The caller is expected to hold the hbalock when calling this routine.
379  **/
380 static uint32_t
381 lpfc_sli4_mq_put(struct lpfc_queue *q, struct lpfc_mqe *mqe)
382 {
383         struct lpfc_mqe *temp_mqe;
384         struct lpfc_register doorbell;
385
386         /* sanity check on queue memory */
387         if (unlikely(!q))
388                 return -ENOMEM;
389         temp_mqe = lpfc_sli4_qe(q, q->host_index);
390
391         /* If the host has not yet processed the next entry then we are done */
392         if (((q->host_index + 1) % q->entry_count) == q->hba_index)
393                 return -ENOMEM;
394         lpfc_sli4_pcimem_bcopy(mqe, temp_mqe, q->entry_size);
395         /* Save off the mailbox pointer for completion */
396         q->phba->mbox = (MAILBOX_t *)temp_mqe;
397
398         /* Update the host index before invoking device */
399         q->host_index = ((q->host_index + 1) % q->entry_count);
400
401         /* Ring Doorbell */
402         doorbell.word0 = 0;
403         bf_set(lpfc_mq_doorbell_num_posted, &doorbell, 1);
404         bf_set(lpfc_mq_doorbell_id, &doorbell, q->queue_id);
405         writel(doorbell.word0, q->phba->sli4_hba.MQDBregaddr);
406         return 0;
407 }
408
409 /**
410  * lpfc_sli4_mq_release - Updates internal hba index for MQ
411  * @q: The Mailbox Queue to operate on.
412  *
413  * This routine will update the HBA index of a queue to reflect consumption of
414  * a Mailbox Queue Entry by the HBA. When the HBA indicates that it has consumed
415  * an entry the host calls this function to update the queue's internal
416  * pointers. This routine returns the number of entries that were consumed by
417  * the HBA.
418  **/
419 static uint32_t
420 lpfc_sli4_mq_release(struct lpfc_queue *q)
421 {
422         /* sanity check on queue memory */
423         if (unlikely(!q))
424                 return 0;
425
426         /* Clear the mailbox pointer for completion */
427         q->phba->mbox = NULL;
428         q->hba_index = ((q->hba_index + 1) % q->entry_count);
429         return 1;
430 }
431
432 /**
433  * lpfc_sli4_eq_get - Gets the next valid EQE from a EQ
434  * @q: The Event Queue to get the first valid EQE from
435  *
436  * This routine will get the first valid Event Queue Entry from @q, update
437  * the queue's internal hba index, and return the EQE. If no valid EQEs are in
438  * the Queue (no more work to do), or the Queue is full of EQEs that have been
439  * processed, but not popped back to the HBA then this routine will return NULL.
440  **/
441 static struct lpfc_eqe *
442 lpfc_sli4_eq_get(struct lpfc_queue *q)
443 {
444         struct lpfc_eqe *eqe;
445
446         /* sanity check on queue memory */
447         if (unlikely(!q))
448                 return NULL;
449         eqe = lpfc_sli4_qe(q, q->host_index);
450
451         /* If the next EQE is not valid then we are done */
452         if (bf_get_le32(lpfc_eqe_valid, eqe) != q->qe_valid)
453                 return NULL;
454
455         /*
456          * insert barrier for instruction interlock : data from the hardware
457          * must have the valid bit checked before it can be copied and acted
458          * upon. Speculative instructions were allowing a bcopy at the start
459          * of lpfc_sli4_fp_handle_wcqe(), which is called immediately
460          * after our return, to copy data before the valid bit check above
461          * was done. As such, some of the copied data was stale. The barrier
462          * ensures the check is before any data is copied.
463          */
464         mb();
465         return eqe;
466 }
467
468 /**
469  * lpfc_sli4_eq_clr_intr - Turn off interrupts from this EQ
470  * @q: The Event Queue to disable interrupts
471  *
472  **/
473 void
474 lpfc_sli4_eq_clr_intr(struct lpfc_queue *q)
475 {
476         struct lpfc_register doorbell;
477
478         doorbell.word0 = 0;
479         bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
480         bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
481         bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
482                 (q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
483         bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
484         writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
485 }
486
487 /**
488  * lpfc_sli4_if6_eq_clr_intr - Turn off interrupts from this EQ
489  * @q: The Event Queue to disable interrupts
490  *
491  **/
492 void
493 lpfc_sli4_if6_eq_clr_intr(struct lpfc_queue *q)
494 {
495         struct lpfc_register doorbell;
496
497         doorbell.word0 = 0;
498         bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
499         writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
500 }
501
502 /**
503  * lpfc_sli4_write_eq_db - write EQ DB for eqe's consumed or arm state
504  * @phba: adapter with EQ
505  * @q: The Event Queue that the host has completed processing for.
506  * @count: Number of elements that have been consumed
507  * @arm: Indicates whether the host wants to arms this CQ.
508  *
509  * This routine will notify the HBA, by ringing the doorbell, that count
510  * number of EQEs have been processed. The @arm parameter indicates whether
511  * the queue should be rearmed when ringing the doorbell.
512  **/
513 void
514 lpfc_sli4_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
515                      uint32_t count, bool arm)
516 {
517         struct lpfc_register doorbell;
518
519         /* sanity check on queue memory */
520         if (unlikely(!q || (count == 0 && !arm)))
521                 return;
522
523         /* ring doorbell for number popped */
524         doorbell.word0 = 0;
525         if (arm) {
526                 bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
527                 bf_set(lpfc_eqcq_doorbell_eqci, &doorbell, 1);
528         }
529         bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
530         bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_EVENT);
531         bf_set(lpfc_eqcq_doorbell_eqid_hi, &doorbell,
532                         (q->queue_id >> LPFC_EQID_HI_FIELD_SHIFT));
533         bf_set(lpfc_eqcq_doorbell_eqid_lo, &doorbell, q->queue_id);
534         writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
535         /* PCI read to flush PCI pipeline on re-arming for INTx mode */
536         if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
537                 readl(q->phba->sli4_hba.EQDBregaddr);
538 }
539
540 /**
541  * lpfc_sli4_if6_write_eq_db - write EQ DB for eqe's consumed or arm state
542  * @phba: adapter with EQ
543  * @q: The Event Queue that the host has completed processing for.
544  * @count: Number of elements that have been consumed
545  * @arm: Indicates whether the host wants to arms this CQ.
546  *
547  * This routine will notify the HBA, by ringing the doorbell, that count
548  * number of EQEs have been processed. The @arm parameter indicates whether
549  * the queue should be rearmed when ringing the doorbell.
550  **/
551 void
552 lpfc_sli4_if6_write_eq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
553                           uint32_t count, bool arm)
554 {
555         struct lpfc_register doorbell;
556
557         /* sanity check on queue memory */
558         if (unlikely(!q || (count == 0 && !arm)))
559                 return;
560
561         /* ring doorbell for number popped */
562         doorbell.word0 = 0;
563         if (arm)
564                 bf_set(lpfc_if6_eq_doorbell_arm, &doorbell, 1);
565         bf_set(lpfc_if6_eq_doorbell_num_released, &doorbell, count);
566         bf_set(lpfc_if6_eq_doorbell_eqid, &doorbell, q->queue_id);
567         writel(doorbell.word0, q->phba->sli4_hba.EQDBregaddr);
568         /* PCI read to flush PCI pipeline on re-arming for INTx mode */
569         if ((q->phba->intr_type == INTx) && (arm == LPFC_QUEUE_REARM))
570                 readl(q->phba->sli4_hba.EQDBregaddr);
571 }
572
573 static void
574 __lpfc_sli4_consume_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
575                         struct lpfc_eqe *eqe)
576 {
577         if (!phba->sli4_hba.pc_sli4_params.eqav)
578                 bf_set_le32(lpfc_eqe_valid, eqe, 0);
579
580         eq->host_index = ((eq->host_index + 1) % eq->entry_count);
581
582         /* if the index wrapped around, toggle the valid bit */
583         if (phba->sli4_hba.pc_sli4_params.eqav && !eq->host_index)
584                 eq->qe_valid = (eq->qe_valid) ? 0 : 1;
585 }
586
587 static void
588 lpfc_sli4_eqcq_flush(struct lpfc_hba *phba, struct lpfc_queue *eq)
589 {
590         struct lpfc_eqe *eqe = NULL;
591         u32 eq_count = 0, cq_count = 0;
592         struct lpfc_cqe *cqe = NULL;
593         struct lpfc_queue *cq = NULL, *childq = NULL;
594         int cqid = 0;
595
596         /* walk all the EQ entries and drop on the floor */
597         eqe = lpfc_sli4_eq_get(eq);
598         while (eqe) {
599                 /* Get the reference to the corresponding CQ */
600                 cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
601                 cq = NULL;
602
603                 list_for_each_entry(childq, &eq->child_list, list) {
604                         if (childq->queue_id == cqid) {
605                                 cq = childq;
606                                 break;
607                         }
608                 }
609                 /* If CQ is valid, iterate through it and drop all the CQEs */
610                 if (cq) {
611                         cqe = lpfc_sli4_cq_get(cq);
612                         while (cqe) {
613                                 __lpfc_sli4_consume_cqe(phba, cq, cqe);
614                                 cq_count++;
615                                 cqe = lpfc_sli4_cq_get(cq);
616                         }
617                         /* Clear and re-arm the CQ */
618                         phba->sli4_hba.sli4_write_cq_db(phba, cq, cq_count,
619                             LPFC_QUEUE_REARM);
620                         cq_count = 0;
621                 }
622                 __lpfc_sli4_consume_eqe(phba, eq, eqe);
623                 eq_count++;
624                 eqe = lpfc_sli4_eq_get(eq);
625         }
626
627         /* Clear and re-arm the EQ */
628         phba->sli4_hba.sli4_write_eq_db(phba, eq, eq_count, LPFC_QUEUE_REARM);
629 }
630
631 static int
632 lpfc_sli4_process_eq(struct lpfc_hba *phba, struct lpfc_queue *eq,
633                      u8 rearm, enum lpfc_poll_mode poll_mode)
634 {
635         struct lpfc_eqe *eqe;
636         int count = 0, consumed = 0;
637
638         if (cmpxchg(&eq->queue_claimed, 0, 1) != 0)
639                 goto rearm_and_exit;
640
641         eqe = lpfc_sli4_eq_get(eq);
642         while (eqe) {
643                 lpfc_sli4_hba_handle_eqe(phba, eq, eqe, poll_mode);
644                 __lpfc_sli4_consume_eqe(phba, eq, eqe);
645
646                 consumed++;
647                 if (!(++count % eq->max_proc_limit))
648                         break;
649
650                 if (!(count % eq->notify_interval)) {
651                         phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed,
652                                                         LPFC_QUEUE_NOARM);
653                         consumed = 0;
654                 }
655
656                 eqe = lpfc_sli4_eq_get(eq);
657         }
658         eq->EQ_processed += count;
659
660         /* Track the max number of EQEs processed in 1 intr */
661         if (count > eq->EQ_max_eqe)
662                 eq->EQ_max_eqe = count;
663
664         xchg(&eq->queue_claimed, 0);
665
666 rearm_and_exit:
667         /* Always clear the EQ. */
668         phba->sli4_hba.sli4_write_eq_db(phba, eq, consumed, rearm);
669
670         return count;
671 }
672
673 /**
674  * lpfc_sli4_cq_get - Gets the next valid CQE from a CQ
675  * @q: The Completion Queue to get the first valid CQE from
676  *
677  * This routine will get the first valid Completion Queue Entry from @q, update
678  * the queue's internal hba index, and return the CQE. If no valid CQEs are in
679  * the Queue (no more work to do), or the Queue is full of CQEs that have been
680  * processed, but not popped back to the HBA then this routine will return NULL.
681  **/
682 static struct lpfc_cqe *
683 lpfc_sli4_cq_get(struct lpfc_queue *q)
684 {
685         struct lpfc_cqe *cqe;
686
687         /* sanity check on queue memory */
688         if (unlikely(!q))
689                 return NULL;
690         cqe = lpfc_sli4_qe(q, q->host_index);
691
692         /* If the next CQE is not valid then we are done */
693         if (bf_get_le32(lpfc_cqe_valid, cqe) != q->qe_valid)
694                 return NULL;
695
696         /*
697          * insert barrier for instruction interlock : data from the hardware
698          * must have the valid bit checked before it can be copied and acted
699          * upon. Given what was seen in lpfc_sli4_cq_get() of speculative
700          * instructions allowing action on content before valid bit checked,
701          * add barrier here as well. May not be needed as "content" is a
702          * single 32-bit entity here (vs multi word structure for cq's).
703          */
704         mb();
705         return cqe;
706 }
707
708 static void
709 __lpfc_sli4_consume_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
710                         struct lpfc_cqe *cqe)
711 {
712         if (!phba->sli4_hba.pc_sli4_params.cqav)
713                 bf_set_le32(lpfc_cqe_valid, cqe, 0);
714
715         cq->host_index = ((cq->host_index + 1) % cq->entry_count);
716
717         /* if the index wrapped around, toggle the valid bit */
718         if (phba->sli4_hba.pc_sli4_params.cqav && !cq->host_index)
719                 cq->qe_valid = (cq->qe_valid) ? 0 : 1;
720 }
721
722 /**
723  * lpfc_sli4_write_cq_db - write cq DB for entries consumed or arm state.
724  * @phba: the adapter with the CQ
725  * @q: The Completion Queue that the host has completed processing for.
726  * @count: the number of elements that were consumed
727  * @arm: Indicates whether the host wants to arms this CQ.
728  *
729  * This routine will notify the HBA, by ringing the doorbell, that the
730  * CQEs have been processed. The @arm parameter specifies whether the
731  * queue should be rearmed when ringing the doorbell.
732  **/
733 void
734 lpfc_sli4_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
735                      uint32_t count, bool arm)
736 {
737         struct lpfc_register doorbell;
738
739         /* sanity check on queue memory */
740         if (unlikely(!q || (count == 0 && !arm)))
741                 return;
742
743         /* ring doorbell for number popped */
744         doorbell.word0 = 0;
745         if (arm)
746                 bf_set(lpfc_eqcq_doorbell_arm, &doorbell, 1);
747         bf_set(lpfc_eqcq_doorbell_num_released, &doorbell, count);
748         bf_set(lpfc_eqcq_doorbell_qt, &doorbell, LPFC_QUEUE_TYPE_COMPLETION);
749         bf_set(lpfc_eqcq_doorbell_cqid_hi, &doorbell,
750                         (q->queue_id >> LPFC_CQID_HI_FIELD_SHIFT));
751         bf_set(lpfc_eqcq_doorbell_cqid_lo, &doorbell, q->queue_id);
752         writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
753 }
754
755 /**
756  * lpfc_sli4_if6_write_cq_db - write cq DB for entries consumed or arm state.
757  * @phba: the adapter with the CQ
758  * @q: The Completion Queue that the host has completed processing for.
759  * @count: the number of elements that were consumed
760  * @arm: Indicates whether the host wants to arms this CQ.
761  *
762  * This routine will notify the HBA, by ringing the doorbell, that the
763  * CQEs have been processed. The @arm parameter specifies whether the
764  * queue should be rearmed when ringing the doorbell.
765  **/
766 void
767 lpfc_sli4_if6_write_cq_db(struct lpfc_hba *phba, struct lpfc_queue *q,
768                          uint32_t count, bool arm)
769 {
770         struct lpfc_register doorbell;
771
772         /* sanity check on queue memory */
773         if (unlikely(!q || (count == 0 && !arm)))
774                 return;
775
776         /* ring doorbell for number popped */
777         doorbell.word0 = 0;
778         if (arm)
779                 bf_set(lpfc_if6_cq_doorbell_arm, &doorbell, 1);
780         bf_set(lpfc_if6_cq_doorbell_num_released, &doorbell, count);
781         bf_set(lpfc_if6_cq_doorbell_cqid, &doorbell, q->queue_id);
782         writel(doorbell.word0, q->phba->sli4_hba.CQDBregaddr);
783 }
784
785 /*
786  * lpfc_sli4_rq_put - Put a Receive Buffer Queue Entry on a Receive Queue
787  *
788  * This routine will copy the contents of @wqe to the next available entry on
789  * the @q. This function will then ring the Receive Queue Doorbell to signal the
790  * HBA to start processing the Receive Queue Entry. This function returns the
791  * index that the rqe was copied to if successful. If no entries are available
792  * on @q then this function will return -ENOMEM.
793  * The caller is expected to hold the hbalock when calling this routine.
794  **/
795 int
796 lpfc_sli4_rq_put(struct lpfc_queue *hq, struct lpfc_queue *dq,
797                  struct lpfc_rqe *hrqe, struct lpfc_rqe *drqe)
798 {
799         struct lpfc_rqe *temp_hrqe;
800         struct lpfc_rqe *temp_drqe;
801         struct lpfc_register doorbell;
802         int hq_put_index;
803         int dq_put_index;
804
805         /* sanity check on queue memory */
806         if (unlikely(!hq) || unlikely(!dq))
807                 return -ENOMEM;
808         hq_put_index = hq->host_index;
809         dq_put_index = dq->host_index;
810         temp_hrqe = lpfc_sli4_qe(hq, hq_put_index);
811         temp_drqe = lpfc_sli4_qe(dq, dq_put_index);
812
813         if (hq->type != LPFC_HRQ || dq->type != LPFC_DRQ)
814                 return -EINVAL;
815         if (hq_put_index != dq_put_index)
816                 return -EINVAL;
817         /* If the host has not yet processed the next entry then we are done */
818         if (((hq_put_index + 1) % hq->entry_count) == hq->hba_index)
819                 return -EBUSY;
820         lpfc_sli4_pcimem_bcopy(hrqe, temp_hrqe, hq->entry_size);
821         lpfc_sli4_pcimem_bcopy(drqe, temp_drqe, dq->entry_size);
822
823         /* Update the host index to point to the next slot */
824         hq->host_index = ((hq_put_index + 1) % hq->entry_count);
825         dq->host_index = ((dq_put_index + 1) % dq->entry_count);
826         hq->RQ_buf_posted++;
827
828         /* Ring The Header Receive Queue Doorbell */
829         if (!(hq->host_index % hq->notify_interval)) {
830                 doorbell.word0 = 0;
831                 if (hq->db_format == LPFC_DB_RING_FORMAT) {
832                         bf_set(lpfc_rq_db_ring_fm_num_posted, &doorbell,
833                                hq->notify_interval);
834                         bf_set(lpfc_rq_db_ring_fm_id, &doorbell, hq->queue_id);
835                 } else if (hq->db_format == LPFC_DB_LIST_FORMAT) {
836                         bf_set(lpfc_rq_db_list_fm_num_posted, &doorbell,
837                                hq->notify_interval);
838                         bf_set(lpfc_rq_db_list_fm_index, &doorbell,
839                                hq->host_index);
840                         bf_set(lpfc_rq_db_list_fm_id, &doorbell, hq->queue_id);
841                 } else {
842                         return -EINVAL;
843                 }
844                 writel(doorbell.word0, hq->db_regaddr);
845         }
846         return hq_put_index;
847 }
848
849 /*
850  * lpfc_sli4_rq_release - Updates internal hba index for RQ
851  *
852  * This routine will update the HBA index of a queue to reflect consumption of
853  * one Receive Queue Entry by the HBA. When the HBA indicates that it has
854  * consumed an entry the host calls this function to update the queue's
855  * internal pointers. This routine returns the number of entries that were
856  * consumed by the HBA.
857  **/
858 static uint32_t
859 lpfc_sli4_rq_release(struct lpfc_queue *hq, struct lpfc_queue *dq)
860 {
861         /* sanity check on queue memory */
862         if (unlikely(!hq) || unlikely(!dq))
863                 return 0;
864
865         if ((hq->type != LPFC_HRQ) || (dq->type != LPFC_DRQ))
866                 return 0;
867         hq->hba_index = ((hq->hba_index + 1) % hq->entry_count);
868         dq->hba_index = ((dq->hba_index + 1) % dq->entry_count);
869         return 1;
870 }
871
872 /**
873  * lpfc_cmd_iocb - Get next command iocb entry in the ring
874  * @phba: Pointer to HBA context object.
875  * @pring: Pointer to driver SLI ring object.
876  *
877  * This function returns pointer to next command iocb entry
878  * in the command ring. The caller must hold hbalock to prevent
879  * other threads consume the next command iocb.
880  * SLI-2/SLI-3 provide different sized iocbs.
881  **/
882 static inline IOCB_t *
883 lpfc_cmd_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
884 {
885         return (IOCB_t *) (((char *) pring->sli.sli3.cmdringaddr) +
886                            pring->sli.sli3.cmdidx * phba->iocb_cmd_size);
887 }
888
889 /**
890  * lpfc_resp_iocb - Get next response iocb entry in the ring
891  * @phba: Pointer to HBA context object.
892  * @pring: Pointer to driver SLI ring object.
893  *
894  * This function returns pointer to next response iocb entry
895  * in the response ring. The caller must hold hbalock to make sure
896  * that no other thread consume the next response iocb.
897  * SLI-2/SLI-3 provide different sized iocbs.
898  **/
899 static inline IOCB_t *
900 lpfc_resp_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
901 {
902         return (IOCB_t *) (((char *) pring->sli.sli3.rspringaddr) +
903                            pring->sli.sli3.rspidx * phba->iocb_rsp_size);
904 }
905
906 /**
907  * __lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
908  * @phba: Pointer to HBA context object.
909  *
910  * This function is called with hbalock held. This function
911  * allocates a new driver iocb object from the iocb pool. If the
912  * allocation is successful, it returns pointer to the newly
913  * allocated iocb object else it returns NULL.
914  **/
915 struct lpfc_iocbq *
916 __lpfc_sli_get_iocbq(struct lpfc_hba *phba)
917 {
918         struct list_head *lpfc_iocb_list = &phba->lpfc_iocb_list;
919         struct lpfc_iocbq * iocbq = NULL;
920
921         lockdep_assert_held(&phba->hbalock);
922
923         list_remove_head(lpfc_iocb_list, iocbq, struct lpfc_iocbq, list);
924         if (iocbq)
925                 phba->iocb_cnt++;
926         if (phba->iocb_cnt > phba->iocb_max)
927                 phba->iocb_max = phba->iocb_cnt;
928         return iocbq;
929 }
930
931 /**
932  * __lpfc_clear_active_sglq - Remove the active sglq for this XRI.
933  * @phba: Pointer to HBA context object.
934  * @xritag: XRI value.
935  *
936  * This function clears the sglq pointer from the array of active
937  * sglq's. The xritag that is passed in is used to index into the
938  * array. Before the xritag can be used it needs to be adjusted
939  * by subtracting the xribase.
940  *
941  * Returns sglq ponter = success, NULL = Failure.
942  **/
943 struct lpfc_sglq *
944 __lpfc_clear_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
945 {
946         struct lpfc_sglq *sglq;
947
948         sglq = phba->sli4_hba.lpfc_sglq_active_list[xritag];
949         phba->sli4_hba.lpfc_sglq_active_list[xritag] = NULL;
950         return sglq;
951 }
952
953 /**
954  * __lpfc_get_active_sglq - Get the active sglq for this XRI.
955  * @phba: Pointer to HBA context object.
956  * @xritag: XRI value.
957  *
958  * This function returns the sglq pointer from the array of active
959  * sglq's. The xritag that is passed in is used to index into the
960  * array. Before the xritag can be used it needs to be adjusted
961  * by subtracting the xribase.
962  *
963  * Returns sglq ponter = success, NULL = Failure.
964  **/
965 struct lpfc_sglq *
966 __lpfc_get_active_sglq(struct lpfc_hba *phba, uint16_t xritag)
967 {
968         struct lpfc_sglq *sglq;
969
970         sglq =  phba->sli4_hba.lpfc_sglq_active_list[xritag];
971         return sglq;
972 }
973
974 /**
975  * lpfc_clr_rrq_active - Clears RRQ active bit in xri_bitmap.
976  * @phba: Pointer to HBA context object.
977  * @xritag: xri used in this exchange.
978  * @rrq: The RRQ to be cleared.
979  *
980  **/
981 void
982 lpfc_clr_rrq_active(struct lpfc_hba *phba,
983                     uint16_t xritag,
984                     struct lpfc_node_rrq *rrq)
985 {
986         struct lpfc_nodelist *ndlp = NULL;
987
988         /* Lookup did to verify if did is still active on this vport */
989         if (rrq->vport)
990                 ndlp = lpfc_findnode_did(rrq->vport, rrq->nlp_DID);
991
992         if (!ndlp)
993                 goto out;
994
995         if (test_and_clear_bit(xritag, ndlp->active_rrqs_xri_bitmap)) {
996                 rrq->send_rrq = 0;
997                 rrq->xritag = 0;
998                 rrq->rrq_stop_time = 0;
999         }
1000 out:
1001         mempool_free(rrq, phba->rrq_pool);
1002 }
1003
1004 /**
1005  * lpfc_handle_rrq_active - Checks if RRQ has waithed RATOV.
1006  * @phba: Pointer to HBA context object.
1007  *
1008  * This function is called with hbalock held. This function
1009  * Checks if stop_time (ratov from setting rrq active) has
1010  * been reached, if it has and the send_rrq flag is set then
1011  * it will call lpfc_send_rrq. If the send_rrq flag is not set
1012  * then it will just call the routine to clear the rrq and
1013  * free the rrq resource.
1014  * The timer is set to the next rrq that is going to expire before
1015  * leaving the routine.
1016  *
1017  **/
1018 void
1019 lpfc_handle_rrq_active(struct lpfc_hba *phba)
1020 {
1021         struct lpfc_node_rrq *rrq;
1022         struct lpfc_node_rrq *nextrrq;
1023         unsigned long next_time;
1024         unsigned long iflags;
1025         LIST_HEAD(send_rrq);
1026
1027         clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1028         next_time = jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1029         spin_lock_irqsave(&phba->rrq_list_lock, iflags);
1030         list_for_each_entry_safe(rrq, nextrrq,
1031                                  &phba->active_rrq_list, list) {
1032                 if (time_after(jiffies, rrq->rrq_stop_time))
1033                         list_move(&rrq->list, &send_rrq);
1034                 else if (time_before(rrq->rrq_stop_time, next_time))
1035                         next_time = rrq->rrq_stop_time;
1036         }
1037         spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1038         if ((!list_empty(&phba->active_rrq_list)) &&
1039             (!test_bit(FC_UNLOADING, &phba->pport->load_flag)))
1040                 mod_timer(&phba->rrq_tmr, next_time);
1041         list_for_each_entry_safe(rrq, nextrrq, &send_rrq, list) {
1042                 list_del(&rrq->list);
1043                 if (!rrq->send_rrq) {
1044                         /* this call will free the rrq */
1045                         lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1046                 } else if (lpfc_send_rrq(phba, rrq)) {
1047                         /* if we send the rrq then the completion handler
1048                         *  will clear the bit in the xribitmap.
1049                         */
1050                         lpfc_clr_rrq_active(phba, rrq->xritag,
1051                                             rrq);
1052                 }
1053         }
1054 }
1055
1056 /**
1057  * lpfc_get_active_rrq - Get the active RRQ for this exchange.
1058  * @vport: Pointer to vport context object.
1059  * @xri: The xri used in the exchange.
1060  * @did: The targets DID for this exchange.
1061  *
1062  * returns NULL = rrq not found in the phba->active_rrq_list.
1063  *         rrq = rrq for this xri and target.
1064  **/
1065 struct lpfc_node_rrq *
1066 lpfc_get_active_rrq(struct lpfc_vport *vport, uint16_t xri, uint32_t did)
1067 {
1068         struct lpfc_hba *phba = vport->phba;
1069         struct lpfc_node_rrq *rrq;
1070         struct lpfc_node_rrq *nextrrq;
1071         unsigned long iflags;
1072
1073         if (phba->sli_rev != LPFC_SLI_REV4)
1074                 return NULL;
1075         spin_lock_irqsave(&phba->rrq_list_lock, iflags);
1076         list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1077                 if (rrq->vport == vport && rrq->xritag == xri &&
1078                                 rrq->nlp_DID == did){
1079                         list_del(&rrq->list);
1080                         spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1081                         return rrq;
1082                 }
1083         }
1084         spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1085         return NULL;
1086 }
1087
1088 /**
1089  * lpfc_cleanup_vports_rrqs - Remove and clear the active RRQ for this vport.
1090  * @vport: Pointer to vport context object.
1091  * @ndlp: Pointer to the lpfc_node_list structure.
1092  * If ndlp is NULL Remove all active RRQs for this vport from the
1093  * phba->active_rrq_list and clear the rrq.
1094  * If ndlp is not NULL then only remove rrqs for this vport & this ndlp.
1095  **/
1096 void
1097 lpfc_cleanup_vports_rrqs(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
1098
1099 {
1100         struct lpfc_hba *phba = vport->phba;
1101         struct lpfc_node_rrq *rrq;
1102         struct lpfc_node_rrq *nextrrq;
1103         unsigned long iflags;
1104         LIST_HEAD(rrq_list);
1105
1106         if (phba->sli_rev != LPFC_SLI_REV4)
1107                 return;
1108         if (!ndlp) {
1109                 lpfc_sli4_vport_delete_els_xri_aborted(vport);
1110                 lpfc_sli4_vport_delete_fcp_xri_aborted(vport);
1111         }
1112         spin_lock_irqsave(&phba->rrq_list_lock, iflags);
1113         list_for_each_entry_safe(rrq, nextrrq, &phba->active_rrq_list, list) {
1114                 if (rrq->vport != vport)
1115                         continue;
1116
1117                 if (!ndlp || ndlp == lpfc_findnode_did(vport, rrq->nlp_DID))
1118                         list_move(&rrq->list, &rrq_list);
1119
1120         }
1121         spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1122
1123         list_for_each_entry_safe(rrq, nextrrq, &rrq_list, list) {
1124                 list_del(&rrq->list);
1125                 lpfc_clr_rrq_active(phba, rrq->xritag, rrq);
1126         }
1127 }
1128
1129 /**
1130  * lpfc_test_rrq_active - Test RRQ bit in xri_bitmap.
1131  * @phba: Pointer to HBA context object.
1132  * @ndlp: Targets nodelist pointer for this exchange.
1133  * @xritag: the xri in the bitmap to test.
1134  *
1135  * This function returns:
1136  * 0 = rrq not active for this xri
1137  * 1 = rrq is valid for this xri.
1138  **/
1139 int
1140 lpfc_test_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1141                         uint16_t  xritag)
1142 {
1143         if (!ndlp)
1144                 return 0;
1145         if (!ndlp->active_rrqs_xri_bitmap)
1146                 return 0;
1147         if (test_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1148                 return 1;
1149         else
1150                 return 0;
1151 }
1152
1153 /**
1154  * lpfc_set_rrq_active - set RRQ active bit in xri_bitmap.
1155  * @phba: Pointer to HBA context object.
1156  * @ndlp: nodelist pointer for this target.
1157  * @xritag: xri used in this exchange.
1158  * @rxid: Remote Exchange ID.
1159  * @send_rrq: Flag used to determine if we should send rrq els cmd.
1160  *
1161  * This function takes the hbalock.
1162  * The active bit is always set in the active rrq xri_bitmap even
1163  * if there is no slot avaiable for the other rrq information.
1164  *
1165  * returns 0 rrq actived for this xri
1166  *         < 0 No memory or invalid ndlp.
1167  **/
1168 int
1169 lpfc_set_rrq_active(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp,
1170                     uint16_t xritag, uint16_t rxid, uint16_t send_rrq)
1171 {
1172         unsigned long iflags;
1173         struct lpfc_node_rrq *rrq;
1174         int empty;
1175
1176         if (!ndlp)
1177                 return -EINVAL;
1178
1179         if (!phba->cfg_enable_rrq)
1180                 return -EINVAL;
1181
1182         if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
1183                 clear_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1184                 goto outnl;
1185         }
1186
1187         spin_lock_irqsave(&phba->hbalock, iflags);
1188         if (ndlp->vport && test_bit(FC_UNLOADING, &ndlp->vport->load_flag))
1189                 goto out;
1190
1191         if (!ndlp->active_rrqs_xri_bitmap)
1192                 goto out;
1193
1194         if (test_and_set_bit(xritag, ndlp->active_rrqs_xri_bitmap))
1195                 goto out;
1196
1197         spin_unlock_irqrestore(&phba->hbalock, iflags);
1198         rrq = mempool_alloc(phba->rrq_pool, GFP_ATOMIC);
1199         if (!rrq) {
1200                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
1201                                 "3155 Unable to allocate RRQ xri:0x%x rxid:0x%x"
1202                                 " DID:0x%x Send:%d\n",
1203                                 xritag, rxid, ndlp->nlp_DID, send_rrq);
1204                 return -EINVAL;
1205         }
1206         if (phba->cfg_enable_rrq == 1)
1207                 rrq->send_rrq = send_rrq;
1208         else
1209                 rrq->send_rrq = 0;
1210         rrq->xritag = xritag;
1211         rrq->rrq_stop_time = jiffies +
1212                                 msecs_to_jiffies(1000 * (phba->fc_ratov + 1));
1213         rrq->nlp_DID = ndlp->nlp_DID;
1214         rrq->vport = ndlp->vport;
1215         rrq->rxid = rxid;
1216
1217         spin_lock_irqsave(&phba->rrq_list_lock, iflags);
1218         empty = list_empty(&phba->active_rrq_list);
1219         list_add_tail(&rrq->list, &phba->active_rrq_list);
1220         spin_unlock_irqrestore(&phba->rrq_list_lock, iflags);
1221         set_bit(HBA_RRQ_ACTIVE, &phba->hba_flag);
1222         if (empty)
1223                 lpfc_worker_wake_up(phba);
1224         return 0;
1225 out:
1226         spin_unlock_irqrestore(&phba->hbalock, iflags);
1227 outnl:
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         int found = 0;
1255         u8 cmnd;
1256
1257         cmnd = get_job_cmnd(phba, piocbq);
1258
1259         if (piocbq->cmd_flag & LPFC_IO_FCP) {
1260                 lpfc_cmd = piocbq->io_buf;
1261                 ndlp = lpfc_cmd->rdata->pnode;
1262         } else  if ((cmnd == CMD_GEN_REQUEST64_CR) &&
1263                         !(piocbq->cmd_flag & LPFC_IO_LIBDFC)) {
1264                 ndlp = piocbq->ndlp;
1265         } else  if (piocbq->cmd_flag & LPFC_IO_LIBDFC) {
1266                 if (piocbq->cmd_flag & LPFC_IO_LOOPBACK)
1267                         ndlp = NULL;
1268                 else
1269                         ndlp = piocbq->ndlp;
1270         } else {
1271                 ndlp = piocbq->ndlp;
1272         }
1273
1274         spin_lock(&phba->sli4_hba.sgl_list_lock);
1275         list_remove_head(lpfc_els_sgl_list, sglq, struct lpfc_sglq, list);
1276         start_sglq = sglq;
1277         while (!found) {
1278                 if (!sglq)
1279                         break;
1280                 if (ndlp && ndlp->active_rrqs_xri_bitmap &&
1281                     test_bit(sglq->sli4_lxritag,
1282                     ndlp->active_rrqs_xri_bitmap)) {
1283                         /* This xri has an rrq outstanding for this DID.
1284                          * put it back in the list and get another xri.
1285                          */
1286                         list_add_tail(&sglq->list, lpfc_els_sgl_list);
1287                         sglq = NULL;
1288                         list_remove_head(lpfc_els_sgl_list, sglq,
1289                                                 struct lpfc_sglq, list);
1290                         if (sglq == start_sglq) {
1291                                 list_add_tail(&sglq->list, lpfc_els_sgl_list);
1292                                 sglq = NULL;
1293                                 break;
1294                         } else
1295                                 continue;
1296                 }
1297                 sglq->ndlp = ndlp;
1298                 found = 1;
1299                 phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1300                 sglq->state = SGL_ALLOCATED;
1301         }
1302         spin_unlock(&phba->sli4_hba.sgl_list_lock);
1303         return sglq;
1304 }
1305
1306 /**
1307  * __lpfc_sli_get_nvmet_sglq - Allocates an iocb object from sgl pool
1308  * @phba: Pointer to HBA context object.
1309  * @piocbq: Pointer to the iocbq.
1310  *
1311  * This function is called with the sgl_list lock held. This function
1312  * gets a new driver sglq object from the sglq list. If the
1313  * list is not empty then it is successful, it returns pointer to the newly
1314  * allocated sglq object else it returns NULL.
1315  **/
1316 struct lpfc_sglq *
1317 __lpfc_sli_get_nvmet_sglq(struct lpfc_hba *phba, struct lpfc_iocbq *piocbq)
1318 {
1319         struct list_head *lpfc_nvmet_sgl_list;
1320         struct lpfc_sglq *sglq = NULL;
1321
1322         lpfc_nvmet_sgl_list = &phba->sli4_hba.lpfc_nvmet_sgl_list;
1323
1324         lockdep_assert_held(&phba->sli4_hba.sgl_list_lock);
1325
1326         list_remove_head(lpfc_nvmet_sgl_list, sglq, struct lpfc_sglq, list);
1327         if (!sglq)
1328                 return NULL;
1329         phba->sli4_hba.lpfc_sglq_active_list[sglq->sli4_lxritag] = sglq;
1330         sglq->state = SGL_ALLOCATED;
1331         return sglq;
1332 }
1333
1334 /**
1335  * lpfc_sli_get_iocbq - Allocates an iocb object from iocb pool
1336  * @phba: Pointer to HBA context object.
1337  *
1338  * This function is called with no lock held. This function
1339  * allocates a new driver iocb object from the iocb pool. If the
1340  * allocation is successful, it returns pointer to the newly
1341  * allocated iocb object else it returns NULL.
1342  **/
1343 struct lpfc_iocbq *
1344 lpfc_sli_get_iocbq(struct lpfc_hba *phba)
1345 {
1346         struct lpfc_iocbq * iocbq = NULL;
1347         unsigned long iflags;
1348
1349         spin_lock_irqsave(&phba->hbalock, iflags);
1350         iocbq = __lpfc_sli_get_iocbq(phba);
1351         spin_unlock_irqrestore(&phba->hbalock, iflags);
1352         return iocbq;
1353 }
1354
1355 /**
1356  * __lpfc_sli_release_iocbq_s4 - Release iocb to the iocb pool
1357  * @phba: Pointer to HBA context object.
1358  * @iocbq: Pointer to driver iocb object.
1359  *
1360  * This function is called to release the driver iocb object
1361  * to the iocb pool. The iotag in the iocb object
1362  * does not change for each use of the iocb object. This function
1363  * clears all other fields of the iocb object when it is freed.
1364  * The sqlq structure that holds the xritag and phys and virtual
1365  * mappings for the scatter gather list is retrieved from the
1366  * active array of sglq. The get of the sglq pointer also clears
1367  * the entry in the array. If the status of the IO indiactes that
1368  * this IO was aborted then the sglq entry it put on the
1369  * lpfc_abts_els_sgl_list until the CQ_ABORTED_XRI is received. If the
1370  * IO has good status or fails for any other reason then the sglq
1371  * entry is added to the free list (lpfc_els_sgl_list). The hbalock is
1372  *  asserted held in the code path calling this routine.
1373  **/
1374 static void
1375 __lpfc_sli_release_iocbq_s4(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1376 {
1377         struct lpfc_sglq *sglq;
1378         unsigned long iflag = 0;
1379         struct lpfc_sli_ring *pring;
1380
1381         if (iocbq->sli4_xritag == NO_XRI)
1382                 sglq = NULL;
1383         else
1384                 sglq = __lpfc_clear_active_sglq(phba, iocbq->sli4_lxritag);
1385
1386
1387         if (sglq)  {
1388                 if (iocbq->cmd_flag & LPFC_IO_NVMET) {
1389                         spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1390                                           iflag);
1391                         sglq->state = SGL_FREED;
1392                         sglq->ndlp = NULL;
1393                         list_add_tail(&sglq->list,
1394                                       &phba->sli4_hba.lpfc_nvmet_sgl_list);
1395                         spin_unlock_irqrestore(
1396                                 &phba->sli4_hba.sgl_list_lock, iflag);
1397                         goto out;
1398                 }
1399
1400                 if ((iocbq->cmd_flag & LPFC_EXCHANGE_BUSY) &&
1401                     (!(unlikely(pci_channel_offline(phba->pcidev)))) &&
1402                     sglq->state != SGL_XRI_ABORTED) {
1403                         spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1404                                           iflag);
1405
1406                         /* Check if we can get a reference on ndlp */
1407                         if (sglq->ndlp && !lpfc_nlp_get(sglq->ndlp))
1408                                 sglq->ndlp = NULL;
1409
1410                         list_add(&sglq->list,
1411                                  &phba->sli4_hba.lpfc_abts_els_sgl_list);
1412                         spin_unlock_irqrestore(
1413                                 &phba->sli4_hba.sgl_list_lock, iflag);
1414                 } else {
1415                         spin_lock_irqsave(&phba->sli4_hba.sgl_list_lock,
1416                                           iflag);
1417                         sglq->state = SGL_FREED;
1418                         sglq->ndlp = NULL;
1419                         list_add_tail(&sglq->list,
1420                                       &phba->sli4_hba.lpfc_els_sgl_list);
1421                         spin_unlock_irqrestore(
1422                                 &phba->sli4_hba.sgl_list_lock, iflag);
1423                         pring = lpfc_phba_elsring(phba);
1424                         /* Check if TXQ queue needs to be serviced */
1425                         if (pring && (!list_empty(&pring->txq)))
1426                                 lpfc_worker_wake_up(phba);
1427                 }
1428         }
1429
1430 out:
1431         /*
1432          * Clean all volatile data fields, preserve iotag and node struct.
1433          */
1434         memset_startat(iocbq, 0, wqe);
1435         iocbq->sli4_lxritag = NO_XRI;
1436         iocbq->sli4_xritag = NO_XRI;
1437         iocbq->cmd_flag &= ~(LPFC_IO_NVME | LPFC_IO_NVMET | LPFC_IO_CMF |
1438                               LPFC_IO_NVME_LS);
1439         list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1440 }
1441
1442
1443 /**
1444  * __lpfc_sli_release_iocbq_s3 - Release iocb to the iocb pool
1445  * @phba: Pointer to HBA context object.
1446  * @iocbq: Pointer to driver iocb object.
1447  *
1448  * This function is called to release the driver iocb object to the
1449  * iocb pool. The iotag in the iocb object does not change for each
1450  * use of the iocb object. This function clears all other fields of
1451  * the iocb object when it is freed. The hbalock is asserted held in
1452  * the code path calling this routine.
1453  **/
1454 static void
1455 __lpfc_sli_release_iocbq_s3(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1456 {
1457
1458         /*
1459          * Clean all volatile data fields, preserve iotag and node struct.
1460          */
1461         memset_startat(iocbq, 0, iocb);
1462         iocbq->sli4_xritag = NO_XRI;
1463         list_add_tail(&iocbq->list, &phba->lpfc_iocb_list);
1464 }
1465
1466 /**
1467  * __lpfc_sli_release_iocbq - Release iocb to the iocb pool
1468  * @phba: Pointer to HBA context object.
1469  * @iocbq: Pointer to driver iocb object.
1470  *
1471  * This function is called with hbalock held to release driver
1472  * iocb object to the iocb pool. The iotag in the iocb object
1473  * does not change for each use of the iocb object. This function
1474  * clears all other fields of the iocb object when it is freed.
1475  **/
1476 static void
1477 __lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1478 {
1479         lockdep_assert_held(&phba->hbalock);
1480
1481         phba->__lpfc_sli_release_iocbq(phba, iocbq);
1482         phba->iocb_cnt--;
1483 }
1484
1485 /**
1486  * lpfc_sli_release_iocbq - Release iocb to the iocb pool
1487  * @phba: Pointer to HBA context object.
1488  * @iocbq: Pointer to driver iocb object.
1489  *
1490  * This function is called with no lock held to release the iocb to
1491  * iocb pool.
1492  **/
1493 void
1494 lpfc_sli_release_iocbq(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
1495 {
1496         unsigned long iflags;
1497
1498         /*
1499          * Clean all volatile data fields, preserve iotag and node struct.
1500          */
1501         spin_lock_irqsave(&phba->hbalock, iflags);
1502         __lpfc_sli_release_iocbq(phba, iocbq);
1503         spin_unlock_irqrestore(&phba->hbalock, iflags);
1504 }
1505
1506 /**
1507  * lpfc_sli_cancel_iocbs - Cancel all iocbs from a list.
1508  * @phba: Pointer to HBA context object.
1509  * @iocblist: List of IOCBs.
1510  * @ulpstatus: ULP status in IOCB command field.
1511  * @ulpWord4: ULP word-4 in IOCB command field.
1512  *
1513  * This function is called with a list of IOCBs to cancel. It cancels the IOCB
1514  * on the list by invoking the complete callback function associated with the
1515  * IOCB with the provided @ulpstatus and @ulpword4 set to the IOCB commond
1516  * fields.
1517  **/
1518 void
1519 lpfc_sli_cancel_iocbs(struct lpfc_hba *phba, struct list_head *iocblist,
1520                       uint32_t ulpstatus, uint32_t ulpWord4)
1521 {
1522         struct lpfc_iocbq *piocb;
1523
1524         while (!list_empty(iocblist)) {
1525                 list_remove_head(iocblist, piocb, struct lpfc_iocbq, list);
1526                 if (piocb->cmd_cmpl) {
1527                         if (piocb->cmd_flag & LPFC_IO_NVME) {
1528                                 lpfc_nvme_cancel_iocb(phba, piocb,
1529                                                       ulpstatus, ulpWord4);
1530                         } else {
1531                                 if (phba->sli_rev == LPFC_SLI_REV4) {
1532                                         bf_set(lpfc_wcqe_c_status,
1533                                                &piocb->wcqe_cmpl, ulpstatus);
1534                                         piocb->wcqe_cmpl.parameter = ulpWord4;
1535                                 } else {
1536                                         piocb->iocb.ulpStatus = ulpstatus;
1537                                         piocb->iocb.un.ulpWord[4] = ulpWord4;
1538                                 }
1539                                 (piocb->cmd_cmpl) (phba, piocb, piocb);
1540                         }
1541                 } else {
1542                         lpfc_sli_release_iocbq(phba, piocb);
1543                 }
1544         }
1545         return;
1546 }
1547
1548 /**
1549  * lpfc_sli_iocb_cmd_type - Get the iocb type
1550  * @iocb_cmnd: iocb command code.
1551  *
1552  * This function is called by ring event handler function to get the iocb type.
1553  * This function translates the iocb command to an iocb command type used to
1554  * decide the final disposition of each completed IOCB.
1555  * The function returns
1556  * LPFC_UNKNOWN_IOCB if it is an unsupported iocb
1557  * LPFC_SOL_IOCB     if it is a solicited iocb completion
1558  * LPFC_ABORT_IOCB   if it is an abort iocb
1559  * LPFC_UNSOL_IOCB   if it is an unsolicited iocb
1560  *
1561  * The caller is not required to hold any lock.
1562  **/
1563 static lpfc_iocb_type
1564 lpfc_sli_iocb_cmd_type(uint8_t iocb_cmnd)
1565 {
1566         lpfc_iocb_type type = LPFC_UNKNOWN_IOCB;
1567
1568         if (iocb_cmnd > CMD_MAX_IOCB_CMD)
1569                 return 0;
1570
1571         switch (iocb_cmnd) {
1572         case CMD_XMIT_SEQUENCE_CR:
1573         case CMD_XMIT_SEQUENCE_CX:
1574         case CMD_XMIT_BCAST_CN:
1575         case CMD_XMIT_BCAST_CX:
1576         case CMD_ELS_REQUEST_CR:
1577         case CMD_ELS_REQUEST_CX:
1578         case CMD_CREATE_XRI_CR:
1579         case CMD_CREATE_XRI_CX:
1580         case CMD_GET_RPI_CN:
1581         case CMD_XMIT_ELS_RSP_CX:
1582         case CMD_GET_RPI_CR:
1583         case CMD_FCP_IWRITE_CR:
1584         case CMD_FCP_IWRITE_CX:
1585         case CMD_FCP_IREAD_CR:
1586         case CMD_FCP_IREAD_CX:
1587         case CMD_FCP_ICMND_CR:
1588         case CMD_FCP_ICMND_CX:
1589         case CMD_FCP_TSEND_CX:
1590         case CMD_FCP_TRSP_CX:
1591         case CMD_FCP_TRECEIVE_CX:
1592         case CMD_FCP_AUTO_TRSP_CX:
1593         case CMD_ADAPTER_MSG:
1594         case CMD_ADAPTER_DUMP:
1595         case CMD_XMIT_SEQUENCE64_CR:
1596         case CMD_XMIT_SEQUENCE64_CX:
1597         case CMD_XMIT_BCAST64_CN:
1598         case CMD_XMIT_BCAST64_CX:
1599         case CMD_ELS_REQUEST64_CR:
1600         case CMD_ELS_REQUEST64_CX:
1601         case CMD_FCP_IWRITE64_CR:
1602         case CMD_FCP_IWRITE64_CX:
1603         case CMD_FCP_IREAD64_CR:
1604         case CMD_FCP_IREAD64_CX:
1605         case CMD_FCP_ICMND64_CR:
1606         case CMD_FCP_ICMND64_CX:
1607         case CMD_FCP_TSEND64_CX:
1608         case CMD_FCP_TRSP64_CX:
1609         case CMD_FCP_TRECEIVE64_CX:
1610         case CMD_GEN_REQUEST64_CR:
1611         case CMD_GEN_REQUEST64_CX:
1612         case CMD_XMIT_ELS_RSP64_CX:
1613         case DSSCMD_IWRITE64_CR:
1614         case DSSCMD_IWRITE64_CX:
1615         case DSSCMD_IREAD64_CR:
1616         case DSSCMD_IREAD64_CX:
1617         case CMD_SEND_FRAME:
1618                 type = LPFC_SOL_IOCB;
1619                 break;
1620         case CMD_ABORT_XRI_CN:
1621         case CMD_ABORT_XRI_CX:
1622         case CMD_CLOSE_XRI_CN:
1623         case CMD_CLOSE_XRI_CX:
1624         case CMD_XRI_ABORTED_CX:
1625         case CMD_ABORT_MXRI64_CN:
1626         case CMD_XMIT_BLS_RSP64_CX:
1627                 type = LPFC_ABORT_IOCB;
1628                 break;
1629         case CMD_RCV_SEQUENCE_CX:
1630         case CMD_RCV_ELS_REQ_CX:
1631         case CMD_RCV_SEQUENCE64_CX:
1632         case CMD_RCV_ELS_REQ64_CX:
1633         case CMD_ASYNC_STATUS:
1634         case CMD_IOCB_RCV_SEQ64_CX:
1635         case CMD_IOCB_RCV_ELS64_CX:
1636         case CMD_IOCB_RCV_CONT64_CX:
1637         case CMD_IOCB_RET_XRI64_CX:
1638                 type = LPFC_UNSOL_IOCB;
1639                 break;
1640         case CMD_IOCB_XMIT_MSEQ64_CR:
1641         case CMD_IOCB_XMIT_MSEQ64_CX:
1642         case CMD_IOCB_RCV_SEQ_LIST64_CX:
1643         case CMD_IOCB_RCV_ELS_LIST64_CX:
1644         case CMD_IOCB_CLOSE_EXTENDED_CN:
1645         case CMD_IOCB_ABORT_EXTENDED_CN:
1646         case CMD_IOCB_RET_HBQE64_CN:
1647         case CMD_IOCB_FCP_IBIDIR64_CR:
1648         case CMD_IOCB_FCP_IBIDIR64_CX:
1649         case CMD_IOCB_FCP_ITASKMGT64_CX:
1650         case CMD_IOCB_LOGENTRY_CN:
1651         case CMD_IOCB_LOGENTRY_ASYNC_CN:
1652                 printk("%s - Unhandled SLI-3 Command x%x\n",
1653                                 __func__, iocb_cmnd);
1654                 type = LPFC_UNKNOWN_IOCB;
1655                 break;
1656         default:
1657                 type = LPFC_UNKNOWN_IOCB;
1658                 break;
1659         }
1660
1661         return type;
1662 }
1663
1664 /**
1665  * lpfc_sli_ring_map - Issue config_ring mbox for all rings
1666  * @phba: Pointer to HBA context object.
1667  *
1668  * This function is called from SLI initialization code
1669  * to configure every ring of the HBA's SLI interface. The
1670  * caller is not required to hold any lock. This function issues
1671  * a config_ring mailbox command for each ring.
1672  * This function returns zero if successful else returns a negative
1673  * error code.
1674  **/
1675 static int
1676 lpfc_sli_ring_map(struct lpfc_hba *phba)
1677 {
1678         struct lpfc_sli *psli = &phba->sli;
1679         LPFC_MBOXQ_t *pmb;
1680         MAILBOX_t *pmbox;
1681         int i, rc, ret = 0;
1682
1683         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
1684         if (!pmb)
1685                 return -ENOMEM;
1686         pmbox = &pmb->u.mb;
1687         phba->link_state = LPFC_INIT_MBX_CMDS;
1688         for (i = 0; i < psli->num_rings; i++) {
1689                 lpfc_config_ring(phba, i, pmb);
1690                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
1691                 if (rc != MBX_SUCCESS) {
1692                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
1693                                         "0446 Adapter failed to init (%d), "
1694                                         "mbxCmd x%x CFG_RING, mbxStatus x%x, "
1695                                         "ring %d\n",
1696                                         rc, pmbox->mbxCommand,
1697                                         pmbox->mbxStatus, i);
1698                         phba->link_state = LPFC_HBA_ERROR;
1699                         ret = -ENXIO;
1700                         break;
1701                 }
1702         }
1703         mempool_free(pmb, phba->mbox_mem_pool);
1704         return ret;
1705 }
1706
1707 /**
1708  * lpfc_sli_ringtxcmpl_put - Adds new iocb to the txcmplq
1709  * @phba: Pointer to HBA context object.
1710  * @pring: Pointer to driver SLI ring object.
1711  * @piocb: Pointer to the driver iocb object.
1712  *
1713  * The driver calls this function with the hbalock held for SLI3 ports or
1714  * the ring lock held for SLI4 ports. The function adds the
1715  * new iocb to txcmplq of the given ring. This function always returns
1716  * 0. If this function is called for ELS ring, this function checks if
1717  * there is a vport associated with the ELS command. This function also
1718  * starts els_tmofunc timer if this is an ELS command.
1719  **/
1720 static int
1721 lpfc_sli_ringtxcmpl_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
1722                         struct lpfc_iocbq *piocb)
1723 {
1724         u32 ulp_command = 0;
1725
1726         BUG_ON(!piocb);
1727         ulp_command = get_job_cmnd(phba, piocb);
1728
1729         list_add_tail(&piocb->list, &pring->txcmplq);
1730         piocb->cmd_flag |= LPFC_IO_ON_TXCMPLQ;
1731         pring->txcmplq_cnt++;
1732         if ((unlikely(pring->ringno == LPFC_ELS_RING)) &&
1733            (ulp_command != CMD_ABORT_XRI_WQE) &&
1734            (ulp_command != CMD_ABORT_XRI_CN) &&
1735            (ulp_command != CMD_CLOSE_XRI_CN)) {
1736                 BUG_ON(!piocb->vport);
1737                 if (!test_bit(FC_UNLOADING, &piocb->vport->load_flag))
1738                         mod_timer(&piocb->vport->els_tmofunc,
1739                                   jiffies +
1740                                   msecs_to_jiffies(1000 * (phba->fc_ratov << 1)));
1741         }
1742
1743         return 0;
1744 }
1745
1746 /**
1747  * lpfc_sli_ringtx_get - Get first element of the txq
1748  * @phba: Pointer to HBA context object.
1749  * @pring: Pointer to driver SLI ring object.
1750  *
1751  * This function is called with hbalock held to get next
1752  * iocb in txq of the given ring. If there is any iocb in
1753  * the txq, the function returns first iocb in the list after
1754  * removing the iocb from the list, else it returns NULL.
1755  **/
1756 struct lpfc_iocbq *
1757 lpfc_sli_ringtx_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
1758 {
1759         struct lpfc_iocbq *cmd_iocb;
1760
1761         lockdep_assert_held(&phba->hbalock);
1762
1763         list_remove_head((&pring->txq), cmd_iocb, struct lpfc_iocbq, list);
1764         return cmd_iocb;
1765 }
1766
1767 /**
1768  * lpfc_cmf_sync_cmpl - Process a CMF_SYNC_WQE cmpl
1769  * @phba: Pointer to HBA context object.
1770  * @cmdiocb: Pointer to driver command iocb object.
1771  * @rspiocb: Pointer to driver response iocb object.
1772  *
1773  * This routine will inform the driver of any BW adjustments we need
1774  * to make. These changes will be picked up during the next CMF
1775  * timer interrupt. In addition, any BW changes will be logged
1776  * with LOG_CGN_MGMT.
1777  **/
1778 static void
1779 lpfc_cmf_sync_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
1780                    struct lpfc_iocbq *rspiocb)
1781 {
1782         union lpfc_wqe128 *wqe;
1783         uint32_t status, info;
1784         struct lpfc_wcqe_complete *wcqe = &rspiocb->wcqe_cmpl;
1785         uint64_t bw, bwdif, slop;
1786         uint64_t pcent, bwpcent;
1787         int asig, afpin, sigcnt, fpincnt;
1788         int wsigmax, wfpinmax, cg, tdp;
1789         char *s;
1790
1791         /* First check for error */
1792         status = bf_get(lpfc_wcqe_c_status, wcqe);
1793         if (status) {
1794                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1795                                 "6211 CMF_SYNC_WQE Error "
1796                                 "req_tag x%x status x%x hwstatus x%x "
1797                                 "tdatap x%x parm x%x\n",
1798                                 bf_get(lpfc_wcqe_c_request_tag, wcqe),
1799                                 bf_get(lpfc_wcqe_c_status, wcqe),
1800                                 bf_get(lpfc_wcqe_c_hw_status, wcqe),
1801                                 wcqe->total_data_placed,
1802                                 wcqe->parameter);
1803                 goto out;
1804         }
1805
1806         /* Gather congestion information on a successful cmpl */
1807         info = wcqe->parameter;
1808         phba->cmf_active_info = info;
1809
1810         /* See if firmware info count is valid or has changed */
1811         if (info > LPFC_MAX_CMF_INFO || phba->cmf_info_per_interval == info)
1812                 info = 0;
1813         else
1814                 phba->cmf_info_per_interval = info;
1815
1816         tdp = bf_get(lpfc_wcqe_c_cmf_bw, wcqe);
1817         cg = bf_get(lpfc_wcqe_c_cmf_cg, wcqe);
1818
1819         /* Get BW requirement from firmware */
1820         bw = (uint64_t)tdp * LPFC_CMF_BLK_SIZE;
1821         if (!bw) {
1822                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1823                                 "6212 CMF_SYNC_WQE x%x: NULL bw\n",
1824                                 bf_get(lpfc_wcqe_c_request_tag, wcqe));
1825                 goto out;
1826         }
1827
1828         /* Gather information needed for logging if a BW change is required */
1829         wqe = &cmdiocb->wqe;
1830         asig = bf_get(cmf_sync_asig, &wqe->cmf_sync);
1831         afpin = bf_get(cmf_sync_afpin, &wqe->cmf_sync);
1832         fpincnt = bf_get(cmf_sync_wfpincnt, &wqe->cmf_sync);
1833         sigcnt = bf_get(cmf_sync_wsigcnt, &wqe->cmf_sync);
1834         if (phba->cmf_max_bytes_per_interval != bw ||
1835             (asig || afpin || sigcnt || fpincnt)) {
1836                 /* Are we increasing or decreasing BW */
1837                 if (phba->cmf_max_bytes_per_interval <  bw) {
1838                         bwdif = bw - phba->cmf_max_bytes_per_interval;
1839                         s = "Increase";
1840                 } else {
1841                         bwdif = phba->cmf_max_bytes_per_interval - bw;
1842                         s = "Decrease";
1843                 }
1844
1845                 /* What is the change percentage */
1846                 slop = div_u64(phba->cmf_link_byte_count, 200); /*For rounding*/
1847                 pcent = div64_u64(bwdif * 100 + slop,
1848                                   phba->cmf_link_byte_count);
1849                 bwpcent = div64_u64(bw * 100 + slop,
1850                                     phba->cmf_link_byte_count);
1851                 /* Because of bytes adjustment due to shorter timer in
1852                  * lpfc_cmf_timer() the cmf_link_byte_count can be shorter and
1853                  * may seem like BW is above 100%.
1854                  */
1855                 if (bwpcent > 100)
1856                         bwpcent = 100;
1857
1858                 if (phba->cmf_max_bytes_per_interval < bw &&
1859                     bwpcent > 95)
1860                         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1861                                         "6208 Congestion bandwidth "
1862                                         "limits removed\n");
1863                 else if ((phba->cmf_max_bytes_per_interval > bw) &&
1864                          ((bwpcent + pcent) <= 100) && ((bwpcent + pcent) > 95))
1865                         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1866                                         "6209 Congestion bandwidth "
1867                                         "limits in effect\n");
1868
1869                 if (asig) {
1870                         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1871                                         "6237 BW Threshold %lld%% (%lld): "
1872                                         "%lld%% %s: Signal Alarm: cg:%d "
1873                                         "Info:%u\n",
1874                                         bwpcent, bw, pcent, s, cg,
1875                                         phba->cmf_active_info);
1876                 } else if (afpin) {
1877                         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1878                                         "6238 BW Threshold %lld%% (%lld): "
1879                                         "%lld%% %s: FPIN Alarm: cg:%d "
1880                                         "Info:%u\n",
1881                                         bwpcent, bw, pcent, s, cg,
1882                                         phba->cmf_active_info);
1883                 } else if (sigcnt) {
1884                         wsigmax = bf_get(cmf_sync_wsigmax, &wqe->cmf_sync);
1885                         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1886                                         "6239 BW Threshold %lld%% (%lld): "
1887                                         "%lld%% %s: Signal Warning: "
1888                                         "Cnt %d Max %d: cg:%d Info:%u\n",
1889                                         bwpcent, bw, pcent, s, sigcnt,
1890                                         wsigmax, cg, phba->cmf_active_info);
1891                 } else if (fpincnt) {
1892                         wfpinmax = bf_get(cmf_sync_wfpinmax, &wqe->cmf_sync);
1893                         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1894                                         "6240 BW Threshold %lld%% (%lld): "
1895                                         "%lld%% %s: FPIN Warning: "
1896                                         "Cnt %d Max %d: cg:%d Info:%u\n",
1897                                         bwpcent, bw, pcent, s, fpincnt,
1898                                         wfpinmax, cg, phba->cmf_active_info);
1899                 } else {
1900                         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1901                                         "6241 BW Threshold %lld%% (%lld): "
1902                                         "CMF %lld%% %s: cg:%d Info:%u\n",
1903                                         bwpcent, bw, pcent, s, cg,
1904                                         phba->cmf_active_info);
1905                 }
1906         } else if (info) {
1907                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1908                                 "6246 Info Threshold %u\n", info);
1909         }
1910
1911         /* Save BW change to be picked up during next timer interrupt */
1912         phba->cmf_last_sync_bw = bw;
1913 out:
1914         lpfc_sli_release_iocbq(phba, cmdiocb);
1915 }
1916
1917 /**
1918  * lpfc_issue_cmf_sync_wqe - Issue a CMF_SYNC_WQE
1919  * @phba: Pointer to HBA context object.
1920  * @ms:   ms to set in WQE interval, 0 means use init op
1921  * @total: Total rcv bytes for this interval
1922  *
1923  * This routine is called every CMF timer interrupt. Its purpose is
1924  * to issue a CMF_SYNC_WQE to the firmware to inform it of any events
1925  * that may indicate we have congestion (FPINs or Signals). Upon
1926  * completion, the firmware will indicate any BW restrictions the
1927  * driver may need to take.
1928  **/
1929 int
1930 lpfc_issue_cmf_sync_wqe(struct lpfc_hba *phba, u32 ms, u64 total)
1931 {
1932         union lpfc_wqe128 *wqe;
1933         struct lpfc_iocbq *sync_buf;
1934         unsigned long iflags;
1935         u32 ret_val, cgn_sig_freq;
1936         u32 atot, wtot, max;
1937         u8 warn_sync_period = 0;
1938
1939         /* First address any alarm / warning activity */
1940         atot = atomic_xchg(&phba->cgn_sync_alarm_cnt, 0);
1941         wtot = atomic_xchg(&phba->cgn_sync_warn_cnt, 0);
1942
1943         spin_lock_irqsave(&phba->hbalock, iflags);
1944
1945         /* ONLY Managed mode will send the CMF_SYNC_WQE to the HBA */
1946         if (phba->cmf_active_mode != LPFC_CFG_MANAGED ||
1947             phba->link_state < LPFC_LINK_UP) {
1948                 ret_val = 0;
1949                 goto out_unlock;
1950         }
1951
1952         sync_buf = __lpfc_sli_get_iocbq(phba);
1953         if (!sync_buf) {
1954                 lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT,
1955                                 "6244 No available WQEs for CMF_SYNC_WQE\n");
1956                 ret_val = ENOMEM;
1957                 goto out_unlock;
1958         }
1959
1960         wqe = &sync_buf->wqe;
1961
1962         /* WQEs are reused.  Clear stale data and set key fields to zero */
1963         memset(wqe, 0, sizeof(*wqe));
1964
1965         /* If this is the very first CMF_SYNC_WQE, issue an init operation */
1966         if (!ms) {
1967                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
1968                                 "6441 CMF Init %d - CMF_SYNC_WQE\n",
1969                                 phba->fc_eventTag);
1970                 bf_set(cmf_sync_op, &wqe->cmf_sync, 1); /* 1=init */
1971                 bf_set(cmf_sync_interval, &wqe->cmf_sync, LPFC_CMF_INTERVAL);
1972                 goto initpath;
1973         }
1974
1975         bf_set(cmf_sync_op, &wqe->cmf_sync, 0); /* 0=recalc */
1976         bf_set(cmf_sync_interval, &wqe->cmf_sync, ms);
1977
1978         /* Check for alarms / warnings */
1979         if (atot) {
1980                 if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1981                         /* We hit an Signal alarm condition */
1982                         bf_set(cmf_sync_asig, &wqe->cmf_sync, 1);
1983                 } else {
1984                         /* We hit a FPIN alarm condition */
1985                         bf_set(cmf_sync_afpin, &wqe->cmf_sync, 1);
1986                 }
1987         } else if (wtot) {
1988                 if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY ||
1989                     phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
1990                         cgn_sig_freq = phba->cgn_sig_freq ? phba->cgn_sig_freq :
1991                                         lpfc_fabric_cgn_frequency;
1992                         /* We hit an Signal warning condition */
1993                         max = LPFC_SEC_TO_MSEC / cgn_sig_freq *
1994                                 lpfc_acqe_cgn_frequency;
1995                         bf_set(cmf_sync_wsigmax, &wqe->cmf_sync, max);
1996                         bf_set(cmf_sync_wsigcnt, &wqe->cmf_sync, wtot);
1997                         warn_sync_period = lpfc_acqe_cgn_frequency;
1998                 } else {
1999                         /* We hit a FPIN warning condition */
2000                         bf_set(cmf_sync_wfpinmax, &wqe->cmf_sync, 1);
2001                         bf_set(cmf_sync_wfpincnt, &wqe->cmf_sync, 1);
2002                         if (phba->cgn_fpin_frequency != LPFC_FPIN_INIT_FREQ)
2003                                 warn_sync_period =
2004                                 LPFC_MSECS_TO_SECS(phba->cgn_fpin_frequency);
2005                 }
2006         }
2007
2008         /* Update total read blocks during previous timer interval */
2009         wqe->cmf_sync.read_bytes = (u32)(total / LPFC_CMF_BLK_SIZE);
2010
2011 initpath:
2012         bf_set(cmf_sync_ver, &wqe->cmf_sync, LPFC_CMF_SYNC_VER);
2013         wqe->cmf_sync.event_tag = phba->fc_eventTag;
2014         bf_set(cmf_sync_cmnd, &wqe->cmf_sync, CMD_CMF_SYNC_WQE);
2015
2016         /* Setup reqtag to match the wqe completion. */
2017         bf_set(cmf_sync_reqtag, &wqe->cmf_sync, sync_buf->iotag);
2018
2019         bf_set(cmf_sync_qosd, &wqe->cmf_sync, 1);
2020         bf_set(cmf_sync_period, &wqe->cmf_sync, warn_sync_period);
2021
2022         bf_set(cmf_sync_cmd_type, &wqe->cmf_sync, CMF_SYNC_COMMAND);
2023         bf_set(cmf_sync_wqec, &wqe->cmf_sync, 1);
2024         bf_set(cmf_sync_cqid, &wqe->cmf_sync, LPFC_WQE_CQ_ID_DEFAULT);
2025
2026         sync_buf->vport = phba->pport;
2027         sync_buf->cmd_cmpl = lpfc_cmf_sync_cmpl;
2028         sync_buf->cmd_dmabuf = NULL;
2029         sync_buf->rsp_dmabuf = NULL;
2030         sync_buf->bpl_dmabuf = NULL;
2031         sync_buf->sli4_xritag = NO_XRI;
2032
2033         sync_buf->cmd_flag |= LPFC_IO_CMF;
2034         ret_val = lpfc_sli4_issue_wqe(phba, &phba->sli4_hba.hdwq[0], sync_buf);
2035         if (ret_val) {
2036                 lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
2037                                 "6214 Cannot issue CMF_SYNC_WQE: x%x\n",
2038                                 ret_val);
2039                 __lpfc_sli_release_iocbq(phba, sync_buf);
2040         }
2041 out_unlock:
2042         spin_unlock_irqrestore(&phba->hbalock, iflags);
2043         return ret_val;
2044 }
2045
2046 /**
2047  * lpfc_sli_next_iocb_slot - Get next iocb slot in the ring
2048  * @phba: Pointer to HBA context object.
2049  * @pring: Pointer to driver SLI ring object.
2050  *
2051  * This function is called with hbalock held and the caller must post the
2052  * iocb without releasing the lock. If the caller releases the lock,
2053  * iocb slot returned by the function is not guaranteed to be available.
2054  * The function returns pointer to the next available iocb slot if there
2055  * is available slot in the ring, else it returns NULL.
2056  * If the get index of the ring is ahead of the put index, the function
2057  * will post an error attention event to the worker thread to take the
2058  * HBA to offline state.
2059  **/
2060 static IOCB_t *
2061 lpfc_sli_next_iocb_slot (struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2062 {
2063         struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
2064         uint32_t  max_cmd_idx = pring->sli.sli3.numCiocb;
2065
2066         lockdep_assert_held(&phba->hbalock);
2067
2068         if ((pring->sli.sli3.next_cmdidx == pring->sli.sli3.cmdidx) &&
2069            (++pring->sli.sli3.next_cmdidx >= max_cmd_idx))
2070                 pring->sli.sli3.next_cmdidx = 0;
2071
2072         if (unlikely(pring->sli.sli3.local_getidx ==
2073                 pring->sli.sli3.next_cmdidx)) {
2074
2075                 pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
2076
2077                 if (unlikely(pring->sli.sli3.local_getidx >= max_cmd_idx)) {
2078                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2079                                         "0315 Ring %d issue: portCmdGet %d "
2080                                         "is bigger than cmd ring %d\n",
2081                                         pring->ringno,
2082                                         pring->sli.sli3.local_getidx,
2083                                         max_cmd_idx);
2084
2085                         phba->link_state = LPFC_HBA_ERROR;
2086                         /*
2087                          * All error attention handlers are posted to
2088                          * worker thread
2089                          */
2090                         phba->work_ha |= HA_ERATT;
2091                         phba->work_hs = HS_FFER3;
2092
2093                         lpfc_worker_wake_up(phba);
2094
2095                         return NULL;
2096                 }
2097
2098                 if (pring->sli.sli3.local_getidx == pring->sli.sli3.next_cmdidx)
2099                         return NULL;
2100         }
2101
2102         return lpfc_cmd_iocb(phba, pring);
2103 }
2104
2105 /**
2106  * lpfc_sli_next_iotag - Get an iotag for the iocb
2107  * @phba: Pointer to HBA context object.
2108  * @iocbq: Pointer to driver iocb object.
2109  *
2110  * This function gets an iotag for the iocb. If there is no unused iotag and
2111  * the iocbq_lookup_len < 0xffff, this function allocates a bigger iotag_lookup
2112  * array and assigns a new iotag.
2113  * The function returns the allocated iotag if successful, else returns zero.
2114  * Zero is not a valid iotag.
2115  * The caller is not required to hold any lock.
2116  **/
2117 uint16_t
2118 lpfc_sli_next_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *iocbq)
2119 {
2120         struct lpfc_iocbq **new_arr;
2121         struct lpfc_iocbq **old_arr;
2122         size_t new_len;
2123         struct lpfc_sli *psli = &phba->sli;
2124         uint16_t iotag;
2125
2126         spin_lock_irq(&phba->hbalock);
2127         iotag = psli->last_iotag;
2128         if(++iotag < psli->iocbq_lookup_len) {
2129                 psli->last_iotag = iotag;
2130                 psli->iocbq_lookup[iotag] = iocbq;
2131                 spin_unlock_irq(&phba->hbalock);
2132                 iocbq->iotag = iotag;
2133                 return iotag;
2134         } else if (psli->iocbq_lookup_len < (0xffff
2135                                            - LPFC_IOCBQ_LOOKUP_INCREMENT)) {
2136                 new_len = psli->iocbq_lookup_len + LPFC_IOCBQ_LOOKUP_INCREMENT;
2137                 spin_unlock_irq(&phba->hbalock);
2138                 new_arr = kcalloc(new_len, sizeof(struct lpfc_iocbq *),
2139                                   GFP_KERNEL);
2140                 if (new_arr) {
2141                         spin_lock_irq(&phba->hbalock);
2142                         old_arr = psli->iocbq_lookup;
2143                         if (new_len <= psli->iocbq_lookup_len) {
2144                                 /* highly unprobable case */
2145                                 kfree(new_arr);
2146                                 iotag = psli->last_iotag;
2147                                 if(++iotag < psli->iocbq_lookup_len) {
2148                                         psli->last_iotag = iotag;
2149                                         psli->iocbq_lookup[iotag] = iocbq;
2150                                         spin_unlock_irq(&phba->hbalock);
2151                                         iocbq->iotag = iotag;
2152                                         return iotag;
2153                                 }
2154                                 spin_unlock_irq(&phba->hbalock);
2155                                 return 0;
2156                         }
2157                         if (psli->iocbq_lookup)
2158                                 memcpy(new_arr, old_arr,
2159                                        ((psli->last_iotag  + 1) *
2160                                         sizeof (struct lpfc_iocbq *)));
2161                         psli->iocbq_lookup = new_arr;
2162                         psli->iocbq_lookup_len = new_len;
2163                         psli->last_iotag = iotag;
2164                         psli->iocbq_lookup[iotag] = iocbq;
2165                         spin_unlock_irq(&phba->hbalock);
2166                         iocbq->iotag = iotag;
2167                         kfree(old_arr);
2168                         return iotag;
2169                 }
2170         } else
2171                 spin_unlock_irq(&phba->hbalock);
2172
2173         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
2174                         "0318 Failed to allocate IOTAG.last IOTAG is %d\n",
2175                         psli->last_iotag);
2176
2177         return 0;
2178 }
2179
2180 /**
2181  * lpfc_sli_submit_iocb - Submit an iocb to the firmware
2182  * @phba: Pointer to HBA context object.
2183  * @pring: Pointer to driver SLI ring object.
2184  * @iocb: Pointer to iocb slot in the ring.
2185  * @nextiocb: Pointer to driver iocb object which need to be
2186  *            posted to firmware.
2187  *
2188  * This function is called to post a new iocb to the firmware. This
2189  * function copies the new iocb to ring iocb slot and updates the
2190  * ring pointers. It adds the new iocb to txcmplq if there is
2191  * a completion call back for this iocb else the function will free the
2192  * iocb object.  The hbalock is asserted held in the code path calling
2193  * this routine.
2194  **/
2195 static void
2196 lpfc_sli_submit_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
2197                 IOCB_t *iocb, struct lpfc_iocbq *nextiocb)
2198 {
2199         /*
2200          * Set up an iotag
2201          */
2202         nextiocb->iocb.ulpIoTag = (nextiocb->cmd_cmpl) ? nextiocb->iotag : 0;
2203
2204
2205         if (pring->ringno == LPFC_ELS_RING) {
2206                 lpfc_debugfs_slow_ring_trc(phba,
2207                         "IOCB cmd ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
2208                         *(((uint32_t *) &nextiocb->iocb) + 4),
2209                         *(((uint32_t *) &nextiocb->iocb) + 6),
2210                         *(((uint32_t *) &nextiocb->iocb) + 7));
2211         }
2212
2213         /*
2214          * Issue iocb command to adapter
2215          */
2216         lpfc_sli_pcimem_bcopy(&nextiocb->iocb, iocb, phba->iocb_cmd_size);
2217         wmb();
2218         pring->stats.iocb_cmd++;
2219
2220         /*
2221          * If there is no completion routine to call, we can release the
2222          * IOCB buffer back right now. For IOCBs, like QUE_RING_BUF,
2223          * that have no rsp ring completion, cmd_cmpl MUST be NULL.
2224          */
2225         if (nextiocb->cmd_cmpl)
2226                 lpfc_sli_ringtxcmpl_put(phba, pring, nextiocb);
2227         else
2228                 __lpfc_sli_release_iocbq(phba, nextiocb);
2229
2230         /*
2231          * Let the HBA know what IOCB slot will be the next one the
2232          * driver will put a command into.
2233          */
2234         pring->sli.sli3.cmdidx = pring->sli.sli3.next_cmdidx;
2235         writel(pring->sli.sli3.cmdidx, &phba->host_gp[pring->ringno].cmdPutInx);
2236 }
2237
2238 /**
2239  * lpfc_sli_update_full_ring - Update the chip attention register
2240  * @phba: Pointer to HBA context object.
2241  * @pring: Pointer to driver SLI ring object.
2242  *
2243  * The caller is not required to hold any lock for calling this function.
2244  * This function updates the chip attention bits for the ring to inform firmware
2245  * that there are pending work to be done for this ring and requests an
2246  * interrupt when there is space available in the ring. This function is
2247  * called when the driver is unable to post more iocbs to the ring due
2248  * to unavailability of space in the ring.
2249  **/
2250 static void
2251 lpfc_sli_update_full_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2252 {
2253         int ringno = pring->ringno;
2254
2255         pring->flag |= LPFC_CALL_RING_AVAILABLE;
2256
2257         wmb();
2258
2259         /*
2260          * Set ring 'ringno' to SET R0CE_REQ in Chip Att register.
2261          * The HBA will tell us when an IOCB entry is available.
2262          */
2263         writel((CA_R0ATT|CA_R0CE_REQ) << (ringno*4), phba->CAregaddr);
2264         readl(phba->CAregaddr); /* flush */
2265
2266         pring->stats.iocb_cmd_full++;
2267 }
2268
2269 /**
2270  * lpfc_sli_update_ring - Update chip attention register
2271  * @phba: Pointer to HBA context object.
2272  * @pring: Pointer to driver SLI ring object.
2273  *
2274  * This function updates the chip attention register bit for the
2275  * given ring to inform HBA that there is more work to be done
2276  * in this ring. The caller is not required to hold any lock.
2277  **/
2278 static void
2279 lpfc_sli_update_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2280 {
2281         int ringno = pring->ringno;
2282
2283         /*
2284          * Tell the HBA that there is work to do in this ring.
2285          */
2286         if (!(phba->sli3_options & LPFC_SLI3_CRP_ENABLED)) {
2287                 wmb();
2288                 writel(CA_R0ATT << (ringno * 4), phba->CAregaddr);
2289                 readl(phba->CAregaddr); /* flush */
2290         }
2291 }
2292
2293 /**
2294  * lpfc_sli_resume_iocb - Process iocbs in the txq
2295  * @phba: Pointer to HBA context object.
2296  * @pring: Pointer to driver SLI ring object.
2297  *
2298  * This function is called with hbalock held to post pending iocbs
2299  * in the txq to the firmware. This function is called when driver
2300  * detects space available in the ring.
2301  **/
2302 static void
2303 lpfc_sli_resume_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
2304 {
2305         IOCB_t *iocb;
2306         struct lpfc_iocbq *nextiocb;
2307
2308         lockdep_assert_held(&phba->hbalock);
2309
2310         /*
2311          * Check to see if:
2312          *  (a) there is anything on the txq to send
2313          *  (b) link is up
2314          *  (c) link attention events can be processed (fcp ring only)
2315          *  (d) IOCB processing is not blocked by the outstanding mbox command.
2316          */
2317
2318         if (lpfc_is_link_up(phba) &&
2319             (!list_empty(&pring->txq)) &&
2320             (pring->ringno != LPFC_FCP_RING ||
2321              phba->sli.sli_flag & LPFC_PROCESS_LA)) {
2322
2323                 while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
2324                        (nextiocb = lpfc_sli_ringtx_get(phba, pring)))
2325                         lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
2326
2327                 if (iocb)
2328                         lpfc_sli_update_ring(phba, pring);
2329                 else
2330                         lpfc_sli_update_full_ring(phba, pring);
2331         }
2332
2333         return;
2334 }
2335
2336 /**
2337  * lpfc_sli_next_hbq_slot - Get next hbq entry for the HBQ
2338  * @phba: Pointer to HBA context object.
2339  * @hbqno: HBQ number.
2340  *
2341  * This function is called with hbalock held to get the next
2342  * available slot for the given HBQ. If there is free slot
2343  * available for the HBQ it will return pointer to the next available
2344  * HBQ entry else it will return NULL.
2345  **/
2346 static struct lpfc_hbq_entry *
2347 lpfc_sli_next_hbq_slot(struct lpfc_hba *phba, uint32_t hbqno)
2348 {
2349         struct hbq_s *hbqp = &phba->hbqs[hbqno];
2350
2351         lockdep_assert_held(&phba->hbalock);
2352
2353         if (hbqp->next_hbqPutIdx == hbqp->hbqPutIdx &&
2354             ++hbqp->next_hbqPutIdx >= hbqp->entry_count)
2355                 hbqp->next_hbqPutIdx = 0;
2356
2357         if (unlikely(hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)) {
2358                 uint32_t raw_index = phba->hbq_get[hbqno];
2359                 uint32_t getidx = le32_to_cpu(raw_index);
2360
2361                 hbqp->local_hbqGetIdx = getidx;
2362
2363                 if (unlikely(hbqp->local_hbqGetIdx >= hbqp->entry_count)) {
2364                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2365                                         "1802 HBQ %d: local_hbqGetIdx "
2366                                         "%u is > than hbqp->entry_count %u\n",
2367                                         hbqno, hbqp->local_hbqGetIdx,
2368                                         hbqp->entry_count);
2369
2370                         phba->link_state = LPFC_HBA_ERROR;
2371                         return NULL;
2372                 }
2373
2374                 if (hbqp->local_hbqGetIdx == hbqp->next_hbqPutIdx)
2375                         return NULL;
2376         }
2377
2378         return (struct lpfc_hbq_entry *) phba->hbqs[hbqno].hbq_virt +
2379                         hbqp->hbqPutIdx;
2380 }
2381
2382 /**
2383  * lpfc_sli_hbqbuf_free_all - Free all the hbq buffers
2384  * @phba: Pointer to HBA context object.
2385  *
2386  * This function is called with no lock held to free all the
2387  * hbq buffers while uninitializing the SLI interface. It also
2388  * frees the HBQ buffers returned by the firmware but not yet
2389  * processed by the upper layers.
2390  **/
2391 void
2392 lpfc_sli_hbqbuf_free_all(struct lpfc_hba *phba)
2393 {
2394         struct lpfc_dmabuf *dmabuf, *next_dmabuf;
2395         struct hbq_dmabuf *hbq_buf;
2396         unsigned long flags;
2397         int i, hbq_count;
2398
2399         hbq_count = lpfc_sli_hbq_count();
2400         /* Return all memory used by all HBQs */
2401         spin_lock_irqsave(&phba->hbalock, flags);
2402         for (i = 0; i < hbq_count; ++i) {
2403                 list_for_each_entry_safe(dmabuf, next_dmabuf,
2404                                 &phba->hbqs[i].hbq_buffer_list, list) {
2405                         hbq_buf = container_of(dmabuf, struct hbq_dmabuf, dbuf);
2406                         list_del(&hbq_buf->dbuf.list);
2407                         (phba->hbqs[i].hbq_free_buffer)(phba, hbq_buf);
2408                 }
2409                 phba->hbqs[i].buffer_count = 0;
2410         }
2411
2412         /* Mark the HBQs not in use */
2413         phba->hbq_in_use = 0;
2414         spin_unlock_irqrestore(&phba->hbalock, flags);
2415 }
2416
2417 /**
2418  * lpfc_sli_hbq_to_firmware - Post the hbq buffer to firmware
2419  * @phba: Pointer to HBA context object.
2420  * @hbqno: HBQ number.
2421  * @hbq_buf: Pointer to HBQ buffer.
2422  *
2423  * This function is called with the hbalock held to post a
2424  * hbq buffer to the firmware. If the function finds an empty
2425  * slot in the HBQ, it will post the buffer. The function will return
2426  * pointer to the hbq entry if it successfully post the buffer
2427  * else it will return NULL.
2428  **/
2429 static int
2430 lpfc_sli_hbq_to_firmware(struct lpfc_hba *phba, uint32_t hbqno,
2431                          struct hbq_dmabuf *hbq_buf)
2432 {
2433         lockdep_assert_held(&phba->hbalock);
2434         return phba->lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buf);
2435 }
2436
2437 /**
2438  * lpfc_sli_hbq_to_firmware_s3 - Post the hbq buffer to SLI3 firmware
2439  * @phba: Pointer to HBA context object.
2440  * @hbqno: HBQ number.
2441  * @hbq_buf: Pointer to HBQ buffer.
2442  *
2443  * This function is called with the hbalock held to post a hbq buffer to the
2444  * firmware. If the function finds an empty slot in the HBQ, it will post the
2445  * buffer and place it on the hbq_buffer_list. The function will return zero if
2446  * it successfully post the buffer else it will return an error.
2447  **/
2448 static int
2449 lpfc_sli_hbq_to_firmware_s3(struct lpfc_hba *phba, uint32_t hbqno,
2450                             struct hbq_dmabuf *hbq_buf)
2451 {
2452         struct lpfc_hbq_entry *hbqe;
2453         dma_addr_t physaddr = hbq_buf->dbuf.phys;
2454
2455         lockdep_assert_held(&phba->hbalock);
2456         /* Get next HBQ entry slot to use */
2457         hbqe = lpfc_sli_next_hbq_slot(phba, hbqno);
2458         if (hbqe) {
2459                 struct hbq_s *hbqp = &phba->hbqs[hbqno];
2460
2461                 hbqe->bde.addrHigh = le32_to_cpu(putPaddrHigh(physaddr));
2462                 hbqe->bde.addrLow  = le32_to_cpu(putPaddrLow(physaddr));
2463                 hbqe->bde.tus.f.bdeSize = hbq_buf->total_size;
2464                 hbqe->bde.tus.f.bdeFlags = 0;
2465                 hbqe->bde.tus.w = le32_to_cpu(hbqe->bde.tus.w);
2466                 hbqe->buffer_tag = le32_to_cpu(hbq_buf->tag);
2467                                 /* Sync SLIM */
2468                 hbqp->hbqPutIdx = hbqp->next_hbqPutIdx;
2469                 writel(hbqp->hbqPutIdx, phba->hbq_put + hbqno);
2470                                 /* flush */
2471                 readl(phba->hbq_put + hbqno);
2472                 list_add_tail(&hbq_buf->dbuf.list, &hbqp->hbq_buffer_list);
2473                 return 0;
2474         } else
2475                 return -ENOMEM;
2476 }
2477
2478 /**
2479  * lpfc_sli_hbq_to_firmware_s4 - Post the hbq buffer to SLI4 firmware
2480  * @phba: Pointer to HBA context object.
2481  * @hbqno: HBQ number.
2482  * @hbq_buf: Pointer to HBQ buffer.
2483  *
2484  * This function is called with the hbalock held to post an RQE to the SLI4
2485  * firmware. If able to post the RQE to the RQ it will queue the hbq entry to
2486  * the hbq_buffer_list and return zero, otherwise it will return an error.
2487  **/
2488 static int
2489 lpfc_sli_hbq_to_firmware_s4(struct lpfc_hba *phba, uint32_t hbqno,
2490                             struct hbq_dmabuf *hbq_buf)
2491 {
2492         int rc;
2493         struct lpfc_rqe hrqe;
2494         struct lpfc_rqe drqe;
2495         struct lpfc_queue *hrq;
2496         struct lpfc_queue *drq;
2497
2498         if (hbqno != LPFC_ELS_HBQ)
2499                 return 1;
2500         hrq = phba->sli4_hba.hdr_rq;
2501         drq = phba->sli4_hba.dat_rq;
2502
2503         lockdep_assert_held(&phba->hbalock);
2504         hrqe.address_lo = putPaddrLow(hbq_buf->hbuf.phys);
2505         hrqe.address_hi = putPaddrHigh(hbq_buf->hbuf.phys);
2506         drqe.address_lo = putPaddrLow(hbq_buf->dbuf.phys);
2507         drqe.address_hi = putPaddrHigh(hbq_buf->dbuf.phys);
2508         rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
2509         if (rc < 0)
2510                 return rc;
2511         hbq_buf->tag = (rc | (hbqno << 16));
2512         list_add_tail(&hbq_buf->dbuf.list, &phba->hbqs[hbqno].hbq_buffer_list);
2513         return 0;
2514 }
2515
2516 /* HBQ for ELS and CT traffic. */
2517 static struct lpfc_hbq_init lpfc_els_hbq = {
2518         .rn = 1,
2519         .entry_count = 256,
2520         .mask_count = 0,
2521         .profile = 0,
2522         .ring_mask = (1 << LPFC_ELS_RING),
2523         .buffer_count = 0,
2524         .init_count = 40,
2525         .add_count = 40,
2526 };
2527
2528 /* Array of HBQs */
2529 struct lpfc_hbq_init *lpfc_hbq_defs[] = {
2530         &lpfc_els_hbq,
2531 };
2532
2533 /**
2534  * lpfc_sli_hbqbuf_fill_hbqs - Post more hbq buffers to HBQ
2535  * @phba: Pointer to HBA context object.
2536  * @hbqno: HBQ number.
2537  * @count: Number of HBQ buffers to be posted.
2538  *
2539  * This function is called with no lock held to post more hbq buffers to the
2540  * given HBQ. The function returns the number of HBQ buffers successfully
2541  * posted.
2542  **/
2543 static int
2544 lpfc_sli_hbqbuf_fill_hbqs(struct lpfc_hba *phba, uint32_t hbqno, uint32_t count)
2545 {
2546         uint32_t i, posted = 0;
2547         unsigned long flags;
2548         struct hbq_dmabuf *hbq_buffer;
2549         LIST_HEAD(hbq_buf_list);
2550         if (!phba->hbqs[hbqno].hbq_alloc_buffer)
2551                 return 0;
2552
2553         if ((phba->hbqs[hbqno].buffer_count + count) >
2554             lpfc_hbq_defs[hbqno]->entry_count)
2555                 count = lpfc_hbq_defs[hbqno]->entry_count -
2556                                         phba->hbqs[hbqno].buffer_count;
2557         if (!count)
2558                 return 0;
2559         /* Allocate HBQ entries */
2560         for (i = 0; i < count; i++) {
2561                 hbq_buffer = (phba->hbqs[hbqno].hbq_alloc_buffer)(phba);
2562                 if (!hbq_buffer)
2563                         break;
2564                 list_add_tail(&hbq_buffer->dbuf.list, &hbq_buf_list);
2565         }
2566         /* Check whether HBQ is still in use */
2567         spin_lock_irqsave(&phba->hbalock, flags);
2568         if (!phba->hbq_in_use)
2569                 goto err;
2570         while (!list_empty(&hbq_buf_list)) {
2571                 list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2572                                  dbuf.list);
2573                 hbq_buffer->tag = (phba->hbqs[hbqno].buffer_count |
2574                                       (hbqno << 16));
2575                 if (!lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer)) {
2576                         phba->hbqs[hbqno].buffer_count++;
2577                         posted++;
2578                 } else
2579                         (phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2580         }
2581         spin_unlock_irqrestore(&phba->hbalock, flags);
2582         return posted;
2583 err:
2584         spin_unlock_irqrestore(&phba->hbalock, flags);
2585         while (!list_empty(&hbq_buf_list)) {
2586                 list_remove_head(&hbq_buf_list, hbq_buffer, struct hbq_dmabuf,
2587                                  dbuf.list);
2588                 (phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2589         }
2590         return 0;
2591 }
2592
2593 /**
2594  * lpfc_sli_hbqbuf_add_hbqs - Post more HBQ buffers to firmware
2595  * @phba: Pointer to HBA context object.
2596  * @qno: HBQ number.
2597  *
2598  * This function posts more buffers to the HBQ. This function
2599  * is called with no lock held. The function returns the number of HBQ entries
2600  * successfully allocated.
2601  **/
2602 int
2603 lpfc_sli_hbqbuf_add_hbqs(struct lpfc_hba *phba, uint32_t qno)
2604 {
2605         if (phba->sli_rev == LPFC_SLI_REV4)
2606                 return 0;
2607         else
2608                 return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2609                                          lpfc_hbq_defs[qno]->add_count);
2610 }
2611
2612 /**
2613  * lpfc_sli_hbqbuf_init_hbqs - Post initial buffers to the HBQ
2614  * @phba: Pointer to HBA context object.
2615  * @qno:  HBQ queue number.
2616  *
2617  * This function is called from SLI initialization code path with
2618  * no lock held to post initial HBQ buffers to firmware. The
2619  * function returns the number of HBQ entries successfully allocated.
2620  **/
2621 static int
2622 lpfc_sli_hbqbuf_init_hbqs(struct lpfc_hba *phba, uint32_t qno)
2623 {
2624         if (phba->sli_rev == LPFC_SLI_REV4)
2625                 return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2626                                         lpfc_hbq_defs[qno]->entry_count);
2627         else
2628                 return lpfc_sli_hbqbuf_fill_hbqs(phba, qno,
2629                                          lpfc_hbq_defs[qno]->init_count);
2630 }
2631
2632 /*
2633  * lpfc_sli_hbqbuf_get - Remove the first hbq off of an hbq list
2634  *
2635  * This function removes the first hbq buffer on an hbq list and returns a
2636  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2637  **/
2638 static struct hbq_dmabuf *
2639 lpfc_sli_hbqbuf_get(struct list_head *rb_list)
2640 {
2641         struct lpfc_dmabuf *d_buf;
2642
2643         list_remove_head(rb_list, d_buf, struct lpfc_dmabuf, list);
2644         if (!d_buf)
2645                 return NULL;
2646         return container_of(d_buf, struct hbq_dmabuf, dbuf);
2647 }
2648
2649 /**
2650  * lpfc_sli_rqbuf_get - Remove the first dma buffer off of an RQ list
2651  * @phba: Pointer to HBA context object.
2652  * @hrq: HBQ number.
2653  *
2654  * This function removes the first RQ buffer on an RQ buffer list and returns a
2655  * pointer to that buffer. If it finds no buffers on the list it returns NULL.
2656  **/
2657 static struct rqb_dmabuf *
2658 lpfc_sli_rqbuf_get(struct lpfc_hba *phba, struct lpfc_queue *hrq)
2659 {
2660         struct lpfc_dmabuf *h_buf;
2661         struct lpfc_rqb *rqbp;
2662
2663         rqbp = hrq->rqbp;
2664         list_remove_head(&rqbp->rqb_buffer_list, h_buf,
2665                          struct lpfc_dmabuf, list);
2666         if (!h_buf)
2667                 return NULL;
2668         rqbp->buffer_count--;
2669         return container_of(h_buf, struct rqb_dmabuf, hbuf);
2670 }
2671
2672 /**
2673  * lpfc_sli_hbqbuf_find - Find the hbq buffer associated with a tag
2674  * @phba: Pointer to HBA context object.
2675  * @tag: Tag of the hbq buffer.
2676  *
2677  * This function searches for the hbq buffer associated with the given tag in
2678  * the hbq buffer list. If it finds the hbq buffer, it returns the hbq_buffer
2679  * otherwise it returns NULL.
2680  **/
2681 static struct hbq_dmabuf *
2682 lpfc_sli_hbqbuf_find(struct lpfc_hba *phba, uint32_t tag)
2683 {
2684         struct lpfc_dmabuf *d_buf;
2685         struct hbq_dmabuf *hbq_buf;
2686         uint32_t hbqno;
2687
2688         hbqno = tag >> 16;
2689         if (hbqno >= LPFC_MAX_HBQS)
2690                 return NULL;
2691
2692         spin_lock_irq(&phba->hbalock);
2693         list_for_each_entry(d_buf, &phba->hbqs[hbqno].hbq_buffer_list, list) {
2694                 hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
2695                 if (hbq_buf->tag == tag) {
2696                         spin_unlock_irq(&phba->hbalock);
2697                         return hbq_buf;
2698                 }
2699         }
2700         spin_unlock_irq(&phba->hbalock);
2701         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2702                         "1803 Bad hbq tag. Data: x%x x%x\n",
2703                         tag, phba->hbqs[tag >> 16].buffer_count);
2704         return NULL;
2705 }
2706
2707 /**
2708  * lpfc_sli_free_hbq - Give back the hbq buffer to firmware
2709  * @phba: Pointer to HBA context object.
2710  * @hbq_buffer: Pointer to HBQ buffer.
2711  *
2712  * This function is called with hbalock. This function gives back
2713  * the hbq buffer to firmware. If the HBQ does not have space to
2714  * post the buffer, it will free the buffer.
2715  **/
2716 void
2717 lpfc_sli_free_hbq(struct lpfc_hba *phba, struct hbq_dmabuf *hbq_buffer)
2718 {
2719         uint32_t hbqno;
2720
2721         if (hbq_buffer) {
2722                 hbqno = hbq_buffer->tag >> 16;
2723                 if (lpfc_sli_hbq_to_firmware(phba, hbqno, hbq_buffer))
2724                         (phba->hbqs[hbqno].hbq_free_buffer)(phba, hbq_buffer);
2725         }
2726 }
2727
2728 /**
2729  * lpfc_sli_chk_mbx_command - Check if the mailbox is a legitimate mailbox
2730  * @mbxCommand: mailbox command code.
2731  *
2732  * This function is called by the mailbox event handler function to verify
2733  * that the completed mailbox command is a legitimate mailbox command. If the
2734  * completed mailbox is not known to the function, it will return MBX_SHUTDOWN
2735  * and the mailbox event handler will take the HBA offline.
2736  **/
2737 static int
2738 lpfc_sli_chk_mbx_command(uint8_t mbxCommand)
2739 {
2740         uint8_t ret;
2741
2742         switch (mbxCommand) {
2743         case MBX_LOAD_SM:
2744         case MBX_READ_NV:
2745         case MBX_WRITE_NV:
2746         case MBX_WRITE_VPARMS:
2747         case MBX_RUN_BIU_DIAG:
2748         case MBX_INIT_LINK:
2749         case MBX_DOWN_LINK:
2750         case MBX_CONFIG_LINK:
2751         case MBX_CONFIG_RING:
2752         case MBX_RESET_RING:
2753         case MBX_READ_CONFIG:
2754         case MBX_READ_RCONFIG:
2755         case MBX_READ_SPARM:
2756         case MBX_READ_STATUS:
2757         case MBX_READ_RPI:
2758         case MBX_READ_XRI:
2759         case MBX_READ_REV:
2760         case MBX_READ_LNK_STAT:
2761         case MBX_REG_LOGIN:
2762         case MBX_UNREG_LOGIN:
2763         case MBX_CLEAR_LA:
2764         case MBX_DUMP_MEMORY:
2765         case MBX_DUMP_CONTEXT:
2766         case MBX_RUN_DIAGS:
2767         case MBX_RESTART:
2768         case MBX_UPDATE_CFG:
2769         case MBX_DOWN_LOAD:
2770         case MBX_DEL_LD_ENTRY:
2771         case MBX_RUN_PROGRAM:
2772         case MBX_SET_MASK:
2773         case MBX_SET_VARIABLE:
2774         case MBX_UNREG_D_ID:
2775         case MBX_KILL_BOARD:
2776         case MBX_CONFIG_FARP:
2777         case MBX_BEACON:
2778         case MBX_LOAD_AREA:
2779         case MBX_RUN_BIU_DIAG64:
2780         case MBX_CONFIG_PORT:
2781         case MBX_READ_SPARM64:
2782         case MBX_READ_RPI64:
2783         case MBX_REG_LOGIN64:
2784         case MBX_READ_TOPOLOGY:
2785         case MBX_WRITE_WWN:
2786         case MBX_SET_DEBUG:
2787         case MBX_LOAD_EXP_ROM:
2788         case MBX_ASYNCEVT_ENABLE:
2789         case MBX_REG_VPI:
2790         case MBX_UNREG_VPI:
2791         case MBX_HEARTBEAT:
2792         case MBX_PORT_CAPABILITIES:
2793         case MBX_PORT_IOV_CONTROL:
2794         case MBX_SLI4_CONFIG:
2795         case MBX_SLI4_REQ_FTRS:
2796         case MBX_REG_FCFI:
2797         case MBX_UNREG_FCFI:
2798         case MBX_REG_VFI:
2799         case MBX_UNREG_VFI:
2800         case MBX_INIT_VPI:
2801         case MBX_INIT_VFI:
2802         case MBX_RESUME_RPI:
2803         case MBX_READ_EVENT_LOG_STATUS:
2804         case MBX_READ_EVENT_LOG:
2805         case MBX_SECURITY_MGMT:
2806         case MBX_AUTH_PORT:
2807         case MBX_ACCESS_VDATA:
2808                 ret = mbxCommand;
2809                 break;
2810         default:
2811                 ret = MBX_SHUTDOWN;
2812                 break;
2813         }
2814         return ret;
2815 }
2816
2817 /**
2818  * lpfc_sli_wake_mbox_wait - lpfc_sli_issue_mbox_wait mbox completion handler
2819  * @phba: Pointer to HBA context object.
2820  * @pmboxq: Pointer to mailbox command.
2821  *
2822  * This is completion handler function for mailbox commands issued from
2823  * lpfc_sli_issue_mbox_wait function. This function is called by the
2824  * mailbox event handler function with no lock held. This function
2825  * will wake up thread waiting on the wait queue pointed by context1
2826  * of the mailbox.
2827  **/
2828 void
2829 lpfc_sli_wake_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq)
2830 {
2831         unsigned long drvr_flag;
2832         struct completion *pmbox_done;
2833
2834         /*
2835          * If pmbox_done is empty, the driver thread gave up waiting and
2836          * continued running.
2837          */
2838         pmboxq->mbox_flag |= LPFC_MBX_WAKE;
2839         spin_lock_irqsave(&phba->hbalock, drvr_flag);
2840         pmbox_done = pmboxq->ctx_u.mbox_wait;
2841         if (pmbox_done)
2842                 complete(pmbox_done);
2843         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
2844         return;
2845 }
2846
2847 /**
2848  * lpfc_sli_def_mbox_cmpl - Default mailbox completion handler
2849  * @phba: Pointer to HBA context object.
2850  * @pmb: Pointer to mailbox object.
2851  *
2852  * This function is the default mailbox completion handler. It
2853  * frees the memory resources associated with the completed mailbox
2854  * command. If the completed command is a REG_LOGIN mailbox command,
2855  * this function will issue a UREG_LOGIN to re-claim the RPI.
2856  **/
2857 void
2858 lpfc_sli_def_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2859 {
2860         struct lpfc_vport  *vport = pmb->vport;
2861         struct lpfc_dmabuf *mp;
2862         struct lpfc_nodelist *ndlp;
2863         struct Scsi_Host *shost;
2864         uint16_t rpi, vpi;
2865         int rc;
2866
2867         /*
2868          * If a REG_LOGIN succeeded  after node is destroyed or node
2869          * is in re-discovery driver need to cleanup the RPI.
2870          */
2871         if (!test_bit(FC_UNLOADING, &phba->pport->load_flag) &&
2872             pmb->u.mb.mbxCommand == MBX_REG_LOGIN64 &&
2873             !pmb->u.mb.mbxStatus) {
2874                 mp = pmb->ctx_buf;
2875                 if (mp) {
2876                         pmb->ctx_buf = NULL;
2877                         lpfc_mbuf_free(phba, mp->virt, mp->phys);
2878                         kfree(mp);
2879                 }
2880                 rpi = pmb->u.mb.un.varWords[0];
2881                 vpi = pmb->u.mb.un.varRegLogin.vpi;
2882                 if (phba->sli_rev == LPFC_SLI_REV4)
2883                         vpi -= phba->sli4_hba.max_cfg_param.vpi_base;
2884                 lpfc_unreg_login(phba, vpi, rpi, pmb);
2885                 pmb->vport = vport;
2886                 pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
2887                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
2888                 if (rc != MBX_NOT_FINISHED)
2889                         return;
2890         }
2891
2892         if ((pmb->u.mb.mbxCommand == MBX_REG_VPI) &&
2893                 !test_bit(FC_UNLOADING, &phba->pport->load_flag) &&
2894                 !pmb->u.mb.mbxStatus) {
2895                 shost = lpfc_shost_from_vport(vport);
2896                 spin_lock_irq(shost->host_lock);
2897                 vport->vpi_state |= LPFC_VPI_REGISTERED;
2898                 spin_unlock_irq(shost->host_lock);
2899                 clear_bit(FC_VPORT_NEEDS_REG_VPI, &vport->fc_flag);
2900         }
2901
2902         if (pmb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
2903                 ndlp = pmb->ctx_ndlp;
2904                 lpfc_nlp_put(ndlp);
2905         }
2906
2907         if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2908                 ndlp = pmb->ctx_ndlp;
2909
2910                 /* Check to see if there are any deferred events to process */
2911                 if (ndlp) {
2912                         lpfc_printf_vlog(
2913                                 vport,
2914                                 KERN_INFO, LOG_MBOX | LOG_DISCOVERY,
2915                                 "1438 UNREG cmpl deferred mbox x%x "
2916                                 "on NPort x%x Data: x%lx x%x x%px x%lx x%x\n",
2917                                 ndlp->nlp_rpi, ndlp->nlp_DID,
2918                                 ndlp->nlp_flag, ndlp->nlp_defer_did,
2919                                 ndlp, vport->load_flag, kref_read(&ndlp->kref));
2920
2921                         if (test_bit(NLP_UNREG_INP, &ndlp->nlp_flag) &&
2922                             ndlp->nlp_defer_did != NLP_EVT_NOTHING_PENDING) {
2923                                 clear_bit(NLP_UNREG_INP, &ndlp->nlp_flag);
2924                                 ndlp->nlp_defer_did = NLP_EVT_NOTHING_PENDING;
2925                                 lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
2926                         }
2927
2928                         /* The unreg_login mailbox is complete and had a
2929                          * reference that has to be released.  The PLOGI
2930                          * got its own ref.
2931                          */
2932                         lpfc_nlp_put(ndlp);
2933                         pmb->ctx_ndlp = NULL;
2934                 }
2935         }
2936
2937         /* This nlp_put pairs with lpfc_sli4_resume_rpi */
2938         if (pmb->u.mb.mbxCommand == MBX_RESUME_RPI) {
2939                 ndlp = pmb->ctx_ndlp;
2940                 lpfc_nlp_put(ndlp);
2941         }
2942
2943         /* Check security permission status on INIT_LINK mailbox command */
2944         if ((pmb->u.mb.mbxCommand == MBX_INIT_LINK) &&
2945             (pmb->u.mb.mbxStatus == MBXERR_SEC_NO_PERMISSION))
2946                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
2947                                 "2860 SLI authentication is required "
2948                                 "for INIT_LINK but has not done yet\n");
2949
2950         if (bf_get(lpfc_mqe_command, &pmb->u.mqe) == MBX_SLI4_CONFIG)
2951                 lpfc_sli4_mbox_cmd_free(phba, pmb);
2952         else
2953                 lpfc_mbox_rsrc_cleanup(phba, pmb, MBOX_THD_UNLOCKED);
2954 }
2955  /**
2956  * lpfc_sli4_unreg_rpi_cmpl_clr - mailbox completion handler
2957  * @phba: Pointer to HBA context object.
2958  * @pmb: Pointer to mailbox object.
2959  *
2960  * This function is the unreg rpi mailbox completion handler. It
2961  * frees the memory resources associated with the completed mailbox
2962  * command. An additional reference is put on the ndlp to prevent
2963  * lpfc_nlp_release from freeing the rpi bit in the bitmask before
2964  * the unreg mailbox command completes, this routine puts the
2965  * reference back.
2966  *
2967  **/
2968 void
2969 lpfc_sli4_unreg_rpi_cmpl_clr(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
2970 {
2971         struct lpfc_vport  *vport = pmb->vport;
2972         struct lpfc_nodelist *ndlp;
2973         bool unreg_inp;
2974
2975         ndlp = pmb->ctx_ndlp;
2976         if (pmb->u.mb.mbxCommand == MBX_UNREG_LOGIN) {
2977                 if (phba->sli_rev == LPFC_SLI_REV4 &&
2978                     (bf_get(lpfc_sli_intf_if_type,
2979                      &phba->sli4_hba.sli_intf) >=
2980                      LPFC_SLI_INTF_IF_TYPE_2)) {
2981                         if (ndlp) {
2982                                 lpfc_printf_vlog(
2983                                          vport, KERN_INFO,
2984                                          LOG_MBOX | LOG_SLI | LOG_NODE,
2985                                          "0010 UNREG_LOGIN vpi:x%x "
2986                                          "rpi:%x DID:%x defer x%x flg x%lx "
2987                                          "x%px\n",
2988                                          vport->vpi, ndlp->nlp_rpi,
2989                                          ndlp->nlp_DID, ndlp->nlp_defer_did,
2990                                          ndlp->nlp_flag,
2991                                          ndlp);
2992
2993                                 /* Cleanup the nlp_flag now that the UNREG RPI
2994                                  * has completed.
2995                                  */
2996                                 unreg_inp = test_and_clear_bit(NLP_UNREG_INP,
2997                                                                &ndlp->nlp_flag);
2998                                 clear_bit(NLP_LOGO_ACC, &ndlp->nlp_flag);
2999
3000                                 /* Check to see if there are any deferred
3001                                  * events to process
3002                                  */
3003                                 if (unreg_inp &&
3004                                     ndlp->nlp_defer_did !=
3005                                     NLP_EVT_NOTHING_PENDING) {
3006                                         lpfc_printf_vlog(
3007                                                 vport, KERN_INFO,
3008                                                 LOG_MBOX | LOG_SLI | LOG_NODE,
3009                                                 "4111 UNREG cmpl deferred "
3010                                                 "clr x%x on "
3011                                                 "NPort x%x Data: x%x x%px\n",
3012                                                 ndlp->nlp_rpi, ndlp->nlp_DID,
3013                                                 ndlp->nlp_defer_did, ndlp);
3014                                         ndlp->nlp_defer_did =
3015                                                 NLP_EVT_NOTHING_PENDING;
3016                                         lpfc_issue_els_plogi(
3017                                                 vport, ndlp->nlp_DID, 0);
3018                                 }
3019
3020                                 lpfc_nlp_put(ndlp);
3021                         }
3022                 }
3023         }
3024
3025         mempool_free(pmb, phba->mbox_mem_pool);
3026 }
3027
3028 /**
3029  * lpfc_sli_handle_mb_event - Handle mailbox completions from firmware
3030  * @phba: Pointer to HBA context object.
3031  *
3032  * This function is called with no lock held. This function processes all
3033  * the completed mailbox commands and gives it to upper layers. The interrupt
3034  * service routine processes mailbox completion interrupt and adds completed
3035  * mailbox commands to the mboxq_cmpl queue and signals the worker thread.
3036  * Worker thread call lpfc_sli_handle_mb_event, which will return the
3037  * completed mailbox commands in mboxq_cmpl queue to the upper layers. This
3038  * function returns the mailbox commands to the upper layer by calling the
3039  * completion handler function of each mailbox.
3040  **/
3041 int
3042 lpfc_sli_handle_mb_event(struct lpfc_hba *phba)
3043 {
3044         MAILBOX_t *pmbox;
3045         LPFC_MBOXQ_t *pmb;
3046         int rc;
3047         LIST_HEAD(cmplq);
3048
3049         phba->sli.slistat.mbox_event++;
3050
3051         /* Get all completed mailboxe buffers into the cmplq */
3052         spin_lock_irq(&phba->hbalock);
3053         list_splice_init(&phba->sli.mboxq_cmpl, &cmplq);
3054         spin_unlock_irq(&phba->hbalock);
3055
3056         /* Get a Mailbox buffer to setup mailbox commands for callback */
3057         do {
3058                 list_remove_head(&cmplq, pmb, LPFC_MBOXQ_t, list);
3059                 if (pmb == NULL)
3060                         break;
3061
3062                 pmbox = &pmb->u.mb;
3063
3064                 if (pmbox->mbxCommand != MBX_HEARTBEAT) {
3065                         if (pmb->vport) {
3066                                 lpfc_debugfs_disc_trc(pmb->vport,
3067                                         LPFC_DISC_TRC_MBOX_VPORT,
3068                                         "MBOX cmpl vport: cmd:x%x mb:x%x x%x",
3069                                         (uint32_t)pmbox->mbxCommand,
3070                                         pmbox->un.varWords[0],
3071                                         pmbox->un.varWords[1]);
3072                         }
3073                         else {
3074                                 lpfc_debugfs_disc_trc(phba->pport,
3075                                         LPFC_DISC_TRC_MBOX,
3076                                         "MBOX cmpl:       cmd:x%x mb:x%x x%x",
3077                                         (uint32_t)pmbox->mbxCommand,
3078                                         pmbox->un.varWords[0],
3079                                         pmbox->un.varWords[1]);
3080                         }
3081                 }
3082
3083                 /*
3084                  * It is a fatal error if unknown mbox command completion.
3085                  */
3086                 if (lpfc_sli_chk_mbx_command(pmbox->mbxCommand) ==
3087                     MBX_SHUTDOWN) {
3088                         /* Unknown mailbox command compl */
3089                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3090                                         "(%d):0323 Unknown Mailbox command "
3091                                         "x%x (x%x/x%x) Cmpl\n",
3092                                         pmb->vport ? pmb->vport->vpi :
3093                                         LPFC_VPORT_UNKNOWN,
3094                                         pmbox->mbxCommand,
3095                                         lpfc_sli_config_mbox_subsys_get(phba,
3096                                                                         pmb),
3097                                         lpfc_sli_config_mbox_opcode_get(phba,
3098                                                                         pmb));
3099                         phba->link_state = LPFC_HBA_ERROR;
3100                         phba->work_hs = HS_FFER3;
3101                         lpfc_handle_eratt(phba);
3102                         continue;
3103                 }
3104
3105                 if (pmbox->mbxStatus) {
3106                         phba->sli.slistat.mbox_stat_err++;
3107                         if (pmbox->mbxStatus == MBXERR_NO_RESOURCES) {
3108                                 /* Mbox cmd cmpl error - RETRYing */
3109                                 lpfc_printf_log(phba, KERN_INFO,
3110                                         LOG_MBOX | LOG_SLI,
3111                                         "(%d):0305 Mbox cmd cmpl "
3112                                         "error - RETRYing Data: x%x "
3113                                         "(x%x/x%x) x%x x%x x%x\n",
3114                                         pmb->vport ? pmb->vport->vpi :
3115                                         LPFC_VPORT_UNKNOWN,
3116                                         pmbox->mbxCommand,
3117                                         lpfc_sli_config_mbox_subsys_get(phba,
3118                                                                         pmb),
3119                                         lpfc_sli_config_mbox_opcode_get(phba,
3120                                                                         pmb),
3121                                         pmbox->mbxStatus,
3122                                         pmbox->un.varWords[0],
3123                                         pmb->vport ? pmb->vport->port_state :
3124                                         LPFC_VPORT_UNKNOWN);
3125                                 pmbox->mbxStatus = 0;
3126                                 pmbox->mbxOwner = OWN_HOST;
3127                                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
3128                                 if (rc != MBX_NOT_FINISHED)
3129                                         continue;
3130                         }
3131                 }
3132
3133                 /* Mailbox cmd <cmd> Cmpl <cmpl> */
3134                 lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
3135                                 "(%d):0307 Mailbox cmd x%x (x%x/x%x) Cmpl %ps "
3136                                 "Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
3137                                 "x%x x%x x%x\n",
3138                                 pmb->vport ? pmb->vport->vpi : 0,
3139                                 pmbox->mbxCommand,
3140                                 lpfc_sli_config_mbox_subsys_get(phba, pmb),
3141                                 lpfc_sli_config_mbox_opcode_get(phba, pmb),
3142                                 pmb->mbox_cmpl,
3143                                 *((uint32_t *) pmbox),
3144                                 pmbox->un.varWords[0],
3145                                 pmbox->un.varWords[1],
3146                                 pmbox->un.varWords[2],
3147                                 pmbox->un.varWords[3],
3148                                 pmbox->un.varWords[4],
3149                                 pmbox->un.varWords[5],
3150                                 pmbox->un.varWords[6],
3151                                 pmbox->un.varWords[7],
3152                                 pmbox->un.varWords[8],
3153                                 pmbox->un.varWords[9],
3154                                 pmbox->un.varWords[10]);
3155
3156                 if (pmb->mbox_cmpl)
3157                         pmb->mbox_cmpl(phba,pmb);
3158         } while (1);
3159         return 0;
3160 }
3161
3162 /**
3163  * lpfc_sli_get_buff - Get the buffer associated with the buffer tag
3164  * @phba: Pointer to HBA context object.
3165  * @pring: Pointer to driver SLI ring object.
3166  * @tag: buffer tag.
3167  *
3168  * This function is called with no lock held. When QUE_BUFTAG_BIT bit
3169  * is set in the tag the buffer is posted for a particular exchange,
3170  * the function will return the buffer without replacing the buffer.
3171  * If the buffer is for unsolicited ELS or CT traffic, this function
3172  * returns the buffer and also posts another buffer to the firmware.
3173  **/
3174 static struct lpfc_dmabuf *
3175 lpfc_sli_get_buff(struct lpfc_hba *phba,
3176                   struct lpfc_sli_ring *pring,
3177                   uint32_t tag)
3178 {
3179         struct hbq_dmabuf *hbq_entry;
3180
3181         if (tag & QUE_BUFTAG_BIT)
3182                 return lpfc_sli_ring_taggedbuf_get(phba, pring, tag);
3183         hbq_entry = lpfc_sli_hbqbuf_find(phba, tag);
3184         if (!hbq_entry)
3185                 return NULL;
3186         return &hbq_entry->dbuf;
3187 }
3188
3189 /**
3190  * lpfc_nvme_unsol_ls_handler - Process an unsolicited event data buffer
3191  *                              containing a NVME LS request.
3192  * @phba: pointer to lpfc hba data structure.
3193  * @piocb: pointer to the iocbq struct representing the sequence starting
3194  *        frame.
3195  *
3196  * This routine initially validates the NVME LS, validates there is a login
3197  * with the port that sent the LS, and then calls the appropriate nvme host
3198  * or target LS request handler.
3199  **/
3200 static void
3201 lpfc_nvme_unsol_ls_handler(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
3202 {
3203         struct lpfc_nodelist *ndlp;
3204         struct lpfc_dmabuf *d_buf;
3205         struct hbq_dmabuf *nvmebuf;
3206         struct fc_frame_header *fc_hdr;
3207         struct lpfc_async_xchg_ctx *axchg = NULL;
3208         char *failwhy = NULL;
3209         uint32_t oxid, sid, did, fctl, size;
3210         int ret = 1;
3211
3212         d_buf = piocb->cmd_dmabuf;
3213
3214         nvmebuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
3215         fc_hdr = nvmebuf->hbuf.virt;
3216         oxid = be16_to_cpu(fc_hdr->fh_ox_id);
3217         sid = sli4_sid_from_fc_hdr(fc_hdr);
3218         did = sli4_did_from_fc_hdr(fc_hdr);
3219         fctl = (fc_hdr->fh_f_ctl[0] << 16 |
3220                 fc_hdr->fh_f_ctl[1] << 8 |
3221                 fc_hdr->fh_f_ctl[2]);
3222         size = bf_get(lpfc_rcqe_length, &nvmebuf->cq_event.cqe.rcqe_cmpl);
3223
3224         lpfc_nvmeio_data(phba, "NVME LS    RCV: xri x%x sz %d from %06x\n",
3225                          oxid, size, sid);
3226
3227         if (test_bit(FC_UNLOADING, &phba->pport->load_flag)) {
3228                 failwhy = "Driver Unloading";
3229         } else if (!(phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME)) {
3230                 failwhy = "NVME FC4 Disabled";
3231         } else if (!phba->nvmet_support && !phba->pport->localport) {
3232                 failwhy = "No Localport";
3233         } else if (phba->nvmet_support && !phba->targetport) {
3234                 failwhy = "No Targetport";
3235         } else if (unlikely(fc_hdr->fh_r_ctl != FC_RCTL_ELS4_REQ)) {
3236                 failwhy = "Bad NVME LS R_CTL";
3237         } else if (unlikely((fctl & 0x00FF0000) !=
3238                         (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT))) {
3239                 failwhy = "Bad NVME LS F_CTL";
3240         } else {
3241                 axchg = kzalloc(sizeof(*axchg), GFP_ATOMIC);
3242                 if (!axchg)
3243                         failwhy = "No CTX memory";
3244         }
3245
3246         if (unlikely(failwhy)) {
3247                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3248                                 "6154 Drop NVME LS: SID %06X OXID x%X: %s\n",
3249                                 sid, oxid, failwhy);
3250                 goto out_fail;
3251         }
3252
3253         /* validate the source of the LS is logged in */
3254         ndlp = lpfc_findnode_did(phba->pport, sid);
3255         if (!ndlp ||
3256             ((ndlp->nlp_state != NLP_STE_UNMAPPED_NODE) &&
3257              (ndlp->nlp_state != NLP_STE_MAPPED_NODE))) {
3258                 lpfc_printf_log(phba, KERN_ERR, LOG_NVME_DISC,
3259                                 "6216 NVME Unsol rcv: No ndlp: "
3260                                 "NPort_ID x%x oxid x%x\n",
3261                                 sid, oxid);
3262                 goto out_fail;
3263         }
3264
3265         axchg->phba = phba;
3266         axchg->ndlp = ndlp;
3267         axchg->size = size;
3268         axchg->oxid = oxid;
3269         axchg->sid = sid;
3270         axchg->wqeq = NULL;
3271         axchg->state = LPFC_NVME_STE_LS_RCV;
3272         axchg->entry_cnt = 1;
3273         axchg->rqb_buffer = (void *)nvmebuf;
3274         axchg->hdwq = &phba->sli4_hba.hdwq[0];
3275         axchg->payload = nvmebuf->dbuf.virt;
3276         INIT_LIST_HEAD(&axchg->list);
3277
3278         if (phba->nvmet_support) {
3279                 ret = lpfc_nvmet_handle_lsreq(phba, axchg);
3280                 spin_lock_irq(&ndlp->lock);
3281                 if (!ret && !(ndlp->fc4_xpt_flags & NLP_XPT_HAS_HH)) {
3282                         ndlp->fc4_xpt_flags |= NLP_XPT_HAS_HH;
3283                         spin_unlock_irq(&ndlp->lock);
3284
3285                         /* This reference is a single occurrence to hold the
3286                          * node valid until the nvmet transport calls
3287                          * host_release.
3288                          */
3289                         if (!lpfc_nlp_get(ndlp))
3290                                 goto out_fail;
3291
3292                         lpfc_printf_log(phba, KERN_ERR, LOG_NODE,
3293                                         "6206 NVMET unsol ls_req ndlp x%px "
3294                                         "DID x%x xflags x%x refcnt %d\n",
3295                                         ndlp, ndlp->nlp_DID,
3296                                         ndlp->fc4_xpt_flags,
3297                                         kref_read(&ndlp->kref));
3298                 } else {
3299                         spin_unlock_irq(&ndlp->lock);
3300                 }
3301         } else {
3302                 ret = lpfc_nvme_handle_lsreq(phba, axchg);
3303         }
3304
3305         /* if zero, LS was successfully handled. If non-zero, LS not handled */
3306         if (!ret)
3307                 return;
3308
3309 out_fail:
3310         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3311                         "6155 Drop NVME LS from DID %06X: SID %06X OXID x%X "
3312                         "NVMe%s handler failed %d\n",
3313                         did, sid, oxid,
3314                         (phba->nvmet_support) ? "T" : "I", ret);
3315
3316         /* recycle receive buffer */
3317         lpfc_in_buf_free(phba, &nvmebuf->dbuf);
3318
3319         /* If start of new exchange, abort it */
3320         if (axchg && (fctl & FC_FC_FIRST_SEQ && !(fctl & FC_FC_EX_CTX)))
3321                 ret = lpfc_nvme_unsol_ls_issue_abort(phba, axchg, sid, oxid);
3322
3323         if (ret)
3324                 kfree(axchg);
3325 }
3326
3327 /**
3328  * lpfc_complete_unsol_iocb - Complete an unsolicited sequence
3329  * @phba: Pointer to HBA context object.
3330  * @pring: Pointer to driver SLI ring object.
3331  * @saveq: Pointer to the iocbq struct representing the sequence starting frame.
3332  * @fch_r_ctl: the r_ctl for the first frame of the sequence.
3333  * @fch_type: the type for the first frame of the sequence.
3334  *
3335  * This function is called with no lock held. This function uses the r_ctl and
3336  * type of the received sequence to find the correct callback function to call
3337  * to process the sequence.
3338  **/
3339 static int
3340 lpfc_complete_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3341                          struct lpfc_iocbq *saveq, uint32_t fch_r_ctl,
3342                          uint32_t fch_type)
3343 {
3344         int i;
3345
3346         switch (fch_type) {
3347         case FC_TYPE_NVME:
3348                 lpfc_nvme_unsol_ls_handler(phba, saveq);
3349                 return 1;
3350         default:
3351                 break;
3352         }
3353
3354         /* unSolicited Responses */
3355         if (pring->prt[0].profile) {
3356                 if (pring->prt[0].lpfc_sli_rcv_unsol_event)
3357                         (pring->prt[0].lpfc_sli_rcv_unsol_event) (phba, pring,
3358                                                                         saveq);
3359                 return 1;
3360         }
3361         /* We must search, based on rctl / type
3362            for the right routine */
3363         for (i = 0; i < pring->num_mask; i++) {
3364                 if ((pring->prt[i].rctl == fch_r_ctl) &&
3365                     (pring->prt[i].type == fch_type)) {
3366                         if (pring->prt[i].lpfc_sli_rcv_unsol_event)
3367                                 (pring->prt[i].lpfc_sli_rcv_unsol_event)
3368                                                 (phba, pring, saveq);
3369                         return 1;
3370                 }
3371         }
3372         return 0;
3373 }
3374
3375 static void
3376 lpfc_sli_prep_unsol_wqe(struct lpfc_hba *phba,
3377                         struct lpfc_iocbq *saveq)
3378 {
3379         IOCB_t *irsp;
3380         union lpfc_wqe128 *wqe;
3381         u16 i = 0;
3382
3383         irsp = &saveq->iocb;
3384         wqe = &saveq->wqe;
3385
3386         /* Fill wcqe with the IOCB status fields */
3387         bf_set(lpfc_wcqe_c_status, &saveq->wcqe_cmpl, irsp->ulpStatus);
3388         saveq->wcqe_cmpl.word3 = irsp->ulpBdeCount;
3389         saveq->wcqe_cmpl.parameter = irsp->un.ulpWord[4];
3390         saveq->wcqe_cmpl.total_data_placed = irsp->unsli3.rcvsli3.acc_len;
3391
3392         /* Source ID */
3393         bf_set(els_rsp64_sid, &wqe->xmit_els_rsp, irsp->un.rcvels.parmRo);
3394
3395         /* rx-id of the response frame */
3396         bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com, irsp->ulpContext);
3397
3398         /* ox-id of the frame */
3399         bf_set(wqe_rcvoxid, &wqe->xmit_els_rsp.wqe_com,
3400                irsp->unsli3.rcvsli3.ox_id);
3401
3402         /* DID */
3403         bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest,
3404                irsp->un.rcvels.remoteID);
3405
3406         /* unsol data len */
3407         for (i = 0; i < irsp->ulpBdeCount; i++) {
3408                 struct lpfc_hbq_entry *hbqe = NULL;
3409
3410                 if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3411                         if (i == 0) {
3412                                 hbqe = (struct lpfc_hbq_entry *)
3413                                         &irsp->un.ulpWord[0];
3414                                 saveq->wqe.gen_req.bde.tus.f.bdeSize =
3415                                         hbqe->bde.tus.f.bdeSize;
3416                         } else if (i == 1) {
3417                                 hbqe = (struct lpfc_hbq_entry *)
3418                                         &irsp->unsli3.sli3Words[4];
3419                                 saveq->unsol_rcv_len = hbqe->bde.tus.f.bdeSize;
3420                         }
3421                 }
3422         }
3423 }
3424
3425 /**
3426  * lpfc_sli_process_unsol_iocb - Unsolicited iocb handler
3427  * @phba: Pointer to HBA context object.
3428  * @pring: Pointer to driver SLI ring object.
3429  * @saveq: Pointer to the unsolicited iocb.
3430  *
3431  * This function is called with no lock held by the ring event handler
3432  * when there is an unsolicited iocb posted to the response ring by the
3433  * firmware. This function gets the buffer associated with the iocbs
3434  * and calls the event handler for the ring. This function handles both
3435  * qring buffers and hbq buffers.
3436  * When the function returns 1 the caller can free the iocb object otherwise
3437  * upper layer functions will free the iocb objects.
3438  **/
3439 static int
3440 lpfc_sli_process_unsol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3441                             struct lpfc_iocbq *saveq)
3442 {
3443         IOCB_t           * irsp;
3444         WORD5            * w5p;
3445         dma_addr_t       paddr;
3446         uint32_t           Rctl, Type;
3447         struct lpfc_iocbq *iocbq;
3448         struct lpfc_dmabuf *dmzbuf;
3449
3450         irsp = &saveq->iocb;
3451         saveq->vport = phba->pport;
3452
3453         if (irsp->ulpCommand == CMD_ASYNC_STATUS) {
3454                 if (pring->lpfc_sli_rcv_async_status)
3455                         pring->lpfc_sli_rcv_async_status(phba, pring, saveq);
3456                 else
3457                         lpfc_printf_log(phba,
3458                                         KERN_WARNING,
3459                                         LOG_SLI,
3460                                         "0316 Ring %d handler: unexpected "
3461                                         "ASYNC_STATUS iocb received evt_code "
3462                                         "0x%x\n",
3463                                         pring->ringno,
3464                                         irsp->un.asyncstat.evt_code);
3465                 return 1;
3466         }
3467
3468         if ((irsp->ulpCommand == CMD_IOCB_RET_XRI64_CX) &&
3469             (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED)) {
3470                 if (irsp->ulpBdeCount > 0) {
3471                         dmzbuf = lpfc_sli_get_buff(phba, pring,
3472                                                    irsp->un.ulpWord[3]);
3473                         lpfc_in_buf_free(phba, dmzbuf);
3474                 }
3475
3476                 if (irsp->ulpBdeCount > 1) {
3477                         dmzbuf = lpfc_sli_get_buff(phba, pring,
3478                                                    irsp->unsli3.sli3Words[3]);
3479                         lpfc_in_buf_free(phba, dmzbuf);
3480                 }
3481
3482                 if (irsp->ulpBdeCount > 2) {
3483                         dmzbuf = lpfc_sli_get_buff(phba, pring,
3484                                                    irsp->unsli3.sli3Words[7]);
3485                         lpfc_in_buf_free(phba, dmzbuf);
3486                 }
3487
3488                 return 1;
3489         }
3490
3491         if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
3492                 if (irsp->ulpBdeCount != 0) {
3493                         saveq->cmd_dmabuf = lpfc_sli_get_buff(phba, pring,
3494                                                 irsp->un.ulpWord[3]);
3495                         if (!saveq->cmd_dmabuf)
3496                                 lpfc_printf_log(phba,
3497                                         KERN_ERR,
3498                                         LOG_SLI,
3499                                         "0341 Ring %d Cannot find buffer for "
3500                                         "an unsolicited iocb. tag 0x%x\n",
3501                                         pring->ringno,
3502                                         irsp->un.ulpWord[3]);
3503                 }
3504                 if (irsp->ulpBdeCount == 2) {
3505                         saveq->bpl_dmabuf = lpfc_sli_get_buff(phba, pring,
3506                                                 irsp->unsli3.sli3Words[7]);
3507                         if (!saveq->bpl_dmabuf)
3508                                 lpfc_printf_log(phba,
3509                                         KERN_ERR,
3510                                         LOG_SLI,
3511                                         "0342 Ring %d Cannot find buffer for an"
3512                                         " unsolicited iocb. tag 0x%x\n",
3513                                         pring->ringno,
3514                                         irsp->unsli3.sli3Words[7]);
3515                 }
3516                 list_for_each_entry(iocbq, &saveq->list, list) {
3517                         irsp = &iocbq->iocb;
3518                         if (irsp->ulpBdeCount != 0) {
3519                                 iocbq->cmd_dmabuf = lpfc_sli_get_buff(phba,
3520                                                         pring,
3521                                                         irsp->un.ulpWord[3]);
3522                                 if (!iocbq->cmd_dmabuf)
3523                                         lpfc_printf_log(phba,
3524                                                 KERN_ERR,
3525                                                 LOG_SLI,
3526                                                 "0343 Ring %d Cannot find "
3527                                                 "buffer for an unsolicited iocb"
3528                                                 ". tag 0x%x\n", pring->ringno,
3529                                                 irsp->un.ulpWord[3]);
3530                         }
3531                         if (irsp->ulpBdeCount == 2) {
3532                                 iocbq->bpl_dmabuf = lpfc_sli_get_buff(phba,
3533                                                 pring,
3534                                                 irsp->unsli3.sli3Words[7]);
3535                                 if (!iocbq->bpl_dmabuf)
3536                                         lpfc_printf_log(phba,
3537                                                 KERN_ERR,
3538                                                 LOG_SLI,
3539                                                 "0344 Ring %d Cannot find "
3540                                                 "buffer for an unsolicited "
3541                                                 "iocb. tag 0x%x\n",
3542                                                 pring->ringno,
3543                                                 irsp->unsli3.sli3Words[7]);
3544                         }
3545                 }
3546         } else {
3547                 paddr = getPaddr(irsp->un.cont64[0].addrHigh,
3548                                  irsp->un.cont64[0].addrLow);
3549                 saveq->cmd_dmabuf = lpfc_sli_ringpostbuf_get(phba, pring,
3550                                                              paddr);
3551                 if (irsp->ulpBdeCount == 2) {
3552                         paddr = getPaddr(irsp->un.cont64[1].addrHigh,
3553                                          irsp->un.cont64[1].addrLow);
3554                         saveq->bpl_dmabuf = lpfc_sli_ringpostbuf_get(phba,
3555                                                                    pring,
3556                                                                    paddr);
3557                 }
3558         }
3559
3560         if (irsp->ulpBdeCount != 0 &&
3561             (irsp->ulpCommand == CMD_IOCB_RCV_CONT64_CX ||
3562              irsp->ulpStatus == IOSTAT_INTERMED_RSP)) {
3563                 int found = 0;
3564
3565                 /* search continue save q for same XRI */
3566                 list_for_each_entry(iocbq, &pring->iocb_continue_saveq, clist) {
3567                         if (iocbq->iocb.unsli3.rcvsli3.ox_id ==
3568                                 saveq->iocb.unsli3.rcvsli3.ox_id) {
3569                                 list_add_tail(&saveq->list, &iocbq->list);
3570                                 found = 1;
3571                                 break;
3572                         }
3573                 }
3574                 if (!found)
3575                         list_add_tail(&saveq->clist,
3576                                       &pring->iocb_continue_saveq);
3577
3578                 if (saveq->iocb.ulpStatus != IOSTAT_INTERMED_RSP) {
3579                         list_del_init(&iocbq->clist);
3580                         saveq = iocbq;
3581                         irsp = &saveq->iocb;
3582                 } else {
3583                         return 0;
3584                 }
3585         }
3586         if ((irsp->ulpCommand == CMD_RCV_ELS_REQ64_CX) ||
3587             (irsp->ulpCommand == CMD_RCV_ELS_REQ_CX) ||
3588             (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX)) {
3589                 Rctl = FC_RCTL_ELS_REQ;
3590                 Type = FC_TYPE_ELS;
3591         } else {
3592                 w5p = (WORD5 *)&(saveq->iocb.un.ulpWord[5]);
3593                 Rctl = w5p->hcsw.Rctl;
3594                 Type = w5p->hcsw.Type;
3595
3596                 /* Firmware Workaround */
3597                 if ((Rctl == 0) && (pring->ringno == LPFC_ELS_RING) &&
3598                         (irsp->ulpCommand == CMD_RCV_SEQUENCE64_CX ||
3599                          irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3600                         Rctl = FC_RCTL_ELS_REQ;
3601                         Type = FC_TYPE_ELS;
3602                         w5p->hcsw.Rctl = Rctl;
3603                         w5p->hcsw.Type = Type;
3604                 }
3605         }
3606
3607         if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) &&
3608             (irsp->ulpCommand == CMD_IOCB_RCV_ELS64_CX ||
3609             irsp->ulpCommand == CMD_IOCB_RCV_SEQ64_CX)) {
3610                 if (irsp->unsli3.rcvsli3.vpi == 0xffff)
3611                         saveq->vport = phba->pport;
3612                 else
3613                         saveq->vport = lpfc_find_vport_by_vpid(phba,
3614                                                irsp->unsli3.rcvsli3.vpi);
3615         }
3616
3617         /* Prepare WQE with Unsol frame */
3618         lpfc_sli_prep_unsol_wqe(phba, saveq);
3619
3620         if (!lpfc_complete_unsol_iocb(phba, pring, saveq, Rctl, Type))
3621                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3622                                 "0313 Ring %d handler: unexpected Rctl x%x "
3623                                 "Type x%x received\n",
3624                                 pring->ringno, Rctl, Type);
3625
3626         return 1;
3627 }
3628
3629 /**
3630  * lpfc_sli_iocbq_lookup - Find command iocb for the given response iocb
3631  * @phba: Pointer to HBA context object.
3632  * @pring: Pointer to driver SLI ring object.
3633  * @prspiocb: Pointer to response iocb object.
3634  *
3635  * This function looks up the iocb_lookup table to get the command iocb
3636  * corresponding to the given response iocb using the iotag of the
3637  * response iocb. The driver calls this function with the hbalock held
3638  * for SLI3 ports or the ring lock held for SLI4 ports.
3639  * This function returns the command iocb object if it finds the command
3640  * iocb else returns NULL.
3641  **/
3642 static struct lpfc_iocbq *
3643 lpfc_sli_iocbq_lookup(struct lpfc_hba *phba,
3644                       struct lpfc_sli_ring *pring,
3645                       struct lpfc_iocbq *prspiocb)
3646 {
3647         struct lpfc_iocbq *cmd_iocb = NULL;
3648         u16 iotag;
3649
3650         if (phba->sli_rev == LPFC_SLI_REV4)
3651                 iotag = get_wqe_reqtag(prspiocb);
3652         else
3653                 iotag = prspiocb->iocb.ulpIoTag;
3654
3655         if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3656                 cmd_iocb = phba->sli.iocbq_lookup[iotag];
3657                 if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3658                         /* remove from txcmpl queue list */
3659                         list_del_init(&cmd_iocb->list);
3660                         cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3661                         pring->txcmplq_cnt--;
3662                         return cmd_iocb;
3663                 }
3664         }
3665
3666         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3667                         "0317 iotag x%x is out of "
3668                         "range: max iotag x%x\n",
3669                         iotag, phba->sli.last_iotag);
3670         return NULL;
3671 }
3672
3673 /**
3674  * lpfc_sli_iocbq_lookup_by_tag - Find command iocb for the iotag
3675  * @phba: Pointer to HBA context object.
3676  * @pring: Pointer to driver SLI ring object.
3677  * @iotag: IOCB tag.
3678  *
3679  * This function looks up the iocb_lookup table to get the command iocb
3680  * corresponding to the given iotag. The driver calls this function with
3681  * the ring lock held because this function is an SLI4 port only helper.
3682  * This function returns the command iocb object if it finds the command
3683  * iocb else returns NULL.
3684  **/
3685 static struct lpfc_iocbq *
3686 lpfc_sli_iocbq_lookup_by_tag(struct lpfc_hba *phba,
3687                              struct lpfc_sli_ring *pring, uint16_t iotag)
3688 {
3689         struct lpfc_iocbq *cmd_iocb = NULL;
3690
3691         if (iotag != 0 && iotag <= phba->sli.last_iotag) {
3692                 cmd_iocb = phba->sli.iocbq_lookup[iotag];
3693                 if (cmd_iocb->cmd_flag & LPFC_IO_ON_TXCMPLQ) {
3694                         /* remove from txcmpl queue list */
3695                         list_del_init(&cmd_iocb->list);
3696                         cmd_iocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
3697                         pring->txcmplq_cnt--;
3698                         return cmd_iocb;
3699                 }
3700         }
3701
3702         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3703                         "0372 iotag x%x lookup error: max iotag (x%x) "
3704                         "cmd_flag x%x\n",
3705                         iotag, phba->sli.last_iotag,
3706                         cmd_iocb ? cmd_iocb->cmd_flag : 0xffff);
3707         return NULL;
3708 }
3709
3710 /**
3711  * lpfc_sli_process_sol_iocb - process solicited iocb completion
3712  * @phba: Pointer to HBA context object.
3713  * @pring: Pointer to driver SLI ring object.
3714  * @saveq: Pointer to the response iocb to be processed.
3715  *
3716  * This function is called by the ring event handler for non-fcp
3717  * rings when there is a new response iocb in the response ring.
3718  * The caller is not required to hold any locks. This function
3719  * gets the command iocb associated with the response iocb and
3720  * calls the completion handler for the command iocb. If there
3721  * is no completion handler, the function will free the resources
3722  * associated with command iocb. If the response iocb is for
3723  * an already aborted command iocb, the status of the completion
3724  * is changed to IOSTAT_LOCAL_REJECT/IOERR_SLI_ABORTED.
3725  * This function always returns 1.
3726  **/
3727 static int
3728 lpfc_sli_process_sol_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
3729                           struct lpfc_iocbq *saveq)
3730 {
3731         struct lpfc_iocbq *cmdiocbp;
3732         unsigned long iflag;
3733         u32 ulp_command, ulp_status, ulp_word4, ulp_context, iotag;
3734
3735         if (phba->sli_rev == LPFC_SLI_REV4)
3736                 spin_lock_irqsave(&pring->ring_lock, iflag);
3737         else
3738                 spin_lock_irqsave(&phba->hbalock, iflag);
3739         cmdiocbp = lpfc_sli_iocbq_lookup(phba, pring, saveq);
3740         if (phba->sli_rev == LPFC_SLI_REV4)
3741                 spin_unlock_irqrestore(&pring->ring_lock, iflag);
3742         else
3743                 spin_unlock_irqrestore(&phba->hbalock, iflag);
3744
3745         ulp_command = get_job_cmnd(phba, saveq);
3746         ulp_status = get_job_ulpstatus(phba, saveq);
3747         ulp_word4 = get_job_word4(phba, saveq);
3748         ulp_context = get_job_ulpcontext(phba, saveq);
3749         if (phba->sli_rev == LPFC_SLI_REV4)
3750                 iotag = get_wqe_reqtag(saveq);
3751         else
3752                 iotag = saveq->iocb.ulpIoTag;
3753
3754         if (cmdiocbp) {
3755                 ulp_command = get_job_cmnd(phba, cmdiocbp);
3756                 if (cmdiocbp->cmd_cmpl) {
3757                         /*
3758                          * If an ELS command failed send an event to mgmt
3759                          * application.
3760                          */
3761                         if (ulp_status &&
3762                              (pring->ringno == LPFC_ELS_RING) &&
3763                              (ulp_command == CMD_ELS_REQUEST64_CR))
3764                                 lpfc_send_els_failure_event(phba,
3765                                         cmdiocbp, saveq);
3766
3767                         /*
3768                          * Post all ELS completions to the worker thread.
3769                          * All other are passed to the completion callback.
3770                          */
3771                         if (pring->ringno == LPFC_ELS_RING) {
3772                                 if ((phba->sli_rev < LPFC_SLI_REV4) &&
3773                                     (cmdiocbp->cmd_flag &
3774                                                         LPFC_DRIVER_ABORTED)) {
3775                                         spin_lock_irqsave(&phba->hbalock,
3776                                                           iflag);
3777                                         cmdiocbp->cmd_flag &=
3778                                                 ~LPFC_DRIVER_ABORTED;
3779                                         spin_unlock_irqrestore(&phba->hbalock,
3780                                                                iflag);
3781                                         saveq->iocb.ulpStatus =
3782                                                 IOSTAT_LOCAL_REJECT;
3783                                         saveq->iocb.un.ulpWord[4] =
3784                                                 IOERR_SLI_ABORTED;
3785
3786                                         /* Firmware could still be in progress
3787                                          * of DMAing payload, so don't free data
3788                                          * buffer till after a hbeat.
3789                                          */
3790                                         spin_lock_irqsave(&phba->hbalock,
3791                                                           iflag);
3792                                         saveq->cmd_flag |= LPFC_DELAY_MEM_FREE;
3793                                         spin_unlock_irqrestore(&phba->hbalock,
3794                                                                iflag);
3795                                 }
3796                                 if (phba->sli_rev == LPFC_SLI_REV4) {
3797                                         if (saveq->cmd_flag &
3798                                             LPFC_EXCHANGE_BUSY) {
3799                                                 /* Set cmdiocb flag for the
3800                                                  * exchange busy so sgl (xri)
3801                                                  * will not be released until
3802                                                  * the abort xri is received
3803                                                  * from hba.
3804                                                  */
3805                                                 spin_lock_irqsave(
3806                                                         &phba->hbalock, iflag);
3807                                                 cmdiocbp->cmd_flag |=
3808                                                         LPFC_EXCHANGE_BUSY;
3809                                                 spin_unlock_irqrestore(
3810                                                         &phba->hbalock, iflag);
3811                                         }
3812                                         if (cmdiocbp->cmd_flag &
3813                                             LPFC_DRIVER_ABORTED) {
3814                                                 /*
3815                                                  * Clear LPFC_DRIVER_ABORTED
3816                                                  * bit in case it was driver
3817                                                  * initiated abort.
3818                                                  */
3819                                                 spin_lock_irqsave(
3820                                                         &phba->hbalock, iflag);
3821                                                 cmdiocbp->cmd_flag &=
3822                                                         ~LPFC_DRIVER_ABORTED;
3823                                                 spin_unlock_irqrestore(
3824                                                         &phba->hbalock, iflag);
3825                                                 set_job_ulpstatus(cmdiocbp,
3826                                                                   IOSTAT_LOCAL_REJECT);
3827                                                 set_job_ulpword4(cmdiocbp,
3828                                                                  IOERR_ABORT_REQUESTED);
3829                                                 /*
3830                                                  * For SLI4, irspiocb contains
3831                                                  * NO_XRI in sli_xritag, it
3832                                                  * shall not affect releasing
3833                                                  * sgl (xri) process.
3834                                                  */
3835                                                 set_job_ulpstatus(saveq,
3836                                                                   IOSTAT_LOCAL_REJECT);
3837                                                 set_job_ulpword4(saveq,
3838                                                                  IOERR_SLI_ABORTED);
3839                                                 spin_lock_irqsave(
3840                                                         &phba->hbalock, iflag);
3841                                                 saveq->cmd_flag |=
3842                                                         LPFC_DELAY_MEM_FREE;
3843                                                 spin_unlock_irqrestore(
3844                                                         &phba->hbalock, iflag);
3845                                         }
3846                                 }
3847                         }
3848                         cmdiocbp->cmd_cmpl(phba, cmdiocbp, saveq);
3849                 } else
3850                         lpfc_sli_release_iocbq(phba, cmdiocbp);
3851         } else {
3852                 /*
3853                  * Unknown initiating command based on the response iotag.
3854                  * This could be the case on the ELS ring because of
3855                  * lpfc_els_abort().
3856                  */
3857                 if (pring->ringno != LPFC_ELS_RING) {
3858                         /*
3859                          * Ring <ringno> handler: unexpected completion IoTag
3860                          * <IoTag>
3861                          */
3862                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
3863                                          "0322 Ring %d handler: "
3864                                          "unexpected completion IoTag x%x "
3865                                          "Data: x%x x%x x%x x%x\n",
3866                                          pring->ringno, iotag, ulp_status,
3867                                          ulp_word4, ulp_command, ulp_context);
3868                 }
3869         }
3870
3871         return 1;
3872 }
3873
3874 /**
3875  * lpfc_sli_rsp_pointers_error - Response ring pointer error handler
3876  * @phba: Pointer to HBA context object.
3877  * @pring: Pointer to driver SLI ring object.
3878  *
3879  * This function is called from the iocb ring event handlers when
3880  * put pointer is ahead of the get pointer for a ring. This function signal
3881  * an error attention condition to the worker thread and the worker
3882  * thread will transition the HBA to offline state.
3883  **/
3884 static void
3885 lpfc_sli_rsp_pointers_error(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
3886 {
3887         struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3888         /*
3889          * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
3890          * rsp ring <portRspMax>
3891          */
3892         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
3893                         "0312 Ring %d handler: portRspPut %d "
3894                         "is bigger than rsp ring %d\n",
3895                         pring->ringno, le32_to_cpu(pgp->rspPutInx),
3896                         pring->sli.sli3.numRiocb);
3897
3898         phba->link_state = LPFC_HBA_ERROR;
3899
3900         /*
3901          * All error attention handlers are posted to
3902          * worker thread
3903          */
3904         phba->work_ha |= HA_ERATT;
3905         phba->work_hs = HS_FFER3;
3906
3907         lpfc_worker_wake_up(phba);
3908
3909         return;
3910 }
3911
3912 /**
3913  * lpfc_poll_eratt - Error attention polling timer timeout handler
3914  * @t: Context to fetch pointer to address of HBA context object from.
3915  *
3916  * This function is invoked by the Error Attention polling timer when the
3917  * timer times out. It will check the SLI Error Attention register for
3918  * possible attention events. If so, it will post an Error Attention event
3919  * and wake up worker thread to process it. Otherwise, it will set up the
3920  * Error Attention polling timer for the next poll.
3921  **/
3922 void lpfc_poll_eratt(struct timer_list *t)
3923 {
3924         struct lpfc_hba *phba;
3925         uint32_t eratt = 0;
3926         uint64_t sli_intr, cnt;
3927
3928         phba = from_timer(phba, t, eratt_poll);
3929         if (!test_bit(HBA_SETUP, &phba->hba_flag))
3930                 return;
3931
3932         if (test_bit(FC_UNLOADING, &phba->pport->load_flag))
3933                 return;
3934
3935         /* Here we will also keep track of interrupts per sec of the hba */
3936         sli_intr = phba->sli.slistat.sli_intr;
3937
3938         if (phba->sli.slistat.sli_prev_intr > sli_intr)
3939                 cnt = (((uint64_t)(-1) - phba->sli.slistat.sli_prev_intr) +
3940                         sli_intr);
3941         else
3942                 cnt = (sli_intr - phba->sli.slistat.sli_prev_intr);
3943
3944         /* 64-bit integer division not supported on 32-bit x86 - use do_div */
3945         do_div(cnt, phba->eratt_poll_interval);
3946         phba->sli.slistat.sli_ips = cnt;
3947
3948         phba->sli.slistat.sli_prev_intr = sli_intr;
3949
3950         /* Check chip HA register for error event */
3951         eratt = lpfc_sli_check_eratt(phba);
3952
3953         if (eratt)
3954                 /* Tell the worker thread there is work to do */
3955                 lpfc_worker_wake_up(phba);
3956         else
3957                 /* Restart the timer for next eratt poll */
3958                 mod_timer(&phba->eratt_poll,
3959                           jiffies +
3960                           msecs_to_jiffies(1000 * phba->eratt_poll_interval));
3961         return;
3962 }
3963
3964
3965 /**
3966  * lpfc_sli_handle_fast_ring_event - Handle ring events on FCP ring
3967  * @phba: Pointer to HBA context object.
3968  * @pring: Pointer to driver SLI ring object.
3969  * @mask: Host attention register mask for this ring.
3970  *
3971  * This function is called from the interrupt context when there is a ring
3972  * event for the fcp ring. The caller does not hold any lock.
3973  * The function processes each response iocb in the response ring until it
3974  * finds an iocb with LE bit set and chains all the iocbs up to the iocb with
3975  * LE bit set. The function will call the completion handler of the command iocb
3976  * if the response iocb indicates a completion for a command iocb or it is
3977  * an abort completion. The function will call lpfc_sli_process_unsol_iocb
3978  * function if this is an unsolicited iocb.
3979  * This routine presumes LPFC_FCP_RING handling and doesn't bother
3980  * to check it explicitly.
3981  */
3982 int
3983 lpfc_sli_handle_fast_ring_event(struct lpfc_hba *phba,
3984                                 struct lpfc_sli_ring *pring, uint32_t mask)
3985 {
3986         struct lpfc_pgp *pgp = &phba->port_gp[pring->ringno];
3987         IOCB_t *irsp = NULL;
3988         IOCB_t *entry = NULL;
3989         struct lpfc_iocbq *cmdiocbq = NULL;
3990         struct lpfc_iocbq rspiocbq;
3991         uint32_t status;
3992         uint32_t portRspPut, portRspMax;
3993         int rc = 1;
3994         lpfc_iocb_type type;
3995         unsigned long iflag;
3996         uint32_t rsp_cmpl = 0;
3997
3998         spin_lock_irqsave(&phba->hbalock, iflag);
3999         pring->stats.iocb_event++;
4000
4001         /*
4002          * The next available response entry should never exceed the maximum
4003          * entries.  If it does, treat it as an adapter hardware error.
4004          */
4005         portRspMax = pring->sli.sli3.numRiocb;
4006         portRspPut = le32_to_cpu(pgp->rspPutInx);
4007         if (unlikely(portRspPut >= portRspMax)) {
4008                 lpfc_sli_rsp_pointers_error(phba, pring);
4009                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4010                 return 1;
4011         }
4012         if (phba->fcp_ring_in_use) {
4013                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4014                 return 1;
4015         } else
4016                 phba->fcp_ring_in_use = 1;
4017
4018         rmb();
4019         while (pring->sli.sli3.rspidx != portRspPut) {
4020                 /*
4021                  * Fetch an entry off the ring and copy it into a local data
4022                  * structure.  The copy involves a byte-swap since the
4023                  * network byte order and pci byte orders are different.
4024                  */
4025                 entry = lpfc_resp_iocb(phba, pring);
4026                 phba->last_completion_time = jiffies;
4027
4028                 if (++pring->sli.sli3.rspidx >= portRspMax)
4029                         pring->sli.sli3.rspidx = 0;
4030
4031                 lpfc_sli_pcimem_bcopy((uint32_t *) entry,
4032                                       (uint32_t *) &rspiocbq.iocb,
4033                                       phba->iocb_rsp_size);
4034                 INIT_LIST_HEAD(&(rspiocbq.list));
4035                 irsp = &rspiocbq.iocb;
4036
4037                 type = lpfc_sli_iocb_cmd_type(irsp->ulpCommand & CMD_IOCB_MASK);
4038                 pring->stats.iocb_rsp++;
4039                 rsp_cmpl++;
4040
4041                 if (unlikely(irsp->ulpStatus)) {
4042                         /*
4043                          * If resource errors reported from HBA, reduce
4044                          * queuedepths of the SCSI device.
4045                          */
4046                         if ((irsp->ulpStatus == IOSTAT_LOCAL_REJECT) &&
4047                             ((irsp->un.ulpWord[4] & IOERR_PARAM_MASK) ==
4048                              IOERR_NO_RESOURCES)) {
4049                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4050                                 phba->lpfc_rampdown_queue_depth(phba);
4051                                 spin_lock_irqsave(&phba->hbalock, iflag);
4052                         }
4053
4054                         /* Rsp ring <ringno> error: IOCB */
4055                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4056                                         "0336 Rsp Ring %d error: IOCB Data: "
4057                                         "x%x x%x x%x x%x x%x x%x x%x x%x\n",
4058                                         pring->ringno,
4059                                         irsp->un.ulpWord[0],
4060                                         irsp->un.ulpWord[1],
4061                                         irsp->un.ulpWord[2],
4062                                         irsp->un.ulpWord[3],
4063                                         irsp->un.ulpWord[4],
4064                                         irsp->un.ulpWord[5],
4065                                         *(uint32_t *)&irsp->un1,
4066                                         *((uint32_t *)&irsp->un1 + 1));
4067                 }
4068
4069                 switch (type) {
4070                 case LPFC_ABORT_IOCB:
4071                 case LPFC_SOL_IOCB:
4072                         /*
4073                          * Idle exchange closed via ABTS from port.  No iocb
4074                          * resources need to be recovered.
4075                          */
4076                         if (unlikely(irsp->ulpCommand == CMD_XRI_ABORTED_CX)) {
4077                                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4078                                                 "0333 IOCB cmd 0x%x"
4079                                                 " processed. Skipping"
4080                                                 " completion\n",
4081                                                 irsp->ulpCommand);
4082                                 break;
4083                         }
4084
4085                         cmdiocbq = lpfc_sli_iocbq_lookup(phba, pring,
4086                                                          &rspiocbq);
4087                         if (unlikely(!cmdiocbq))
4088                                 break;
4089                         if (cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED)
4090                                 cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
4091                         if (cmdiocbq->cmd_cmpl) {
4092                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4093                                 cmdiocbq->cmd_cmpl(phba, cmdiocbq, &rspiocbq);
4094                                 spin_lock_irqsave(&phba->hbalock, iflag);
4095                         }
4096                         break;
4097                 case LPFC_UNSOL_IOCB:
4098                         spin_unlock_irqrestore(&phba->hbalock, iflag);
4099                         lpfc_sli_process_unsol_iocb(phba, pring, &rspiocbq);
4100                         spin_lock_irqsave(&phba->hbalock, iflag);
4101                         break;
4102                 default:
4103                         if (irsp->ulpCommand == CMD_ADAPTER_MSG) {
4104                                 char adaptermsg[LPFC_MAX_ADPTMSG];
4105                                 memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4106                                 memcpy(&adaptermsg[0], (uint8_t *) irsp,
4107                                        MAX_MSG_DATA);
4108                                 dev_warn(&((phba->pcidev)->dev),
4109                                          "lpfc%d: %s\n",
4110                                          phba->brd_no, adaptermsg);
4111                         } else {
4112                                 /* Unknown IOCB command */
4113                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4114                                                 "0334 Unknown IOCB command "
4115                                                 "Data: x%x, x%x x%x x%x x%x\n",
4116                                                 type, irsp->ulpCommand,
4117                                                 irsp->ulpStatus,
4118                                                 irsp->ulpIoTag,
4119                                                 irsp->ulpContext);
4120                         }
4121                         break;
4122                 }
4123
4124                 /*
4125                  * The response IOCB has been processed.  Update the ring
4126                  * pointer in SLIM.  If the port response put pointer has not
4127                  * been updated, sync the pgp->rspPutInx and fetch the new port
4128                  * response put pointer.
4129                  */
4130                 writel(pring->sli.sli3.rspidx,
4131                         &phba->host_gp[pring->ringno].rspGetInx);
4132
4133                 if (pring->sli.sli3.rspidx == portRspPut)
4134                         portRspPut = le32_to_cpu(pgp->rspPutInx);
4135         }
4136
4137         if ((rsp_cmpl > 0) && (mask & HA_R0RE_REQ)) {
4138                 pring->stats.iocb_rsp_full++;
4139                 status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4140                 writel(status, phba->CAregaddr);
4141                 readl(phba->CAregaddr);
4142         }
4143         if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4144                 pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4145                 pring->stats.iocb_cmd_empty++;
4146
4147                 /* Force update of the local copy of cmdGetInx */
4148                 pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4149                 lpfc_sli_resume_iocb(phba, pring);
4150
4151                 if ((pring->lpfc_sli_cmd_available))
4152                         (pring->lpfc_sli_cmd_available) (phba, pring);
4153
4154         }
4155
4156         phba->fcp_ring_in_use = 0;
4157         spin_unlock_irqrestore(&phba->hbalock, iflag);
4158         return rc;
4159 }
4160
4161 /**
4162  * lpfc_sli_sp_handle_rspiocb - Handle slow-path response iocb
4163  * @phba: Pointer to HBA context object.
4164  * @pring: Pointer to driver SLI ring object.
4165  * @rspiocbp: Pointer to driver response IOCB object.
4166  *
4167  * This function is called from the worker thread when there is a slow-path
4168  * response IOCB to process. This function chains all the response iocbs until
4169  * seeing the iocb with the LE bit set. The function will call
4170  * lpfc_sli_process_sol_iocb function if the response iocb indicates a
4171  * completion of a command iocb. The function will call the
4172  * lpfc_sli_process_unsol_iocb function if this is an unsolicited iocb.
4173  * The function frees the resources or calls the completion handler if this
4174  * iocb is an abort completion. The function returns NULL when the response
4175  * iocb has the LE bit set and all the chained iocbs are processed, otherwise
4176  * this function shall chain the iocb on to the iocb_continueq and return the
4177  * response iocb passed in.
4178  **/
4179 static struct lpfc_iocbq *
4180 lpfc_sli_sp_handle_rspiocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
4181                         struct lpfc_iocbq *rspiocbp)
4182 {
4183         struct lpfc_iocbq *saveq;
4184         struct lpfc_iocbq *cmdiocb;
4185         struct lpfc_iocbq *next_iocb;
4186         IOCB_t *irsp;
4187         uint32_t free_saveq;
4188         u8 cmd_type;
4189         lpfc_iocb_type type;
4190         unsigned long iflag;
4191         u32 ulp_status = get_job_ulpstatus(phba, rspiocbp);
4192         u32 ulp_word4 = get_job_word4(phba, rspiocbp);
4193         u32 ulp_command = get_job_cmnd(phba, rspiocbp);
4194         int rc;
4195
4196         spin_lock_irqsave(&phba->hbalock, iflag);
4197         /* First add the response iocb to the countinueq list */
4198         list_add_tail(&rspiocbp->list, &pring->iocb_continueq);
4199         pring->iocb_continueq_cnt++;
4200
4201         /*
4202          * By default, the driver expects to free all resources
4203          * associated with this iocb completion.
4204          */
4205         free_saveq = 1;
4206         saveq = list_get_first(&pring->iocb_continueq,
4207                                struct lpfc_iocbq, list);
4208         list_del_init(&pring->iocb_continueq);
4209         pring->iocb_continueq_cnt = 0;
4210
4211         pring->stats.iocb_rsp++;
4212
4213         /*
4214          * If resource errors reported from HBA, reduce
4215          * queuedepths of the SCSI device.
4216          */
4217         if (ulp_status == IOSTAT_LOCAL_REJECT &&
4218             ((ulp_word4 & IOERR_PARAM_MASK) ==
4219              IOERR_NO_RESOURCES)) {
4220                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4221                 phba->lpfc_rampdown_queue_depth(phba);
4222                 spin_lock_irqsave(&phba->hbalock, iflag);
4223         }
4224
4225         if (ulp_status) {
4226                 /* Rsp ring <ringno> error: IOCB */
4227                 if (phba->sli_rev < LPFC_SLI_REV4) {
4228                         irsp = &rspiocbp->iocb;
4229                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4230                                         "0328 Rsp Ring %d error: ulp_status x%x "
4231                                         "IOCB Data: "
4232                                         "x%08x x%08x x%08x x%08x "
4233                                         "x%08x x%08x x%08x x%08x "
4234                                         "x%08x x%08x x%08x x%08x "
4235                                         "x%08x x%08x x%08x x%08x\n",
4236                                         pring->ringno, ulp_status,
4237                                         get_job_ulpword(rspiocbp, 0),
4238                                         get_job_ulpword(rspiocbp, 1),
4239                                         get_job_ulpword(rspiocbp, 2),
4240                                         get_job_ulpword(rspiocbp, 3),
4241                                         get_job_ulpword(rspiocbp, 4),
4242                                         get_job_ulpword(rspiocbp, 5),
4243                                         *(((uint32_t *)irsp) + 6),
4244                                         *(((uint32_t *)irsp) + 7),
4245                                         *(((uint32_t *)irsp) + 8),
4246                                         *(((uint32_t *)irsp) + 9),
4247                                         *(((uint32_t *)irsp) + 10),
4248                                         *(((uint32_t *)irsp) + 11),
4249                                         *(((uint32_t *)irsp) + 12),
4250                                         *(((uint32_t *)irsp) + 13),
4251                                         *(((uint32_t *)irsp) + 14),
4252                                         *(((uint32_t *)irsp) + 15));
4253                 } else {
4254                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
4255                                         "0321 Rsp Ring %d error: "
4256                                         "IOCB Data: "
4257                                         "x%x x%x x%x x%x\n",
4258                                         pring->ringno,
4259                                         rspiocbp->wcqe_cmpl.word0,
4260                                         rspiocbp->wcqe_cmpl.total_data_placed,
4261                                         rspiocbp->wcqe_cmpl.parameter,
4262                                         rspiocbp->wcqe_cmpl.word3);
4263                 }
4264         }
4265
4266
4267         /*
4268          * Fetch the iocb command type and call the correct completion
4269          * routine. Solicited and Unsolicited IOCBs on the ELS ring
4270          * get freed back to the lpfc_iocb_list by the discovery
4271          * kernel thread.
4272          */
4273         cmd_type = ulp_command & CMD_IOCB_MASK;
4274         type = lpfc_sli_iocb_cmd_type(cmd_type);
4275         switch (type) {
4276         case LPFC_SOL_IOCB:
4277                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4278                 rc = lpfc_sli_process_sol_iocb(phba, pring, saveq);
4279                 spin_lock_irqsave(&phba->hbalock, iflag);
4280                 break;
4281         case LPFC_UNSOL_IOCB:
4282                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4283                 rc = lpfc_sli_process_unsol_iocb(phba, pring, saveq);
4284                 spin_lock_irqsave(&phba->hbalock, iflag);
4285                 if (!rc)
4286                         free_saveq = 0;
4287                 break;
4288         case LPFC_ABORT_IOCB:
4289                 cmdiocb = NULL;
4290                 if (ulp_command != CMD_XRI_ABORTED_CX)
4291                         cmdiocb = lpfc_sli_iocbq_lookup(phba, pring,
4292                                                         saveq);
4293                 if (cmdiocb) {
4294                         /* Call the specified completion routine */
4295                         if (cmdiocb->cmd_cmpl) {
4296                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4297                                 cmdiocb->cmd_cmpl(phba, cmdiocb, saveq);
4298                                 spin_lock_irqsave(&phba->hbalock, iflag);
4299                         } else {
4300                                 __lpfc_sli_release_iocbq(phba, cmdiocb);
4301                         }
4302                 }
4303                 break;
4304         case LPFC_UNKNOWN_IOCB:
4305                 if (ulp_command == CMD_ADAPTER_MSG) {
4306                         char adaptermsg[LPFC_MAX_ADPTMSG];
4307
4308                         memset(adaptermsg, 0, LPFC_MAX_ADPTMSG);
4309                         memcpy(&adaptermsg[0], (uint8_t *)&rspiocbp->wqe,
4310                                MAX_MSG_DATA);
4311                         dev_warn(&((phba->pcidev)->dev),
4312                                  "lpfc%d: %s\n",
4313                                  phba->brd_no, adaptermsg);
4314                 } else {
4315                         /* Unknown command */
4316                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4317                                         "0335 Unknown IOCB "
4318                                         "command Data: x%x "
4319                                         "x%x x%x x%x\n",
4320                                         ulp_command,
4321                                         ulp_status,
4322                                         get_wqe_reqtag(rspiocbp),
4323                                         get_job_ulpcontext(phba, rspiocbp));
4324                 }
4325                 break;
4326         }
4327
4328         if (free_saveq) {
4329                 list_for_each_entry_safe(rspiocbp, next_iocb,
4330                                          &saveq->list, list) {
4331                         list_del_init(&rspiocbp->list);
4332                         __lpfc_sli_release_iocbq(phba, rspiocbp);
4333                 }
4334                 __lpfc_sli_release_iocbq(phba, saveq);
4335         }
4336         rspiocbp = NULL;
4337         spin_unlock_irqrestore(&phba->hbalock, iflag);
4338         return rspiocbp;
4339 }
4340
4341 /**
4342  * lpfc_sli_handle_slow_ring_event - Wrapper func for handling slow-path iocbs
4343  * @phba: Pointer to HBA context object.
4344  * @pring: Pointer to driver SLI ring object.
4345  * @mask: Host attention register mask for this ring.
4346  *
4347  * This routine wraps the actual slow_ring event process routine from the
4348  * API jump table function pointer from the lpfc_hba struct.
4349  **/
4350 void
4351 lpfc_sli_handle_slow_ring_event(struct lpfc_hba *phba,
4352                                 struct lpfc_sli_ring *pring, uint32_t mask)
4353 {
4354         phba->lpfc_sli_handle_slow_ring_event(phba, pring, mask);
4355 }
4356
4357 /**
4358  * lpfc_sli_handle_slow_ring_event_s3 - Handle SLI3 ring event for non-FCP rings
4359  * @phba: Pointer to HBA context object.
4360  * @pring: Pointer to driver SLI ring object.
4361  * @mask: Host attention register mask for this ring.
4362  *
4363  * This function is called from the worker thread when there is a ring event
4364  * for non-fcp rings. The caller does not hold any lock. The function will
4365  * remove each response iocb in the response ring and calls the handle
4366  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4367  **/
4368 static void
4369 lpfc_sli_handle_slow_ring_event_s3(struct lpfc_hba *phba,
4370                                    struct lpfc_sli_ring *pring, uint32_t mask)
4371 {
4372         struct lpfc_pgp *pgp;
4373         IOCB_t *entry;
4374         IOCB_t *irsp = NULL;
4375         struct lpfc_iocbq *rspiocbp = NULL;
4376         uint32_t portRspPut, portRspMax;
4377         unsigned long iflag;
4378         uint32_t status;
4379
4380         pgp = &phba->port_gp[pring->ringno];
4381         spin_lock_irqsave(&phba->hbalock, iflag);
4382         pring->stats.iocb_event++;
4383
4384         /*
4385          * The next available response entry should never exceed the maximum
4386          * entries.  If it does, treat it as an adapter hardware error.
4387          */
4388         portRspMax = pring->sli.sli3.numRiocb;
4389         portRspPut = le32_to_cpu(pgp->rspPutInx);
4390         if (portRspPut >= portRspMax) {
4391                 /*
4392                  * Ring <ringno> handler: portRspPut <portRspPut> is bigger than
4393                  * rsp ring <portRspMax>
4394                  */
4395                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4396                                 "0303 Ring %d handler: portRspPut %d "
4397                                 "is bigger than rsp ring %d\n",
4398                                 pring->ringno, portRspPut, portRspMax);
4399
4400                 phba->link_state = LPFC_HBA_ERROR;
4401                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4402
4403                 phba->work_hs = HS_FFER3;
4404                 lpfc_handle_eratt(phba);
4405
4406                 return;
4407         }
4408
4409         rmb();
4410         while (pring->sli.sli3.rspidx != portRspPut) {
4411                 /*
4412                  * Build a completion list and call the appropriate handler.
4413                  * The process is to get the next available response iocb, get
4414                  * a free iocb from the list, copy the response data into the
4415                  * free iocb, insert to the continuation list, and update the
4416                  * next response index to slim.  This process makes response
4417                  * iocb's in the ring available to DMA as fast as possible but
4418                  * pays a penalty for a copy operation.  Since the iocb is
4419                  * only 32 bytes, this penalty is considered small relative to
4420                  * the PCI reads for register values and a slim write.  When
4421                  * the ulpLe field is set, the entire Command has been
4422                  * received.
4423                  */
4424                 entry = lpfc_resp_iocb(phba, pring);
4425
4426                 phba->last_completion_time = jiffies;
4427                 rspiocbp = __lpfc_sli_get_iocbq(phba);
4428                 if (rspiocbp == NULL) {
4429                         printk(KERN_ERR "%s: out of buffers! Failing "
4430                                "completion.\n", __func__);
4431                         break;
4432                 }
4433
4434                 lpfc_sli_pcimem_bcopy(entry, &rspiocbp->iocb,
4435                                       phba->iocb_rsp_size);
4436                 irsp = &rspiocbp->iocb;
4437
4438                 if (++pring->sli.sli3.rspidx >= portRspMax)
4439                         pring->sli.sli3.rspidx = 0;
4440
4441                 if (pring->ringno == LPFC_ELS_RING) {
4442                         lpfc_debugfs_slow_ring_trc(phba,
4443                         "IOCB rsp ring:   wd4:x%08x wd6:x%08x wd7:x%08x",
4444                                 *(((uint32_t *) irsp) + 4),
4445                                 *(((uint32_t *) irsp) + 6),
4446                                 *(((uint32_t *) irsp) + 7));
4447                 }
4448
4449                 writel(pring->sli.sli3.rspidx,
4450                         &phba->host_gp[pring->ringno].rspGetInx);
4451
4452                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4453                 /* Handle the response IOCB */
4454                 rspiocbp = lpfc_sli_sp_handle_rspiocb(phba, pring, rspiocbp);
4455                 spin_lock_irqsave(&phba->hbalock, iflag);
4456
4457                 /*
4458                  * If the port response put pointer has not been updated, sync
4459                  * the pgp->rspPutInx in the MAILBOX_tand fetch the new port
4460                  * response put pointer.
4461                  */
4462                 if (pring->sli.sli3.rspidx == portRspPut) {
4463                         portRspPut = le32_to_cpu(pgp->rspPutInx);
4464                 }
4465         } /* while (pring->sli.sli3.rspidx != portRspPut) */
4466
4467         if ((rspiocbp != NULL) && (mask & HA_R0RE_REQ)) {
4468                 /* At least one response entry has been freed */
4469                 pring->stats.iocb_rsp_full++;
4470                 /* SET RxRE_RSP in Chip Att register */
4471                 status = ((CA_R0ATT | CA_R0RE_RSP) << (pring->ringno * 4));
4472                 writel(status, phba->CAregaddr);
4473                 readl(phba->CAregaddr); /* flush */
4474         }
4475         if ((mask & HA_R0CE_RSP) && (pring->flag & LPFC_CALL_RING_AVAILABLE)) {
4476                 pring->flag &= ~LPFC_CALL_RING_AVAILABLE;
4477                 pring->stats.iocb_cmd_empty++;
4478
4479                 /* Force update of the local copy of cmdGetInx */
4480                 pring->sli.sli3.local_getidx = le32_to_cpu(pgp->cmdGetInx);
4481                 lpfc_sli_resume_iocb(phba, pring);
4482
4483                 if ((pring->lpfc_sli_cmd_available))
4484                         (pring->lpfc_sli_cmd_available) (phba, pring);
4485
4486         }
4487
4488         spin_unlock_irqrestore(&phba->hbalock, iflag);
4489         return;
4490 }
4491
4492 /**
4493  * lpfc_sli_handle_slow_ring_event_s4 - Handle SLI4 slow-path els events
4494  * @phba: Pointer to HBA context object.
4495  * @pring: Pointer to driver SLI ring object.
4496  * @mask: Host attention register mask for this ring.
4497  *
4498  * This function is called from the worker thread when there is a pending
4499  * ELS response iocb on the driver internal slow-path response iocb worker
4500  * queue. The caller does not hold any lock. The function will remove each
4501  * response iocb from the response worker queue and calls the handle
4502  * response iocb routine (lpfc_sli_sp_handle_rspiocb) to process it.
4503  **/
4504 static void
4505 lpfc_sli_handle_slow_ring_event_s4(struct lpfc_hba *phba,
4506                                    struct lpfc_sli_ring *pring, uint32_t mask)
4507 {
4508         struct lpfc_iocbq *irspiocbq;
4509         struct hbq_dmabuf *dmabuf;
4510         struct lpfc_cq_event *cq_event;
4511         unsigned long iflag;
4512         int count = 0;
4513
4514         clear_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
4515         while (!list_empty(&phba->sli4_hba.sp_queue_event)) {
4516                 /* Get the response iocb from the head of work queue */
4517                 spin_lock_irqsave(&phba->hbalock, iflag);
4518                 list_remove_head(&phba->sli4_hba.sp_queue_event,
4519                                  cq_event, struct lpfc_cq_event, list);
4520                 spin_unlock_irqrestore(&phba->hbalock, iflag);
4521
4522                 switch (bf_get(lpfc_wcqe_c_code, &cq_event->cqe.wcqe_cmpl)) {
4523                 case CQE_CODE_COMPL_WQE:
4524                         irspiocbq = container_of(cq_event, struct lpfc_iocbq,
4525                                                  cq_event);
4526                         /* Translate ELS WCQE to response IOCBQ */
4527                         irspiocbq = lpfc_sli4_els_preprocess_rspiocbq(phba,
4528                                                                       irspiocbq);
4529                         if (irspiocbq)
4530                                 lpfc_sli_sp_handle_rspiocb(phba, pring,
4531                                                            irspiocbq);
4532                         count++;
4533                         break;
4534                 case CQE_CODE_RECEIVE:
4535                 case CQE_CODE_RECEIVE_V1:
4536                         dmabuf = container_of(cq_event, struct hbq_dmabuf,
4537                                               cq_event);
4538                         lpfc_sli4_handle_received_buffer(phba, dmabuf);
4539                         count++;
4540                         break;
4541                 default:
4542                         break;
4543                 }
4544
4545                 /* Limit the number of events to 64 to avoid soft lockups */
4546                 if (count == 64)
4547                         break;
4548         }
4549 }
4550
4551 /**
4552  * lpfc_sli_abort_iocb_ring - Abort all iocbs in the ring
4553  * @phba: Pointer to HBA context object.
4554  * @pring: Pointer to driver SLI ring object.
4555  *
4556  * This function aborts all iocbs in the given ring and frees all the iocb
4557  * objects in txq. This function issues an abort iocb for all the iocb commands
4558  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4559  * the return of this function. The caller is not required to hold any locks.
4560  **/
4561 void
4562 lpfc_sli_abort_iocb_ring(struct lpfc_hba *phba, struct lpfc_sli_ring *pring)
4563 {
4564         LIST_HEAD(tx_completions);
4565         LIST_HEAD(txcmplq_completions);
4566         struct lpfc_iocbq *iocb, *next_iocb;
4567         int offline;
4568
4569         if (pring->ringno == LPFC_ELS_RING) {
4570                 lpfc_fabric_abort_hba(phba);
4571         }
4572         offline = pci_channel_offline(phba->pcidev);
4573
4574         /* Error everything on txq and txcmplq
4575          * First do the txq.
4576          */
4577         if (phba->sli_rev >= LPFC_SLI_REV4) {
4578                 spin_lock_irq(&pring->ring_lock);
4579                 list_splice_init(&pring->txq, &tx_completions);
4580                 pring->txq_cnt = 0;
4581
4582                 if (offline) {
4583                         list_splice_init(&pring->txcmplq,
4584                                          &txcmplq_completions);
4585                 } else {
4586                         /* Next issue ABTS for everything on the txcmplq */
4587                         list_for_each_entry_safe(iocb, next_iocb,
4588                                                  &pring->txcmplq, list)
4589                                 lpfc_sli_issue_abort_iotag(phba, pring,
4590                                                            iocb, NULL);
4591                 }
4592                 spin_unlock_irq(&pring->ring_lock);
4593         } else {
4594                 spin_lock_irq(&phba->hbalock);
4595                 list_splice_init(&pring->txq, &tx_completions);
4596                 pring->txq_cnt = 0;
4597
4598                 if (offline) {
4599                         list_splice_init(&pring->txcmplq, &txcmplq_completions);
4600                 } else {
4601                         /* Next issue ABTS for everything on the txcmplq */
4602                         list_for_each_entry_safe(iocb, next_iocb,
4603                                                  &pring->txcmplq, list)
4604                                 lpfc_sli_issue_abort_iotag(phba, pring,
4605                                                            iocb, NULL);
4606                 }
4607                 spin_unlock_irq(&phba->hbalock);
4608         }
4609
4610         if (offline) {
4611                 /* Cancel all the IOCBs from the completions list */
4612                 lpfc_sli_cancel_iocbs(phba, &txcmplq_completions,
4613                                       IOSTAT_LOCAL_REJECT, IOERR_SLI_ABORTED);
4614         } else {
4615                 /* Make sure HBA is alive */
4616                 lpfc_issue_hb_tmo(phba);
4617         }
4618         /* Cancel all the IOCBs from the completions list */
4619         lpfc_sli_cancel_iocbs(phba, &tx_completions, IOSTAT_LOCAL_REJECT,
4620                               IOERR_SLI_ABORTED);
4621 }
4622
4623 /**
4624  * lpfc_sli_abort_fcp_rings - Abort all iocbs in all FCP rings
4625  * @phba: Pointer to HBA context object.
4626  *
4627  * This function aborts all iocbs in FCP rings and frees all the iocb
4628  * objects in txq. This function issues an abort iocb for all the iocb commands
4629  * in txcmplq. The iocbs in the txcmplq is not guaranteed to complete before
4630  * the return of this function. The caller is not required to hold any locks.
4631  **/
4632 void
4633 lpfc_sli_abort_fcp_rings(struct lpfc_hba *phba)
4634 {
4635         struct lpfc_sli *psli = &phba->sli;
4636         struct lpfc_sli_ring  *pring;
4637         uint32_t i;
4638
4639         /* Look on all the FCP Rings for the iotag */
4640         if (phba->sli_rev >= LPFC_SLI_REV4) {
4641                 for (i = 0; i < phba->cfg_hdw_queue; i++) {
4642                         pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4643                         lpfc_sli_abort_iocb_ring(phba, pring);
4644                 }
4645         } else {
4646                 pring = &psli->sli3_ring[LPFC_FCP_RING];
4647                 lpfc_sli_abort_iocb_ring(phba, pring);
4648         }
4649 }
4650
4651 /**
4652  * lpfc_sli_flush_io_rings - flush all iocbs in the IO ring
4653  * @phba: Pointer to HBA context object.
4654  *
4655  * This function flushes all iocbs in the IO ring and frees all the iocb
4656  * objects in txq and txcmplq. This function will not issue abort iocbs
4657  * for all the iocb commands in txcmplq, they will just be returned with
4658  * IOERR_SLI_DOWN. This function is invoked with EEH when device's PCI
4659  * slot has been permanently disabled.
4660  **/
4661 void
4662 lpfc_sli_flush_io_rings(struct lpfc_hba *phba)
4663 {
4664         LIST_HEAD(txq);
4665         LIST_HEAD(txcmplq);
4666         struct lpfc_sli *psli = &phba->sli;
4667         struct lpfc_sli_ring  *pring;
4668         uint32_t i;
4669         struct lpfc_iocbq *piocb, *next_iocb;
4670
4671         /* Indicate the I/O queues are flushed */
4672         set_bit(HBA_IOQ_FLUSH, &phba->hba_flag);
4673
4674         /* Look on all the FCP Rings for the iotag */
4675         if (phba->sli_rev >= LPFC_SLI_REV4) {
4676                 for (i = 0; i < phba->cfg_hdw_queue; i++) {
4677                         if (!phba->sli4_hba.hdwq ||
4678                             !phba->sli4_hba.hdwq[i].io_wq) {
4679                                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
4680                                                 "7777 hdwq's deleted %lx "
4681                                                 "%lx %x %x\n",
4682                                                 phba->pport->load_flag,
4683                                                 phba->hba_flag,
4684                                                 phba->link_state,
4685                                                 phba->sli.sli_flag);
4686                                 return;
4687                         }
4688                         pring = phba->sli4_hba.hdwq[i].io_wq->pring;
4689
4690                         spin_lock_irq(&pring->ring_lock);
4691                         /* Retrieve everything on txq */
4692                         list_splice_init(&pring->txq, &txq);
4693                         list_for_each_entry_safe(piocb, next_iocb,
4694                                                  &pring->txcmplq, list)
4695                                 piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4696                         /* Retrieve everything on the txcmplq */
4697                         list_splice_init(&pring->txcmplq, &txcmplq);
4698                         pring->txq_cnt = 0;
4699                         pring->txcmplq_cnt = 0;
4700                         spin_unlock_irq(&pring->ring_lock);
4701
4702                         /* Flush the txq */
4703                         lpfc_sli_cancel_iocbs(phba, &txq,
4704                                               IOSTAT_LOCAL_REJECT,
4705                                               IOERR_SLI_DOWN);
4706                         /* Flush the txcmplq */
4707                         lpfc_sli_cancel_iocbs(phba, &txcmplq,
4708                                               IOSTAT_LOCAL_REJECT,
4709                                               IOERR_SLI_DOWN);
4710                         if (unlikely(pci_channel_offline(phba->pcidev)))
4711                                 lpfc_sli4_io_xri_aborted(phba, NULL, 0);
4712                 }
4713         } else {
4714                 pring = &psli->sli3_ring[LPFC_FCP_RING];
4715
4716                 spin_lock_irq(&phba->hbalock);
4717                 /* Retrieve everything on txq */
4718                 list_splice_init(&pring->txq, &txq);
4719                 list_for_each_entry_safe(piocb, next_iocb,
4720                                          &pring->txcmplq, list)
4721                         piocb->cmd_flag &= ~LPFC_IO_ON_TXCMPLQ;
4722                 /* Retrieve everything on the txcmplq */
4723                 list_splice_init(&pring->txcmplq, &txcmplq);
4724                 pring->txq_cnt = 0;
4725                 pring->txcmplq_cnt = 0;
4726                 spin_unlock_irq(&phba->hbalock);
4727
4728                 /* Flush the txq */
4729                 lpfc_sli_cancel_iocbs(phba, &txq, IOSTAT_LOCAL_REJECT,
4730                                       IOERR_SLI_DOWN);
4731                 /* Flush the txcmpq */
4732                 lpfc_sli_cancel_iocbs(phba, &txcmplq, IOSTAT_LOCAL_REJECT,
4733                                       IOERR_SLI_DOWN);
4734         }
4735 }
4736
4737 /**
4738  * lpfc_sli_brdready_s3 - Check for sli3 host ready status
4739  * @phba: Pointer to HBA context object.
4740  * @mask: Bit mask to be checked.
4741  *
4742  * This function reads the host status register and compares
4743  * with the provided bit mask to check if HBA completed
4744  * the restart. This function will wait in a loop for the
4745  * HBA to complete restart. If the HBA does not restart within
4746  * 15 iterations, the function will reset the HBA again. The
4747  * function returns 1 when HBA fail to restart otherwise returns
4748  * zero.
4749  **/
4750 static int
4751 lpfc_sli_brdready_s3(struct lpfc_hba *phba, uint32_t mask)
4752 {
4753         uint32_t status;
4754         int i = 0;
4755         int retval = 0;
4756
4757         /* Read the HBA Host Status Register */
4758         if (lpfc_readl(phba->HSregaddr, &status))
4759                 return 1;
4760
4761         set_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
4762
4763         /*
4764          * Check status register every 100ms for 5 retries, then every
4765          * 500ms for 5, then every 2.5 sec for 5, then reset board and
4766          * every 2.5 sec for 4.
4767          * Break our of the loop if errors occurred during init.
4768          */
4769         while (((status & mask) != mask) &&
4770                !(status & HS_FFERM) &&
4771                i++ < 20) {
4772
4773                 if (i <= 5)
4774                         msleep(10);
4775                 else if (i <= 10)
4776                         msleep(500);
4777                 else
4778                         msleep(2500);
4779
4780                 if (i == 15) {
4781                                 /* Do post */
4782                         phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4783                         lpfc_sli_brdrestart(phba);
4784                 }
4785                 /* Read the HBA Host Status Register */
4786                 if (lpfc_readl(phba->HSregaddr, &status)) {
4787                         retval = 1;
4788                         break;
4789                 }
4790         }
4791
4792         /* Check to see if any errors occurred during init */
4793         if ((status & HS_FFERM) || (i >= 20)) {
4794                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
4795                                 "2751 Adapter failed to restart, "
4796                                 "status reg x%x, FW Data: A8 x%x AC x%x\n",
4797                                 status,
4798                                 readl(phba->MBslimaddr + 0xa8),
4799                                 readl(phba->MBslimaddr + 0xac));
4800                 phba->link_state = LPFC_HBA_ERROR;
4801                 retval = 1;
4802         }
4803
4804         return retval;
4805 }
4806
4807 /**
4808  * lpfc_sli_brdready_s4 - Check for sli4 host ready status
4809  * @phba: Pointer to HBA context object.
4810  * @mask: Bit mask to be checked.
4811  *
4812  * This function checks the host status register to check if HBA is
4813  * ready. This function will wait in a loop for the HBA to be ready
4814  * If the HBA is not ready , the function will will reset the HBA PCI
4815  * function again. The function returns 1 when HBA fail to be ready
4816  * otherwise returns zero.
4817  **/
4818 static int
4819 lpfc_sli_brdready_s4(struct lpfc_hba *phba, uint32_t mask)
4820 {
4821         uint32_t status;
4822         int retval = 0;
4823
4824         /* Read the HBA Host Status Register */
4825         status = lpfc_sli4_post_status_check(phba);
4826
4827         if (status) {
4828                 phba->pport->port_state = LPFC_VPORT_UNKNOWN;
4829                 lpfc_sli_brdrestart(phba);
4830                 status = lpfc_sli4_post_status_check(phba);
4831         }
4832
4833         /* Check to see if any errors occurred during init */
4834         if (status) {
4835                 phba->link_state = LPFC_HBA_ERROR;
4836                 retval = 1;
4837         } else
4838                 phba->sli4_hba.intr_enable = 0;
4839
4840         clear_bit(HBA_SETUP, &phba->hba_flag);
4841         return retval;
4842 }
4843
4844 /**
4845  * lpfc_sli_brdready - Wrapper func for checking the hba readyness
4846  * @phba: Pointer to HBA context object.
4847  * @mask: Bit mask to be checked.
4848  *
4849  * This routine wraps the actual SLI3 or SLI4 hba readyness check routine
4850  * from the API jump table function pointer from the lpfc_hba struct.
4851  **/
4852 int
4853 lpfc_sli_brdready(struct lpfc_hba *phba, uint32_t mask)
4854 {
4855         return phba->lpfc_sli_brdready(phba, mask);
4856 }
4857
4858 #define BARRIER_TEST_PATTERN (0xdeadbeef)
4859
4860 /**
4861  * lpfc_reset_barrier - Make HBA ready for HBA reset
4862  * @phba: Pointer to HBA context object.
4863  *
4864  * This function is called before resetting an HBA. This function is called
4865  * with hbalock held and requests HBA to quiesce DMAs before a reset.
4866  **/
4867 void lpfc_reset_barrier(struct lpfc_hba *phba)
4868 {
4869         uint32_t __iomem *resp_buf;
4870         uint32_t __iomem *mbox_buf;
4871         volatile struct MAILBOX_word0 mbox;
4872         uint32_t hc_copy, ha_copy, resp_data;
4873         int  i;
4874         uint8_t hdrtype;
4875
4876         lockdep_assert_held(&phba->hbalock);
4877
4878         pci_read_config_byte(phba->pcidev, PCI_HEADER_TYPE, &hdrtype);
4879         if (hdrtype != PCI_HEADER_TYPE_MFD ||
4880             (FC_JEDEC_ID(phba->vpd.rev.biuRev) != HELIOS_JEDEC_ID &&
4881              FC_JEDEC_ID(phba->vpd.rev.biuRev) != THOR_JEDEC_ID))
4882                 return;
4883
4884         /*
4885          * Tell the other part of the chip to suspend temporarily all
4886          * its DMA activity.
4887          */
4888         resp_buf = phba->MBslimaddr;
4889
4890         /* Disable the error attention */
4891         if (lpfc_readl(phba->HCregaddr, &hc_copy))
4892                 return;
4893         writel((hc_copy & ~HC_ERINT_ENA), phba->HCregaddr);
4894         readl(phba->HCregaddr); /* flush */
4895         phba->link_flag |= LS_IGNORE_ERATT;
4896
4897         if (lpfc_readl(phba->HAregaddr, &ha_copy))
4898                 return;
4899         if (ha_copy & HA_ERATT) {
4900                 /* Clear Chip error bit */
4901                 writel(HA_ERATT, phba->HAregaddr);
4902                 phba->pport->stopped = 1;
4903         }
4904
4905         mbox.word0 = 0;
4906         mbox.mbxCommand = MBX_KILL_BOARD;
4907         mbox.mbxOwner = OWN_CHIP;
4908
4909         writel(BARRIER_TEST_PATTERN, (resp_buf + 1));
4910         mbox_buf = phba->MBslimaddr;
4911         writel(mbox.word0, mbox_buf);
4912
4913         for (i = 0; i < 50; i++) {
4914                 if (lpfc_readl((resp_buf + 1), &resp_data))
4915                         return;
4916                 if (resp_data != ~(BARRIER_TEST_PATTERN))
4917                         mdelay(1);
4918                 else
4919                         break;
4920         }
4921         resp_data = 0;
4922         if (lpfc_readl((resp_buf + 1), &resp_data))
4923                 return;
4924         if (resp_data  != ~(BARRIER_TEST_PATTERN)) {
4925                 if (phba->sli.sli_flag & LPFC_SLI_ACTIVE ||
4926                     phba->pport->stopped)
4927                         goto restore_hc;
4928                 else
4929                         goto clear_errat;
4930         }
4931
4932         mbox.mbxOwner = OWN_HOST;
4933         resp_data = 0;
4934         for (i = 0; i < 500; i++) {
4935                 if (lpfc_readl(resp_buf, &resp_data))
4936                         return;
4937                 if (resp_data != mbox.word0)
4938                         mdelay(1);
4939                 else
4940                         break;
4941         }
4942
4943 clear_errat:
4944
4945         while (++i < 500) {
4946                 if (lpfc_readl(phba->HAregaddr, &ha_copy))
4947                         return;
4948                 if (!(ha_copy & HA_ERATT))
4949                         mdelay(1);
4950                 else
4951                         break;
4952         }
4953
4954         if (readl(phba->HAregaddr) & HA_ERATT) {
4955                 writel(HA_ERATT, phba->HAregaddr);
4956                 phba->pport->stopped = 1;
4957         }
4958
4959 restore_hc:
4960         phba->link_flag &= ~LS_IGNORE_ERATT;
4961         writel(hc_copy, phba->HCregaddr);
4962         readl(phba->HCregaddr); /* flush */
4963 }
4964
4965 /**
4966  * lpfc_sli_brdkill - Issue a kill_board mailbox command
4967  * @phba: Pointer to HBA context object.
4968  *
4969  * This function issues a kill_board mailbox command and waits for
4970  * the error attention interrupt. This function is called for stopping
4971  * the firmware processing. The caller is not required to hold any
4972  * locks. This function calls lpfc_hba_down_post function to free
4973  * any pending commands after the kill. The function will return 1 when it
4974  * fails to kill the board else will return 0.
4975  **/
4976 int
4977 lpfc_sli_brdkill(struct lpfc_hba *phba)
4978 {
4979         struct lpfc_sli *psli;
4980         LPFC_MBOXQ_t *pmb;
4981         uint32_t status;
4982         uint32_t ha_copy;
4983         int retval;
4984         int i = 0;
4985
4986         psli = &phba->sli;
4987
4988         /* Kill HBA */
4989         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
4990                         "0329 Kill HBA Data: x%x x%x\n",
4991                         phba->pport->port_state, psli->sli_flag);
4992
4993         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
4994         if (!pmb)
4995                 return 1;
4996
4997         /* Disable the error attention */
4998         spin_lock_irq(&phba->hbalock);
4999         if (lpfc_readl(phba->HCregaddr, &status)) {
5000                 spin_unlock_irq(&phba->hbalock);
5001                 mempool_free(pmb, phba->mbox_mem_pool);
5002                 return 1;
5003         }
5004         status &= ~HC_ERINT_ENA;
5005         writel(status, phba->HCregaddr);
5006         readl(phba->HCregaddr); /* flush */
5007         phba->link_flag |= LS_IGNORE_ERATT;
5008         spin_unlock_irq(&phba->hbalock);
5009
5010         lpfc_kill_board(phba, pmb);
5011         pmb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
5012         retval = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
5013
5014         if (retval != MBX_SUCCESS) {
5015                 if (retval != MBX_BUSY)
5016                         mempool_free(pmb, phba->mbox_mem_pool);
5017                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5018                                 "2752 KILL_BOARD command failed retval %d\n",
5019                                 retval);
5020                 spin_lock_irq(&phba->hbalock);
5021                 phba->link_flag &= ~LS_IGNORE_ERATT;
5022                 spin_unlock_irq(&phba->hbalock);
5023                 return 1;
5024         }
5025
5026         spin_lock_irq(&phba->hbalock);
5027         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
5028         spin_unlock_irq(&phba->hbalock);
5029
5030         mempool_free(pmb, phba->mbox_mem_pool);
5031
5032         /* There is no completion for a KILL_BOARD mbox cmd. Check for an error
5033          * attention every 100ms for 3 seconds. If we don't get ERATT after
5034          * 3 seconds we still set HBA_ERROR state because the status of the
5035          * board is now undefined.
5036          */
5037         if (lpfc_readl(phba->HAregaddr, &ha_copy))
5038                 return 1;
5039         while ((i++ < 30) && !(ha_copy & HA_ERATT)) {
5040                 mdelay(100);
5041                 if (lpfc_readl(phba->HAregaddr, &ha_copy))
5042                         return 1;
5043         }
5044
5045         del_timer_sync(&psli->mbox_tmo);
5046         if (ha_copy & HA_ERATT) {
5047                 writel(HA_ERATT, phba->HAregaddr);
5048                 phba->pport->stopped = 1;
5049         }
5050         spin_lock_irq(&phba->hbalock);
5051         psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5052         psli->mbox_active = NULL;
5053         phba->link_flag &= ~LS_IGNORE_ERATT;
5054         spin_unlock_irq(&phba->hbalock);
5055
5056         lpfc_hba_down_post(phba);
5057         phba->link_state = LPFC_HBA_ERROR;
5058
5059         return ha_copy & HA_ERATT ? 0 : 1;
5060 }
5061
5062 /**
5063  * lpfc_sli_brdreset - Reset a sli-2 or sli-3 HBA
5064  * @phba: Pointer to HBA context object.
5065  *
5066  * This function resets the HBA by writing HC_INITFF to the control
5067  * register. After the HBA resets, this function resets all the iocb ring
5068  * indices. This function disables PCI layer parity checking during
5069  * the reset.
5070  * This function returns 0 always.
5071  * The caller is not required to hold any locks.
5072  **/
5073 int
5074 lpfc_sli_brdreset(struct lpfc_hba *phba)
5075 {
5076         struct lpfc_sli *psli;
5077         struct lpfc_sli_ring *pring;
5078         uint16_t cfg_value;
5079         int i;
5080
5081         psli = &phba->sli;
5082
5083         /* Reset HBA */
5084         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5085                         "0325 Reset HBA Data: x%x x%x\n",
5086                         (phba->pport) ? phba->pport->port_state : 0,
5087                         psli->sli_flag);
5088
5089         /* perform board reset */
5090         phba->fc_eventTag = 0;
5091         phba->link_events = 0;
5092         set_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
5093         if (phba->pport) {
5094                 phba->pport->fc_myDID = 0;
5095                 phba->pport->fc_prevDID = 0;
5096         }
5097
5098         /* Turn off parity checking and serr during the physical reset */
5099         if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value))
5100                 return -EIO;
5101
5102         pci_write_config_word(phba->pcidev, PCI_COMMAND,
5103                               (cfg_value &
5104                                ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5105
5106         psli->sli_flag &= ~(LPFC_SLI_ACTIVE | LPFC_PROCESS_LA);
5107
5108         /* Now toggle INITFF bit in the Host Control Register */
5109         writel(HC_INITFF, phba->HCregaddr);
5110         mdelay(1);
5111         readl(phba->HCregaddr); /* flush */
5112         writel(0, phba->HCregaddr);
5113         readl(phba->HCregaddr); /* flush */
5114
5115         /* Restore PCI cmd register */
5116         pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5117
5118         /* Initialize relevant SLI info */
5119         for (i = 0; i < psli->num_rings; i++) {
5120                 pring = &psli->sli3_ring[i];
5121                 pring->flag = 0;
5122                 pring->sli.sli3.rspidx = 0;
5123                 pring->sli.sli3.next_cmdidx  = 0;
5124                 pring->sli.sli3.local_getidx = 0;
5125                 pring->sli.sli3.cmdidx = 0;
5126                 pring->missbufcnt = 0;
5127         }
5128
5129         phba->link_state = LPFC_WARM_START;
5130         return 0;
5131 }
5132
5133 /**
5134  * lpfc_sli4_brdreset - Reset a sli-4 HBA
5135  * @phba: Pointer to HBA context object.
5136  *
5137  * This function resets a SLI4 HBA. This function disables PCI layer parity
5138  * checking during resets the device. The caller is not required to hold
5139  * any locks.
5140  *
5141  * This function returns 0 on success else returns negative error code.
5142  **/
5143 int
5144 lpfc_sli4_brdreset(struct lpfc_hba *phba)
5145 {
5146         struct lpfc_sli *psli = &phba->sli;
5147         uint16_t cfg_value;
5148         int rc = 0;
5149
5150         /* Reset HBA */
5151         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5152                         "0295 Reset HBA Data: x%x x%x x%lx\n",
5153                         phba->pport->port_state, psli->sli_flag,
5154                         phba->hba_flag);
5155
5156         /* perform board reset */
5157         phba->fc_eventTag = 0;
5158         phba->link_events = 0;
5159         phba->pport->fc_myDID = 0;
5160         phba->pport->fc_prevDID = 0;
5161         clear_bit(HBA_SETUP, &phba->hba_flag);
5162
5163         spin_lock_irq(&phba->hbalock);
5164         psli->sli_flag &= ~(LPFC_PROCESS_LA);
5165         phba->fcf.fcf_flag = 0;
5166         spin_unlock_irq(&phba->hbalock);
5167
5168         /* Now physically reset the device */
5169         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5170                         "0389 Performing PCI function reset!\n");
5171
5172         /* Turn off parity checking and serr during the physical reset */
5173         if (pci_read_config_word(phba->pcidev, PCI_COMMAND, &cfg_value)) {
5174                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5175                                 "3205 PCI read Config failed\n");
5176                 return -EIO;
5177         }
5178
5179         pci_write_config_word(phba->pcidev, PCI_COMMAND, (cfg_value &
5180                               ~(PCI_COMMAND_PARITY | PCI_COMMAND_SERR)));
5181
5182         /* Perform FCoE PCI function reset before freeing queue memory */
5183         rc = lpfc_pci_function_reset(phba);
5184
5185         /* Restore PCI cmd register */
5186         pci_write_config_word(phba->pcidev, PCI_COMMAND, cfg_value);
5187
5188         return rc;
5189 }
5190
5191 /**
5192  * lpfc_sli_brdrestart_s3 - Restart a sli-3 hba
5193  * @phba: Pointer to HBA context object.
5194  *
5195  * This function is called in the SLI initialization code path to
5196  * restart the HBA. The caller is not required to hold any lock.
5197  * This function writes MBX_RESTART mailbox command to the SLIM and
5198  * resets the HBA. At the end of the function, it calls lpfc_hba_down_post
5199  * function to free any pending commands. The function enables
5200  * POST only during the first initialization. The function returns zero.
5201  * The function does not guarantee completion of MBX_RESTART mailbox
5202  * command before the return of this function.
5203  **/
5204 static int
5205 lpfc_sli_brdrestart_s3(struct lpfc_hba *phba)
5206 {
5207         volatile struct MAILBOX_word0 mb;
5208         struct lpfc_sli *psli;
5209         void __iomem *to_slim;
5210
5211         spin_lock_irq(&phba->hbalock);
5212
5213         psli = &phba->sli;
5214
5215         /* Restart HBA */
5216         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5217                         "0337 Restart HBA Data: x%x x%x\n",
5218                         (phba->pport) ? phba->pport->port_state : 0,
5219                         psli->sli_flag);
5220
5221         mb.word0 = 0;
5222         mb.mbxCommand = MBX_RESTART;
5223         mb.mbxHc = 1;
5224
5225         lpfc_reset_barrier(phba);
5226
5227         to_slim = phba->MBslimaddr;
5228         writel(mb.word0, to_slim);
5229         readl(to_slim); /* flush */
5230
5231         /* Only skip post after fc_ffinit is completed */
5232         if (phba->pport && phba->pport->port_state)
5233                 mb.word0 = 1;   /* This is really setting up word1 */
5234         else
5235                 mb.word0 = 0;   /* This is really setting up word1 */
5236         to_slim = phba->MBslimaddr + sizeof (uint32_t);
5237         writel(mb.word0, to_slim);
5238         readl(to_slim); /* flush */
5239
5240         lpfc_sli_brdreset(phba);
5241         if (phba->pport)
5242                 phba->pport->stopped = 0;
5243         phba->link_state = LPFC_INIT_START;
5244         phba->hba_flag = 0;
5245         spin_unlock_irq(&phba->hbalock);
5246
5247         memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5248         psli->stats_start = ktime_get_seconds();
5249
5250         /* Give the INITFF and Post time to settle. */
5251         mdelay(100);
5252
5253         lpfc_hba_down_post(phba);
5254
5255         return 0;
5256 }
5257
5258 /**
5259  * lpfc_sli_brdrestart_s4 - Restart the sli-4 hba
5260  * @phba: Pointer to HBA context object.
5261  *
5262  * This function is called in the SLI initialization code path to restart
5263  * a SLI4 HBA. The caller is not required to hold any lock.
5264  * At the end of the function, it calls lpfc_hba_down_post function to
5265  * free any pending commands.
5266  **/
5267 static int
5268 lpfc_sli_brdrestart_s4(struct lpfc_hba *phba)
5269 {
5270         struct lpfc_sli *psli = &phba->sli;
5271         int rc;
5272
5273         /* Restart HBA */
5274         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
5275                         "0296 Restart HBA Data: x%x x%x\n",
5276                         phba->pport->port_state, psli->sli_flag);
5277
5278         lpfc_sli4_queue_unset(phba);
5279
5280         rc = lpfc_sli4_brdreset(phba);
5281         if (rc) {
5282                 phba->link_state = LPFC_HBA_ERROR;
5283                 goto hba_down_queue;
5284         }
5285
5286         spin_lock_irq(&phba->hbalock);
5287         phba->pport->stopped = 0;
5288         phba->link_state = LPFC_INIT_START;
5289         phba->hba_flag = 0;
5290         /* Preserve FA-PWWN expectation */
5291         phba->sli4_hba.fawwpn_flag &= LPFC_FAWWPN_FABRIC;
5292         spin_unlock_irq(&phba->hbalock);
5293
5294         memset(&psli->lnk_stat_offsets, 0, sizeof(psli->lnk_stat_offsets));
5295         psli->stats_start = ktime_get_seconds();
5296
5297 hba_down_queue:
5298         lpfc_hba_down_post(phba);
5299         lpfc_sli4_queue_destroy(phba);
5300
5301         return rc;
5302 }
5303
5304 /**
5305  * lpfc_sli_brdrestart - Wrapper func for restarting hba
5306  * @phba: Pointer to HBA context object.
5307  *
5308  * This routine wraps the actual SLI3 or SLI4 hba restart routine from the
5309  * API jump table function pointer from the lpfc_hba struct.
5310 **/
5311 int
5312 lpfc_sli_brdrestart(struct lpfc_hba *phba)
5313 {
5314         return phba->lpfc_sli_brdrestart(phba);
5315 }
5316
5317 /**
5318  * lpfc_sli_chipset_init - Wait for the restart of the HBA after a restart
5319  * @phba: Pointer to HBA context object.
5320  *
5321  * This function is called after a HBA restart to wait for successful
5322  * restart of the HBA. Successful restart of the HBA is indicated by
5323  * HS_FFRDY and HS_MBRDY bits. If the HBA fails to restart even after 15
5324  * iteration, the function will restart the HBA again. The function returns
5325  * zero if HBA successfully restarted else returns negative error code.
5326  **/
5327 int
5328 lpfc_sli_chipset_init(struct lpfc_hba *phba)
5329 {
5330         uint32_t status, i = 0;
5331
5332         /* Read the HBA Host Status Register */
5333         if (lpfc_readl(phba->HSregaddr, &status))
5334                 return -EIO;
5335
5336         /* Check status register to see what current state is */
5337         i = 0;
5338         while ((status & (HS_FFRDY | HS_MBRDY)) != (HS_FFRDY | HS_MBRDY)) {
5339
5340                 /* Check every 10ms for 10 retries, then every 100ms for 90
5341                  * retries, then every 1 sec for 50 retires for a total of
5342                  * ~60 seconds before reset the board again and check every
5343                  * 1 sec for 50 retries. The up to 60 seconds before the
5344                  * board ready is required by the Falcon FIPS zeroization
5345                  * complete, and any reset the board in between shall cause
5346                  * restart of zeroization, further delay the board ready.
5347                  */
5348                 if (i++ >= 200) {
5349                         /* Adapter failed to init, timeout, status reg
5350                            <status> */
5351                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5352                                         "0436 Adapter failed to init, "
5353                                         "timeout, status reg x%x, "
5354                                         "FW Data: A8 x%x AC x%x\n", status,
5355                                         readl(phba->MBslimaddr + 0xa8),
5356                                         readl(phba->MBslimaddr + 0xac));
5357                         phba->link_state = LPFC_HBA_ERROR;
5358                         return -ETIMEDOUT;
5359                 }
5360
5361                 /* Check to see if any errors occurred during init */
5362                 if (status & HS_FFERM) {
5363                         /* ERROR: During chipset initialization */
5364                         /* Adapter failed to init, chipset, status reg
5365                            <status> */
5366                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5367                                         "0437 Adapter failed to init, "
5368                                         "chipset, status reg x%x, "
5369                                         "FW Data: A8 x%x AC x%x\n", status,
5370                                         readl(phba->MBslimaddr + 0xa8),
5371                                         readl(phba->MBslimaddr + 0xac));
5372                         phba->link_state = LPFC_HBA_ERROR;
5373                         return -EIO;
5374                 }
5375
5376                 if (i <= 10)
5377                         msleep(10);
5378                 else if (i <= 100)
5379                         msleep(100);
5380                 else
5381                         msleep(1000);
5382
5383                 if (i == 150) {
5384                         /* Do post */
5385                         phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5386                         lpfc_sli_brdrestart(phba);
5387                 }
5388                 /* Read the HBA Host Status Register */
5389                 if (lpfc_readl(phba->HSregaddr, &status))
5390                         return -EIO;
5391         }
5392
5393         /* Check to see if any errors occurred during init */
5394         if (status & HS_FFERM) {
5395                 /* ERROR: During chipset initialization */
5396                 /* Adapter failed to init, chipset, status reg <status> */
5397                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5398                                 "0438 Adapter failed to init, chipset, "
5399                                 "status reg x%x, "
5400                                 "FW Data: A8 x%x AC x%x\n", status,
5401                                 readl(phba->MBslimaddr + 0xa8),
5402                                 readl(phba->MBslimaddr + 0xac));
5403                 phba->link_state = LPFC_HBA_ERROR;
5404                 return -EIO;
5405         }
5406
5407         set_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
5408
5409         /* Clear all interrupt enable conditions */
5410         writel(0, phba->HCregaddr);
5411         readl(phba->HCregaddr); /* flush */
5412
5413         /* setup host attn register */
5414         writel(0xffffffff, phba->HAregaddr);
5415         readl(phba->HAregaddr); /* flush */
5416         return 0;
5417 }
5418
5419 /**
5420  * lpfc_sli_hbq_count - Get the number of HBQs to be configured
5421  *
5422  * This function calculates and returns the number of HBQs required to be
5423  * configured.
5424  **/
5425 int
5426 lpfc_sli_hbq_count(void)
5427 {
5428         return ARRAY_SIZE(lpfc_hbq_defs);
5429 }
5430
5431 /**
5432  * lpfc_sli_hbq_entry_count - Calculate total number of hbq entries
5433  *
5434  * This function adds the number of hbq entries in every HBQ to get
5435  * the total number of hbq entries required for the HBA and returns
5436  * the total count.
5437  **/
5438 static int
5439 lpfc_sli_hbq_entry_count(void)
5440 {
5441         int  hbq_count = lpfc_sli_hbq_count();
5442         int  count = 0;
5443         int  i;
5444
5445         for (i = 0; i < hbq_count; ++i)
5446                 count += lpfc_hbq_defs[i]->entry_count;
5447         return count;
5448 }
5449
5450 /**
5451  * lpfc_sli_hbq_size - Calculate memory required for all hbq entries
5452  *
5453  * This function calculates amount of memory required for all hbq entries
5454  * to be configured and returns the total memory required.
5455  **/
5456 int
5457 lpfc_sli_hbq_size(void)
5458 {
5459         return lpfc_sli_hbq_entry_count() * sizeof(struct lpfc_hbq_entry);
5460 }
5461
5462 /**
5463  * lpfc_sli_hbq_setup - configure and initialize HBQs
5464  * @phba: Pointer to HBA context object.
5465  *
5466  * This function is called during the SLI initialization to configure
5467  * all the HBQs and post buffers to the HBQ. The caller is not
5468  * required to hold any locks. This function will return zero if successful
5469  * else it will return negative error code.
5470  **/
5471 static int
5472 lpfc_sli_hbq_setup(struct lpfc_hba *phba)
5473 {
5474         int  hbq_count = lpfc_sli_hbq_count();
5475         LPFC_MBOXQ_t *pmb;
5476         MAILBOX_t *pmbox;
5477         uint32_t hbqno;
5478         uint32_t hbq_entry_index;
5479
5480                                 /* Get a Mailbox buffer to setup mailbox
5481                                  * commands for HBA initialization
5482                                  */
5483         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5484
5485         if (!pmb)
5486                 return -ENOMEM;
5487
5488         pmbox = &pmb->u.mb;
5489
5490         /* Initialize the struct lpfc_sli_hbq structure for each hbq */
5491         phba->link_state = LPFC_INIT_MBX_CMDS;
5492         phba->hbq_in_use = 1;
5493
5494         hbq_entry_index = 0;
5495         for (hbqno = 0; hbqno < hbq_count; ++hbqno) {
5496                 phba->hbqs[hbqno].next_hbqPutIdx = 0;
5497                 phba->hbqs[hbqno].hbqPutIdx      = 0;
5498                 phba->hbqs[hbqno].local_hbqGetIdx   = 0;
5499                 phba->hbqs[hbqno].entry_count =
5500                         lpfc_hbq_defs[hbqno]->entry_count;
5501                 lpfc_config_hbq(phba, hbqno, lpfc_hbq_defs[hbqno],
5502                         hbq_entry_index, pmb);
5503                 hbq_entry_index += phba->hbqs[hbqno].entry_count;
5504
5505                 if (lpfc_sli_issue_mbox(phba, pmb, MBX_POLL) != MBX_SUCCESS) {
5506                         /* Adapter failed to init, mbxCmd <cmd> CFG_RING,
5507                            mbxStatus <status>, ring <num> */
5508
5509                         lpfc_printf_log(phba, KERN_ERR,
5510                                         LOG_SLI | LOG_VPORT,
5511                                         "1805 Adapter failed to init. "
5512                                         "Data: x%x x%x x%x\n",
5513                                         pmbox->mbxCommand,
5514                                         pmbox->mbxStatus, hbqno);
5515
5516                         phba->link_state = LPFC_HBA_ERROR;
5517                         mempool_free(pmb, phba->mbox_mem_pool);
5518                         return -ENXIO;
5519                 }
5520         }
5521         phba->hbq_count = hbq_count;
5522
5523         mempool_free(pmb, phba->mbox_mem_pool);
5524
5525         /* Initially populate or replenish the HBQs */
5526         for (hbqno = 0; hbqno < hbq_count; ++hbqno)
5527                 lpfc_sli_hbqbuf_init_hbqs(phba, hbqno);
5528         return 0;
5529 }
5530
5531 /**
5532  * lpfc_sli4_rb_setup - Initialize and post RBs to HBA
5533  * @phba: Pointer to HBA context object.
5534  *
5535  * This function is called during the SLI initialization to configure
5536  * all the HBQs and post buffers to the HBQ. The caller is not
5537  * required to hold any locks. This function will return zero if successful
5538  * else it will return negative error code.
5539  **/
5540 static int
5541 lpfc_sli4_rb_setup(struct lpfc_hba *phba)
5542 {
5543         phba->hbq_in_use = 1;
5544         /**
5545          * Specific case when the MDS diagnostics is enabled and supported.
5546          * The receive buffer count is truncated to manage the incoming
5547          * traffic.
5548          **/
5549         if (phba->cfg_enable_mds_diags && phba->mds_diags_support)
5550                 phba->hbqs[LPFC_ELS_HBQ].entry_count =
5551                         lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count >> 1;
5552         else
5553                 phba->hbqs[LPFC_ELS_HBQ].entry_count =
5554                         lpfc_hbq_defs[LPFC_ELS_HBQ]->entry_count;
5555         phba->hbq_count = 1;
5556         lpfc_sli_hbqbuf_init_hbqs(phba, LPFC_ELS_HBQ);
5557         /* Initially populate or replenish the HBQs */
5558         return 0;
5559 }
5560
5561 /**
5562  * lpfc_sli_config_port - Issue config port mailbox command
5563  * @phba: Pointer to HBA context object.
5564  * @sli_mode: sli mode - 2/3
5565  *
5566  * This function is called by the sli initialization code path
5567  * to issue config_port mailbox command. This function restarts the
5568  * HBA firmware and issues a config_port mailbox command to configure
5569  * the SLI interface in the sli mode specified by sli_mode
5570  * variable. The caller is not required to hold any locks.
5571  * The function returns 0 if successful, else returns negative error
5572  * code.
5573  **/
5574 int
5575 lpfc_sli_config_port(struct lpfc_hba *phba, int sli_mode)
5576 {
5577         LPFC_MBOXQ_t *pmb;
5578         uint32_t resetcount = 0, rc = 0, done = 0;
5579
5580         pmb = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5581         if (!pmb) {
5582                 phba->link_state = LPFC_HBA_ERROR;
5583                 return -ENOMEM;
5584         }
5585
5586         phba->sli_rev = sli_mode;
5587         while (resetcount < 2 && !done) {
5588                 spin_lock_irq(&phba->hbalock);
5589                 phba->sli.sli_flag |= LPFC_SLI_MBOX_ACTIVE;
5590                 spin_unlock_irq(&phba->hbalock);
5591                 phba->pport->port_state = LPFC_VPORT_UNKNOWN;
5592                 lpfc_sli_brdrestart(phba);
5593                 rc = lpfc_sli_chipset_init(phba);
5594                 if (rc)
5595                         break;
5596
5597                 spin_lock_irq(&phba->hbalock);
5598                 phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
5599                 spin_unlock_irq(&phba->hbalock);
5600                 resetcount++;
5601
5602                 /* Call pre CONFIG_PORT mailbox command initialization.  A
5603                  * value of 0 means the call was successful.  Any other
5604                  * nonzero value is a failure, but if ERESTART is returned,
5605                  * the driver may reset the HBA and try again.
5606                  */
5607                 rc = lpfc_config_port_prep(phba);
5608                 if (rc == -ERESTART) {
5609                         phba->link_state = LPFC_LINK_UNKNOWN;
5610                         continue;
5611                 } else if (rc)
5612                         break;
5613
5614                 phba->link_state = LPFC_INIT_MBX_CMDS;
5615                 lpfc_config_port(phba, pmb);
5616                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
5617                 phba->sli3_options &= ~(LPFC_SLI3_NPIV_ENABLED |
5618                                         LPFC_SLI3_HBQ_ENABLED |
5619                                         LPFC_SLI3_CRP_ENABLED |
5620                                         LPFC_SLI3_DSS_ENABLED);
5621                 if (rc != MBX_SUCCESS) {
5622                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5623                                 "0442 Adapter failed to init, mbxCmd x%x "
5624                                 "CONFIG_PORT, mbxStatus x%x Data: x%x\n",
5625                                 pmb->u.mb.mbxCommand, pmb->u.mb.mbxStatus, 0);
5626                         spin_lock_irq(&phba->hbalock);
5627                         phba->sli.sli_flag &= ~LPFC_SLI_ACTIVE;
5628                         spin_unlock_irq(&phba->hbalock);
5629                         rc = -ENXIO;
5630                 } else {
5631                         /* Allow asynchronous mailbox command to go through */
5632                         spin_lock_irq(&phba->hbalock);
5633                         phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
5634                         spin_unlock_irq(&phba->hbalock);
5635                         done = 1;
5636
5637                         if ((pmb->u.mb.un.varCfgPort.casabt == 1) &&
5638                             (pmb->u.mb.un.varCfgPort.gasabt == 0))
5639                                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
5640                                         "3110 Port did not grant ASABT\n");
5641                 }
5642         }
5643         if (!done) {
5644                 rc = -EINVAL;
5645                 goto do_prep_failed;
5646         }
5647         if (pmb->u.mb.un.varCfgPort.sli_mode == 3) {
5648                 if (!pmb->u.mb.un.varCfgPort.cMA) {
5649                         rc = -ENXIO;
5650                         goto do_prep_failed;
5651                 }
5652                 if (phba->max_vpi && pmb->u.mb.un.varCfgPort.gmv) {
5653                         phba->sli3_options |= LPFC_SLI3_NPIV_ENABLED;
5654                         phba->max_vpi = pmb->u.mb.un.varCfgPort.max_vpi;
5655                         phba->max_vports = (phba->max_vpi > phba->max_vports) ?
5656                                 phba->max_vpi : phba->max_vports;
5657
5658                 } else
5659                         phba->max_vpi = 0;
5660                 if (pmb->u.mb.un.varCfgPort.gerbm)
5661                         phba->sli3_options |= LPFC_SLI3_HBQ_ENABLED;
5662                 if (pmb->u.mb.un.varCfgPort.gcrp)
5663                         phba->sli3_options |= LPFC_SLI3_CRP_ENABLED;
5664
5665                 phba->hbq_get = phba->mbox->us.s3_pgp.hbq_get;
5666                 phba->port_gp = phba->mbox->us.s3_pgp.port;
5667
5668                 if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
5669                         if (pmb->u.mb.un.varCfgPort.gbg == 0) {
5670                                 phba->cfg_enable_bg = 0;
5671                                 phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
5672                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5673                                                 "0443 Adapter did not grant "
5674                                                 "BlockGuard\n");
5675                         }
5676                 }
5677         } else {
5678                 phba->hbq_get = NULL;
5679                 phba->port_gp = phba->mbox->us.s2.port;
5680                 phba->max_vpi = 0;
5681         }
5682 do_prep_failed:
5683         mempool_free(pmb, phba->mbox_mem_pool);
5684         return rc;
5685 }
5686
5687
5688 /**
5689  * lpfc_sli_hba_setup - SLI initialization function
5690  * @phba: Pointer to HBA context object.
5691  *
5692  * This function is the main SLI initialization function. This function
5693  * is called by the HBA initialization code, HBA reset code and HBA
5694  * error attention handler code. Caller is not required to hold any
5695  * locks. This function issues config_port mailbox command to configure
5696  * the SLI, setup iocb rings and HBQ rings. In the end the function
5697  * calls the config_port_post function to issue init_link mailbox
5698  * command and to start the discovery. The function will return zero
5699  * if successful, else it will return negative error code.
5700  **/
5701 int
5702 lpfc_sli_hba_setup(struct lpfc_hba *phba)
5703 {
5704         uint32_t rc;
5705         int  i;
5706         int longs;
5707
5708         /* Enable ISR already does config_port because of config_msi mbx */
5709         if (test_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag)) {
5710                 rc = lpfc_sli_config_port(phba, LPFC_SLI_REV3);
5711                 if (rc)
5712                         return -EIO;
5713                 clear_bit(HBA_NEEDS_CFG_PORT, &phba->hba_flag);
5714         }
5715         phba->fcp_embed_io = 0; /* SLI4 FC support only */
5716
5717         if (phba->sli_rev == 3) {
5718                 phba->iocb_cmd_size = SLI3_IOCB_CMD_SIZE;
5719                 phba->iocb_rsp_size = SLI3_IOCB_RSP_SIZE;
5720         } else {
5721                 phba->iocb_cmd_size = SLI2_IOCB_CMD_SIZE;
5722                 phba->iocb_rsp_size = SLI2_IOCB_RSP_SIZE;
5723                 phba->sli3_options = 0;
5724         }
5725
5726         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
5727                         "0444 Firmware in SLI %x mode. Max_vpi %d\n",
5728                         phba->sli_rev, phba->max_vpi);
5729         rc = lpfc_sli_ring_map(phba);
5730
5731         if (rc)
5732                 goto lpfc_sli_hba_setup_error;
5733
5734         /* Initialize VPIs. */
5735         if (phba->sli_rev == LPFC_SLI_REV3) {
5736                 /*
5737                  * The VPI bitmask and physical ID array are allocated
5738                  * and initialized once only - at driver load.  A port
5739                  * reset doesn't need to reinitialize this memory.
5740                  */
5741                 if ((phba->vpi_bmask == NULL) && (phba->vpi_ids == NULL)) {
5742                         longs = (phba->max_vpi + BITS_PER_LONG) / BITS_PER_LONG;
5743                         phba->vpi_bmask = kcalloc(longs,
5744                                                   sizeof(unsigned long),
5745                                                   GFP_KERNEL);
5746                         if (!phba->vpi_bmask) {
5747                                 rc = -ENOMEM;
5748                                 goto lpfc_sli_hba_setup_error;
5749                         }
5750
5751                         phba->vpi_ids = kcalloc(phba->max_vpi + 1,
5752                                                 sizeof(uint16_t),
5753                                                 GFP_KERNEL);
5754                         if (!phba->vpi_ids) {
5755                                 kfree(phba->vpi_bmask);
5756                                 rc = -ENOMEM;
5757                                 goto lpfc_sli_hba_setup_error;
5758                         }
5759                         for (i = 0; i < phba->max_vpi; i++)
5760                                 phba->vpi_ids[i] = i;
5761                 }
5762         }
5763
5764         /* Init HBQs */
5765         if (phba->sli3_options & LPFC_SLI3_HBQ_ENABLED) {
5766                 rc = lpfc_sli_hbq_setup(phba);
5767                 if (rc)
5768                         goto lpfc_sli_hba_setup_error;
5769         }
5770         spin_lock_irq(&phba->hbalock);
5771         phba->sli.sli_flag |= LPFC_PROCESS_LA;
5772         spin_unlock_irq(&phba->hbalock);
5773
5774         rc = lpfc_config_port_post(phba);
5775         if (rc)
5776                 goto lpfc_sli_hba_setup_error;
5777
5778         return rc;
5779
5780 lpfc_sli_hba_setup_error:
5781         phba->link_state = LPFC_HBA_ERROR;
5782         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5783                         "0445 Firmware initialization failed\n");
5784         return rc;
5785 }
5786
5787 /**
5788  * lpfc_sli4_read_fcoe_params - Read fcoe params from conf region
5789  * @phba: Pointer to HBA context object.
5790  *
5791  * This function issue a dump mailbox command to read config region
5792  * 23 and parse the records in the region and populate driver
5793  * data structure.
5794  **/
5795 static int
5796 lpfc_sli4_read_fcoe_params(struct lpfc_hba *phba)
5797 {
5798         LPFC_MBOXQ_t *mboxq;
5799         struct lpfc_dmabuf *mp;
5800         struct lpfc_mqe *mqe;
5801         uint32_t data_length;
5802         int rc;
5803
5804         /* Program the default value of vlan_id and fc_map */
5805         phba->valid_vlan = 0;
5806         phba->fc_map[0] = LPFC_FCOE_FCF_MAP0;
5807         phba->fc_map[1] = LPFC_FCOE_FCF_MAP1;
5808         phba->fc_map[2] = LPFC_FCOE_FCF_MAP2;
5809
5810         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5811         if (!mboxq)
5812                 return -ENOMEM;
5813
5814         mqe = &mboxq->u.mqe;
5815         if (lpfc_sli4_dump_cfg_rg23(phba, mboxq)) {
5816                 rc = -ENOMEM;
5817                 goto out_free_mboxq;
5818         }
5819
5820         mp = mboxq->ctx_buf;
5821         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5822
5823         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
5824                         "(%d):2571 Mailbox cmd x%x Status x%x "
5825                         "Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5826                         "x%x x%x x%x x%x x%x x%x x%x x%x x%x "
5827                         "CQ: x%x x%x x%x x%x\n",
5828                         mboxq->vport ? mboxq->vport->vpi : 0,
5829                         bf_get(lpfc_mqe_command, mqe),
5830                         bf_get(lpfc_mqe_status, mqe),
5831                         mqe->un.mb_words[0], mqe->un.mb_words[1],
5832                         mqe->un.mb_words[2], mqe->un.mb_words[3],
5833                         mqe->un.mb_words[4], mqe->un.mb_words[5],
5834                         mqe->un.mb_words[6], mqe->un.mb_words[7],
5835                         mqe->un.mb_words[8], mqe->un.mb_words[9],
5836                         mqe->un.mb_words[10], mqe->un.mb_words[11],
5837                         mqe->un.mb_words[12], mqe->un.mb_words[13],
5838                         mqe->un.mb_words[14], mqe->un.mb_words[15],
5839                         mqe->un.mb_words[16], mqe->un.mb_words[50],
5840                         mboxq->mcqe.word0,
5841                         mboxq->mcqe.mcqe_tag0,  mboxq->mcqe.mcqe_tag1,
5842                         mboxq->mcqe.trailer);
5843
5844         if (rc) {
5845                 rc = -EIO;
5846                 goto out_free_mboxq;
5847         }
5848         data_length = mqe->un.mb_words[5];
5849         if (data_length > DMP_RGN23_SIZE) {
5850                 rc = -EIO;
5851                 goto out_free_mboxq;
5852         }
5853
5854         lpfc_parse_fcoe_conf(phba, mp->virt, data_length);
5855         rc = 0;
5856
5857 out_free_mboxq:
5858         lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
5859         return rc;
5860 }
5861
5862 /**
5863  * lpfc_sli4_read_rev - Issue READ_REV and collect vpd data
5864  * @phba: pointer to lpfc hba data structure.
5865  * @mboxq: pointer to the LPFC_MBOXQ_t structure.
5866  * @vpd: pointer to the memory to hold resulting port vpd data.
5867  * @vpd_size: On input, the number of bytes allocated to @vpd.
5868  *            On output, the number of data bytes in @vpd.
5869  *
5870  * This routine executes a READ_REV SLI4 mailbox command.  In
5871  * addition, this routine gets the port vpd data.
5872  *
5873  * Return codes
5874  *      0 - successful
5875  *      -ENOMEM - could not allocated memory.
5876  **/
5877 static int
5878 lpfc_sli4_read_rev(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
5879                     uint8_t *vpd, uint32_t *vpd_size)
5880 {
5881         int rc = 0;
5882         uint32_t dma_size;
5883         struct lpfc_dmabuf *dmabuf;
5884         struct lpfc_mqe *mqe;
5885
5886         dmabuf = kzalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
5887         if (!dmabuf)
5888                 return -ENOMEM;
5889
5890         /*
5891          * Get a DMA buffer for the vpd data resulting from the READ_REV
5892          * mailbox command.
5893          */
5894         dma_size = *vpd_size;
5895         dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev, dma_size,
5896                                           &dmabuf->phys, GFP_KERNEL);
5897         if (!dmabuf->virt) {
5898                 kfree(dmabuf);
5899                 return -ENOMEM;
5900         }
5901
5902         /*
5903          * The SLI4 implementation of READ_REV conflicts at word1,
5904          * bits 31:16 and SLI4 adds vpd functionality not present
5905          * in SLI3.  This code corrects the conflicts.
5906          */
5907         lpfc_read_rev(phba, mboxq);
5908         mqe = &mboxq->u.mqe;
5909         mqe->un.read_rev.vpd_paddr_high = putPaddrHigh(dmabuf->phys);
5910         mqe->un.read_rev.vpd_paddr_low = putPaddrLow(dmabuf->phys);
5911         mqe->un.read_rev.word1 &= 0x0000FFFF;
5912         bf_set(lpfc_mbx_rd_rev_vpd, &mqe->un.read_rev, 1);
5913         bf_set(lpfc_mbx_rd_rev_avail_len, &mqe->un.read_rev, dma_size);
5914
5915         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5916         if (rc) {
5917                 dma_free_coherent(&phba->pcidev->dev, dma_size,
5918                                   dmabuf->virt, dmabuf->phys);
5919                 kfree(dmabuf);
5920                 return -EIO;
5921         }
5922
5923         /*
5924          * The available vpd length cannot be bigger than the
5925          * DMA buffer passed to the port.  Catch the less than
5926          * case and update the caller's size.
5927          */
5928         if (mqe->un.read_rev.avail_vpd_len < *vpd_size)
5929                 *vpd_size = mqe->un.read_rev.avail_vpd_len;
5930
5931         memcpy(vpd, dmabuf->virt, *vpd_size);
5932
5933         dma_free_coherent(&phba->pcidev->dev, dma_size,
5934                           dmabuf->virt, dmabuf->phys);
5935         kfree(dmabuf);
5936         return 0;
5937 }
5938
5939 /**
5940  * lpfc_sli4_get_ctl_attr - Retrieve SLI4 device controller attributes
5941  * @phba: pointer to lpfc hba data structure.
5942  *
5943  * This routine retrieves SLI4 device physical port name this PCI function
5944  * is attached to.
5945  *
5946  * Return codes
5947  *      0 - successful
5948  *      otherwise - failed to retrieve controller attributes
5949  **/
5950 static int
5951 lpfc_sli4_get_ctl_attr(struct lpfc_hba *phba)
5952 {
5953         LPFC_MBOXQ_t *mboxq;
5954         struct lpfc_mbx_get_cntl_attributes *mbx_cntl_attr;
5955         struct lpfc_controller_attribute *cntl_attr;
5956         void *virtaddr = NULL;
5957         uint32_t alloclen, reqlen;
5958         uint32_t shdr_status, shdr_add_status;
5959         union lpfc_sli4_cfg_shdr *shdr;
5960         int rc;
5961
5962         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
5963         if (!mboxq)
5964                 return -ENOMEM;
5965
5966         /* Send COMMON_GET_CNTL_ATTRIBUTES mbox cmd */
5967         reqlen = sizeof(struct lpfc_mbx_get_cntl_attributes);
5968         alloclen = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
5969                         LPFC_MBOX_OPCODE_GET_CNTL_ATTRIBUTES, reqlen,
5970                         LPFC_SLI4_MBX_NEMBED);
5971
5972         if (alloclen < reqlen) {
5973                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
5974                                 "3084 Allocated DMA memory size (%d) is "
5975                                 "less than the requested DMA memory size "
5976                                 "(%d)\n", alloclen, reqlen);
5977                 rc = -ENOMEM;
5978                 goto out_free_mboxq;
5979         }
5980         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
5981         virtaddr = mboxq->sge_array->addr[0];
5982         mbx_cntl_attr = (struct lpfc_mbx_get_cntl_attributes *)virtaddr;
5983         shdr = &mbx_cntl_attr->cfg_shdr;
5984         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
5985         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
5986         if (shdr_status || shdr_add_status || rc) {
5987                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
5988                                 "3085 Mailbox x%x (x%x/x%x) failed, "
5989                                 "rc:x%x, status:x%x, add_status:x%x\n",
5990                                 bf_get(lpfc_mqe_command, &mboxq->u.mqe),
5991                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
5992                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
5993                                 rc, shdr_status, shdr_add_status);
5994                 rc = -ENXIO;
5995                 goto out_free_mboxq;
5996         }
5997
5998         cntl_attr = &mbx_cntl_attr->cntl_attr;
5999         phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_VAL;
6000         phba->sli4_hba.lnk_info.lnk_tp =
6001                 bf_get(lpfc_cntl_attr_lnk_type, cntl_attr);
6002         phba->sli4_hba.lnk_info.lnk_no =
6003                 bf_get(lpfc_cntl_attr_lnk_numb, cntl_attr);
6004         phba->sli4_hba.flash_id = bf_get(lpfc_cntl_attr_flash_id, cntl_attr);
6005         phba->sli4_hba.asic_rev = bf_get(lpfc_cntl_attr_asic_rev, cntl_attr);
6006
6007         memset(phba->BIOSVersion, 0, sizeof(phba->BIOSVersion));
6008         strlcat(phba->BIOSVersion, (char *)cntl_attr->bios_ver_str,
6009                 sizeof(phba->BIOSVersion));
6010
6011         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6012                         "3086 lnk_type:%d, lnk_numb:%d, bios_ver:%s, "
6013                         "flash_id: x%02x, asic_rev: x%02x\n",
6014                         phba->sli4_hba.lnk_info.lnk_tp,
6015                         phba->sli4_hba.lnk_info.lnk_no,
6016                         phba->BIOSVersion, phba->sli4_hba.flash_id,
6017                         phba->sli4_hba.asic_rev);
6018 out_free_mboxq:
6019         if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6020                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
6021         else
6022                 mempool_free(mboxq, phba->mbox_mem_pool);
6023         return rc;
6024 }
6025
6026 /**
6027  * lpfc_sli4_retrieve_pport_name - Retrieve SLI4 device physical port name
6028  * @phba: pointer to lpfc hba data structure.
6029  *
6030  * This routine retrieves SLI4 device physical port name this PCI function
6031  * is attached to.
6032  *
6033  * Return codes
6034  *      0 - successful
6035  *      otherwise - failed to retrieve physical port name
6036  **/
6037 static int
6038 lpfc_sli4_retrieve_pport_name(struct lpfc_hba *phba)
6039 {
6040         LPFC_MBOXQ_t *mboxq;
6041         struct lpfc_mbx_get_port_name *get_port_name;
6042         uint32_t shdr_status, shdr_add_status;
6043         union lpfc_sli4_cfg_shdr *shdr;
6044         char cport_name = 0;
6045         int rc;
6046
6047         /* We assume nothing at this point */
6048         phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6049         phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_NON;
6050
6051         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6052         if (!mboxq)
6053                 return -ENOMEM;
6054         /* obtain link type and link number via READ_CONFIG */
6055         phba->sli4_hba.lnk_info.lnk_dv = LPFC_LNK_DAT_INVAL;
6056         lpfc_sli4_read_config(phba);
6057
6058         if (phba->sli4_hba.fawwpn_flag & LPFC_FAWWPN_CONFIG)
6059                 phba->sli4_hba.fawwpn_flag |= LPFC_FAWWPN_FABRIC;
6060
6061         if (phba->sli4_hba.lnk_info.lnk_dv == LPFC_LNK_DAT_VAL)
6062                 goto retrieve_ppname;
6063
6064         /* obtain link type and link number via COMMON_GET_CNTL_ATTRIBUTES */
6065         rc = lpfc_sli4_get_ctl_attr(phba);
6066         if (rc)
6067                 goto out_free_mboxq;
6068
6069 retrieve_ppname:
6070         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
6071                 LPFC_MBOX_OPCODE_GET_PORT_NAME,
6072                 sizeof(struct lpfc_mbx_get_port_name) -
6073                 sizeof(struct lpfc_sli4_cfg_mhdr),
6074                 LPFC_SLI4_MBX_EMBED);
6075         get_port_name = &mboxq->u.mqe.un.get_port_name;
6076         shdr = (union lpfc_sli4_cfg_shdr *)&get_port_name->header.cfg_shdr;
6077         bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_OPCODE_VERSION_1);
6078         bf_set(lpfc_mbx_get_port_name_lnk_type, &get_port_name->u.request,
6079                 phba->sli4_hba.lnk_info.lnk_tp);
6080         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
6081         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6082         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6083         if (shdr_status || shdr_add_status || rc) {
6084                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
6085                                 "3087 Mailbox x%x (x%x/x%x) failed: "
6086                                 "rc:x%x, status:x%x, add_status:x%x\n",
6087                                 bf_get(lpfc_mqe_command, &mboxq->u.mqe),
6088                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
6089                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
6090                                 rc, shdr_status, shdr_add_status);
6091                 rc = -ENXIO;
6092                 goto out_free_mboxq;
6093         }
6094         switch (phba->sli4_hba.lnk_info.lnk_no) {
6095         case LPFC_LINK_NUMBER_0:
6096                 cport_name = bf_get(lpfc_mbx_get_port_name_name0,
6097                                 &get_port_name->u.response);
6098                 phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6099                 break;
6100         case LPFC_LINK_NUMBER_1:
6101                 cport_name = bf_get(lpfc_mbx_get_port_name_name1,
6102                                 &get_port_name->u.response);
6103                 phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6104                 break;
6105         case LPFC_LINK_NUMBER_2:
6106                 cport_name = bf_get(lpfc_mbx_get_port_name_name2,
6107                                 &get_port_name->u.response);
6108                 phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6109                 break;
6110         case LPFC_LINK_NUMBER_3:
6111                 cport_name = bf_get(lpfc_mbx_get_port_name_name3,
6112                                 &get_port_name->u.response);
6113                 phba->sli4_hba.pport_name_sta = LPFC_SLI4_PPNAME_GET;
6114                 break;
6115         default:
6116                 break;
6117         }
6118
6119         if (phba->sli4_hba.pport_name_sta == LPFC_SLI4_PPNAME_GET) {
6120                 phba->Port[0] = cport_name;
6121                 phba->Port[1] = '\0';
6122                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6123                                 "3091 SLI get port name: %s\n", phba->Port);
6124         }
6125
6126 out_free_mboxq:
6127         if (bf_get(lpfc_mqe_command, &mboxq->u.mqe) == MBX_SLI4_CONFIG)
6128                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
6129         else
6130                 mempool_free(mboxq, phba->mbox_mem_pool);
6131         return rc;
6132 }
6133
6134 /**
6135  * lpfc_sli4_arm_cqeq_intr - Arm sli-4 device completion and event queues
6136  * @phba: pointer to lpfc hba data structure.
6137  *
6138  * This routine is called to explicitly arm the SLI4 device's completion and
6139  * event queues
6140  **/
6141 static void
6142 lpfc_sli4_arm_cqeq_intr(struct lpfc_hba *phba)
6143 {
6144         int qidx;
6145         struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
6146         struct lpfc_sli4_hdw_queue *qp;
6147         struct lpfc_queue *eq;
6148
6149         sli4_hba->sli4_write_cq_db(phba, sli4_hba->mbx_cq, 0, LPFC_QUEUE_REARM);
6150         sli4_hba->sli4_write_cq_db(phba, sli4_hba->els_cq, 0, LPFC_QUEUE_REARM);
6151         if (sli4_hba->nvmels_cq)
6152                 sli4_hba->sli4_write_cq_db(phba, sli4_hba->nvmels_cq, 0,
6153                                            LPFC_QUEUE_REARM);
6154
6155         if (sli4_hba->hdwq) {
6156                 /* Loop thru all Hardware Queues */
6157                 for (qidx = 0; qidx < phba->cfg_hdw_queue; qidx++) {
6158                         qp = &sli4_hba->hdwq[qidx];
6159                         /* ARM the corresponding CQ */
6160                         sli4_hba->sli4_write_cq_db(phba, qp->io_cq, 0,
6161                                                 LPFC_QUEUE_REARM);
6162                 }
6163
6164                 /* Loop thru all IRQ vectors */
6165                 for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
6166                         eq = sli4_hba->hba_eq_hdl[qidx].eq;
6167                         /* ARM the corresponding EQ */
6168                         sli4_hba->sli4_write_eq_db(phba, eq,
6169                                                    0, LPFC_QUEUE_REARM);
6170                 }
6171         }
6172
6173         if (phba->nvmet_support) {
6174                 for (qidx = 0; qidx < phba->cfg_nvmet_mrq; qidx++) {
6175                         sli4_hba->sli4_write_cq_db(phba,
6176                                 sli4_hba->nvmet_cqset[qidx], 0,
6177                                 LPFC_QUEUE_REARM);
6178                 }
6179         }
6180 }
6181
6182 /**
6183  * lpfc_sli4_get_avail_extnt_rsrc - Get available resource extent count.
6184  * @phba: Pointer to HBA context object.
6185  * @type: The resource extent type.
6186  * @extnt_count: buffer to hold port available extent count.
6187  * @extnt_size: buffer to hold element count per extent.
6188  *
6189  * This function calls the port and retrievs the number of available
6190  * extents and their size for a particular extent type.
6191  *
6192  * Returns: 0 if successful.  Nonzero otherwise.
6193  **/
6194 int
6195 lpfc_sli4_get_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type,
6196                                uint16_t *extnt_count, uint16_t *extnt_size)
6197 {
6198         int rc = 0;
6199         uint32_t length;
6200         uint32_t mbox_tmo;
6201         struct lpfc_mbx_get_rsrc_extent_info *rsrc_info;
6202         LPFC_MBOXQ_t *mbox;
6203
6204         *extnt_count = 0;
6205         *extnt_size = 0;
6206
6207         mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6208         if (!mbox)
6209                 return -ENOMEM;
6210
6211         /* Find out how many extents are available for this resource type */
6212         length = (sizeof(struct lpfc_mbx_get_rsrc_extent_info) -
6213                   sizeof(struct lpfc_sli4_cfg_mhdr));
6214         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6215                          LPFC_MBOX_OPCODE_GET_RSRC_EXTENT_INFO,
6216                          length, LPFC_SLI4_MBX_EMBED);
6217
6218         /* Send an extents count of 0 - the GET doesn't use it. */
6219         rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6220                                         LPFC_SLI4_MBX_EMBED);
6221         if (unlikely(rc)) {
6222                 rc = -EIO;
6223                 goto err_exit;
6224         }
6225
6226         if (!phba->sli4_hba.intr_enable)
6227                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6228         else {
6229                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6230                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6231         }
6232         if (unlikely(rc)) {
6233                 rc = -EIO;
6234                 goto err_exit;
6235         }
6236
6237         rsrc_info = &mbox->u.mqe.un.rsrc_extent_info;
6238         if (bf_get(lpfc_mbox_hdr_status,
6239                    &rsrc_info->header.cfg_shdr.response)) {
6240                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6241                                 "2930 Failed to get resource extents "
6242                                 "Status 0x%x Add'l Status 0x%x\n",
6243                                 bf_get(lpfc_mbox_hdr_status,
6244                                        &rsrc_info->header.cfg_shdr.response),
6245                                 bf_get(lpfc_mbox_hdr_add_status,
6246                                        &rsrc_info->header.cfg_shdr.response));
6247                 rc = -EIO;
6248                 goto err_exit;
6249         }
6250
6251         *extnt_count = bf_get(lpfc_mbx_get_rsrc_extent_info_cnt,
6252                               &rsrc_info->u.rsp);
6253         *extnt_size = bf_get(lpfc_mbx_get_rsrc_extent_info_size,
6254                              &rsrc_info->u.rsp);
6255
6256         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
6257                         "3162 Retrieved extents type-%d from port: count:%d, "
6258                         "size:%d\n", type, *extnt_count, *extnt_size);
6259
6260 err_exit:
6261         mempool_free(mbox, phba->mbox_mem_pool);
6262         return rc;
6263 }
6264
6265 /**
6266  * lpfc_sli4_chk_avail_extnt_rsrc - Check for available SLI4 resource extents.
6267  * @phba: Pointer to HBA context object.
6268  * @type: The extent type to check.
6269  *
6270  * This function reads the current available extents from the port and checks
6271  * if the extent count or extent size has changed since the last access.
6272  * Callers use this routine post port reset to understand if there is a
6273  * extent reprovisioning requirement.
6274  *
6275  * Returns:
6276  *   -Error: error indicates problem.
6277  *   1: Extent count or size has changed.
6278  *   0: No changes.
6279  **/
6280 static int
6281 lpfc_sli4_chk_avail_extnt_rsrc(struct lpfc_hba *phba, uint16_t type)
6282 {
6283         uint16_t curr_ext_cnt, rsrc_ext_cnt;
6284         uint16_t size_diff, rsrc_ext_size;
6285         int rc = 0;
6286         struct lpfc_rsrc_blks *rsrc_entry;
6287         struct list_head *rsrc_blk_list = NULL;
6288
6289         size_diff = 0;
6290         curr_ext_cnt = 0;
6291         rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6292                                             &rsrc_ext_cnt,
6293                                             &rsrc_ext_size);
6294         if (unlikely(rc))
6295                 return -EIO;
6296
6297         switch (type) {
6298         case LPFC_RSC_TYPE_FCOE_RPI:
6299                 rsrc_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6300                 break;
6301         case LPFC_RSC_TYPE_FCOE_VPI:
6302                 rsrc_blk_list = &phba->lpfc_vpi_blk_list;
6303                 break;
6304         case LPFC_RSC_TYPE_FCOE_XRI:
6305                 rsrc_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6306                 break;
6307         case LPFC_RSC_TYPE_FCOE_VFI:
6308                 rsrc_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6309                 break;
6310         default:
6311                 break;
6312         }
6313
6314         list_for_each_entry(rsrc_entry, rsrc_blk_list, list) {
6315                 curr_ext_cnt++;
6316                 if (rsrc_entry->rsrc_size != rsrc_ext_size)
6317                         size_diff++;
6318         }
6319
6320         if (curr_ext_cnt != rsrc_ext_cnt || size_diff != 0)
6321                 rc = 1;
6322
6323         return rc;
6324 }
6325
6326 /**
6327  * lpfc_sli4_cfg_post_extnts -
6328  * @phba: Pointer to HBA context object.
6329  * @extnt_cnt: number of available extents.
6330  * @type: the extent type (rpi, xri, vfi, vpi).
6331  * @emb: buffer to hold either MBX_EMBED or MBX_NEMBED operation.
6332  * @mbox: pointer to the caller's allocated mailbox structure.
6333  *
6334  * This function executes the extents allocation request.  It also
6335  * takes care of the amount of memory needed to allocate or get the
6336  * allocated extents. It is the caller's responsibility to evaluate
6337  * the response.
6338  *
6339  * Returns:
6340  *   -Error:  Error value describes the condition found.
6341  *   0: if successful
6342  **/
6343 static int
6344 lpfc_sli4_cfg_post_extnts(struct lpfc_hba *phba, uint16_t extnt_cnt,
6345                           uint16_t type, bool *emb, LPFC_MBOXQ_t *mbox)
6346 {
6347         int rc = 0;
6348         uint32_t req_len;
6349         uint32_t emb_len;
6350         uint32_t alloc_len, mbox_tmo;
6351
6352         /* Calculate the total requested length of the dma memory */
6353         req_len = extnt_cnt * sizeof(uint16_t);
6354
6355         /*
6356          * Calculate the size of an embedded mailbox.  The uint32_t
6357          * accounts for extents-specific word.
6358          */
6359         emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
6360                 sizeof(uint32_t);
6361
6362         /*
6363          * Presume the allocation and response will fit into an embedded
6364          * mailbox.  If not true, reconfigure to a non-embedded mailbox.
6365          */
6366         *emb = LPFC_SLI4_MBX_EMBED;
6367         if (req_len > emb_len) {
6368                 req_len = extnt_cnt * sizeof(uint16_t) +
6369                         sizeof(union lpfc_sli4_cfg_shdr) +
6370                         sizeof(uint32_t);
6371                 *emb = LPFC_SLI4_MBX_NEMBED;
6372         }
6373
6374         alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6375                                      LPFC_MBOX_OPCODE_ALLOC_RSRC_EXTENT,
6376                                      req_len, *emb);
6377         if (alloc_len < req_len) {
6378                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6379                         "2982 Allocated DMA memory size (x%x) is "
6380                         "less than the requested DMA memory "
6381                         "size (x%x)\n", alloc_len, req_len);
6382                 return -ENOMEM;
6383         }
6384         rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, extnt_cnt, type, *emb);
6385         if (unlikely(rc))
6386                 return -EIO;
6387
6388         if (!phba->sli4_hba.intr_enable)
6389                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6390         else {
6391                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6392                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6393         }
6394
6395         if (unlikely(rc))
6396                 rc = -EIO;
6397         return rc;
6398 }
6399
6400 /**
6401  * lpfc_sli4_alloc_extent - Allocate an SLI4 resource extent.
6402  * @phba: Pointer to HBA context object.
6403  * @type:  The resource extent type to allocate.
6404  *
6405  * This function allocates the number of elements for the specified
6406  * resource type.
6407  **/
6408 static int
6409 lpfc_sli4_alloc_extent(struct lpfc_hba *phba, uint16_t type)
6410 {
6411         bool emb = false;
6412         uint16_t rsrc_id_cnt, rsrc_cnt, rsrc_size;
6413         uint16_t rsrc_id, rsrc_start, j, k;
6414         uint16_t *ids;
6415         int i, rc;
6416         unsigned long longs;
6417         unsigned long *bmask;
6418         struct lpfc_rsrc_blks *rsrc_blks;
6419         LPFC_MBOXQ_t *mbox;
6420         uint32_t length;
6421         struct lpfc_id_range *id_array = NULL;
6422         void *virtaddr = NULL;
6423         struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
6424         struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
6425         struct list_head *ext_blk_list;
6426
6427         rc = lpfc_sli4_get_avail_extnt_rsrc(phba, type,
6428                                             &rsrc_cnt,
6429                                             &rsrc_size);
6430         if (unlikely(rc))
6431                 return -EIO;
6432
6433         if ((rsrc_cnt == 0) || (rsrc_size == 0)) {
6434                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6435                         "3009 No available Resource Extents "
6436                         "for resource type 0x%x: Count: 0x%x, "
6437                         "Size 0x%x\n", type, rsrc_cnt,
6438                         rsrc_size);
6439                 return -ENOMEM;
6440         }
6441
6442         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_INIT | LOG_SLI,
6443                         "2903 Post resource extents type-0x%x: "
6444                         "count:%d, size %d\n", type, rsrc_cnt, rsrc_size);
6445
6446         mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6447         if (!mbox)
6448                 return -ENOMEM;
6449
6450         rc = lpfc_sli4_cfg_post_extnts(phba, rsrc_cnt, type, &emb, mbox);
6451         if (unlikely(rc)) {
6452                 rc = -EIO;
6453                 goto err_exit;
6454         }
6455
6456         /*
6457          * Figure out where the response is located.  Then get local pointers
6458          * to the response data.  The port does not guarantee to respond to
6459          * all extents counts request so update the local variable with the
6460          * allocated count from the port.
6461          */
6462         if (emb == LPFC_SLI4_MBX_EMBED) {
6463                 rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
6464                 id_array = &rsrc_ext->u.rsp.id[0];
6465                 rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
6466         } else {
6467                 virtaddr = mbox->sge_array->addr[0];
6468                 n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
6469                 rsrc_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
6470                 id_array = &n_rsrc->id;
6471         }
6472
6473         longs = ((rsrc_cnt * rsrc_size) + BITS_PER_LONG - 1) / BITS_PER_LONG;
6474         rsrc_id_cnt = rsrc_cnt * rsrc_size;
6475
6476         /*
6477          * Based on the resource size and count, correct the base and max
6478          * resource values.
6479          */
6480         length = sizeof(struct lpfc_rsrc_blks);
6481         switch (type) {
6482         case LPFC_RSC_TYPE_FCOE_RPI:
6483                 phba->sli4_hba.rpi_bmask = kcalloc(longs,
6484                                                    sizeof(unsigned long),
6485                                                    GFP_KERNEL);
6486                 if (unlikely(!phba->sli4_hba.rpi_bmask)) {
6487                         rc = -ENOMEM;
6488                         goto err_exit;
6489                 }
6490                 phba->sli4_hba.rpi_ids = kcalloc(rsrc_id_cnt,
6491                                                  sizeof(uint16_t),
6492                                                  GFP_KERNEL);
6493                 if (unlikely(!phba->sli4_hba.rpi_ids)) {
6494                         kfree(phba->sli4_hba.rpi_bmask);
6495                         rc = -ENOMEM;
6496                         goto err_exit;
6497                 }
6498
6499                 /*
6500                  * The next_rpi was initialized with the maximum available
6501                  * count but the port may allocate a smaller number.  Catch
6502                  * that case and update the next_rpi.
6503                  */
6504                 phba->sli4_hba.next_rpi = rsrc_id_cnt;
6505
6506                 /* Initialize local ptrs for common extent processing later. */
6507                 bmask = phba->sli4_hba.rpi_bmask;
6508                 ids = phba->sli4_hba.rpi_ids;
6509                 ext_blk_list = &phba->sli4_hba.lpfc_rpi_blk_list;
6510                 break;
6511         case LPFC_RSC_TYPE_FCOE_VPI:
6512                 phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
6513                                           GFP_KERNEL);
6514                 if (unlikely(!phba->vpi_bmask)) {
6515                         rc = -ENOMEM;
6516                         goto err_exit;
6517                 }
6518                 phba->vpi_ids = kcalloc(rsrc_id_cnt, sizeof(uint16_t),
6519                                          GFP_KERNEL);
6520                 if (unlikely(!phba->vpi_ids)) {
6521                         kfree(phba->vpi_bmask);
6522                         rc = -ENOMEM;
6523                         goto err_exit;
6524                 }
6525
6526                 /* Initialize local ptrs for common extent processing later. */
6527                 bmask = phba->vpi_bmask;
6528                 ids = phba->vpi_ids;
6529                 ext_blk_list = &phba->lpfc_vpi_blk_list;
6530                 break;
6531         case LPFC_RSC_TYPE_FCOE_XRI:
6532                 phba->sli4_hba.xri_bmask = kcalloc(longs,
6533                                                    sizeof(unsigned long),
6534                                                    GFP_KERNEL);
6535                 if (unlikely(!phba->sli4_hba.xri_bmask)) {
6536                         rc = -ENOMEM;
6537                         goto err_exit;
6538                 }
6539                 phba->sli4_hba.max_cfg_param.xri_used = 0;
6540                 phba->sli4_hba.xri_ids = kcalloc(rsrc_id_cnt,
6541                                                  sizeof(uint16_t),
6542                                                  GFP_KERNEL);
6543                 if (unlikely(!phba->sli4_hba.xri_ids)) {
6544                         kfree(phba->sli4_hba.xri_bmask);
6545                         rc = -ENOMEM;
6546                         goto err_exit;
6547                 }
6548
6549                 /* Initialize local ptrs for common extent processing later. */
6550                 bmask = phba->sli4_hba.xri_bmask;
6551                 ids = phba->sli4_hba.xri_ids;
6552                 ext_blk_list = &phba->sli4_hba.lpfc_xri_blk_list;
6553                 break;
6554         case LPFC_RSC_TYPE_FCOE_VFI:
6555                 phba->sli4_hba.vfi_bmask = kcalloc(longs,
6556                                                    sizeof(unsigned long),
6557                                                    GFP_KERNEL);
6558                 if (unlikely(!phba->sli4_hba.vfi_bmask)) {
6559                         rc = -ENOMEM;
6560                         goto err_exit;
6561                 }
6562                 phba->sli4_hba.vfi_ids = kcalloc(rsrc_id_cnt,
6563                                                  sizeof(uint16_t),
6564                                                  GFP_KERNEL);
6565                 if (unlikely(!phba->sli4_hba.vfi_ids)) {
6566                         kfree(phba->sli4_hba.vfi_bmask);
6567                         rc = -ENOMEM;
6568                         goto err_exit;
6569                 }
6570
6571                 /* Initialize local ptrs for common extent processing later. */
6572                 bmask = phba->sli4_hba.vfi_bmask;
6573                 ids = phba->sli4_hba.vfi_ids;
6574                 ext_blk_list = &phba->sli4_hba.lpfc_vfi_blk_list;
6575                 break;
6576         default:
6577                 /* Unsupported Opcode.  Fail call. */
6578                 id_array = NULL;
6579                 bmask = NULL;
6580                 ids = NULL;
6581                 ext_blk_list = NULL;
6582                 goto err_exit;
6583         }
6584
6585         /*
6586          * Complete initializing the extent configuration with the
6587          * allocated ids assigned to this function.  The bitmask serves
6588          * as an index into the array and manages the available ids.  The
6589          * array just stores the ids communicated to the port via the wqes.
6590          */
6591         for (i = 0, j = 0, k = 0; i < rsrc_cnt; i++) {
6592                 if ((i % 2) == 0)
6593                         rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_0,
6594                                          &id_array[k]);
6595                 else
6596                         rsrc_id = bf_get(lpfc_mbx_rsrc_id_word4_1,
6597                                          &id_array[k]);
6598
6599                 rsrc_blks = kzalloc(length, GFP_KERNEL);
6600                 if (unlikely(!rsrc_blks)) {
6601                         rc = -ENOMEM;
6602                         kfree(bmask);
6603                         kfree(ids);
6604                         goto err_exit;
6605                 }
6606                 rsrc_blks->rsrc_start = rsrc_id;
6607                 rsrc_blks->rsrc_size = rsrc_size;
6608                 list_add_tail(&rsrc_blks->list, ext_blk_list);
6609                 rsrc_start = rsrc_id;
6610                 if ((type == LPFC_RSC_TYPE_FCOE_XRI) && (j == 0)) {
6611                         phba->sli4_hba.io_xri_start = rsrc_start +
6612                                 lpfc_sli4_get_iocb_cnt(phba);
6613                 }
6614
6615                 while (rsrc_id < (rsrc_start + rsrc_size)) {
6616                         ids[j] = rsrc_id;
6617                         rsrc_id++;
6618                         j++;
6619                 }
6620                 /* Entire word processed.  Get next word.*/
6621                 if ((i % 2) == 1)
6622                         k++;
6623         }
6624  err_exit:
6625         lpfc_sli4_mbox_cmd_free(phba, mbox);
6626         return rc;
6627 }
6628
6629
6630
6631 /**
6632  * lpfc_sli4_dealloc_extent - Deallocate an SLI4 resource extent.
6633  * @phba: Pointer to HBA context object.
6634  * @type: the extent's type.
6635  *
6636  * This function deallocates all extents of a particular resource type.
6637  * SLI4 does not allow for deallocating a particular extent range.  It
6638  * is the caller's responsibility to release all kernel memory resources.
6639  **/
6640 static int
6641 lpfc_sli4_dealloc_extent(struct lpfc_hba *phba, uint16_t type)
6642 {
6643         int rc;
6644         uint32_t length, mbox_tmo = 0;
6645         LPFC_MBOXQ_t *mbox;
6646         struct lpfc_mbx_dealloc_rsrc_extents *dealloc_rsrc;
6647         struct lpfc_rsrc_blks *rsrc_blk, *rsrc_blk_next;
6648
6649         mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
6650         if (!mbox)
6651                 return -ENOMEM;
6652
6653         /*
6654          * This function sends an embedded mailbox because it only sends the
6655          * the resource type.  All extents of this type are released by the
6656          * port.
6657          */
6658         length = (sizeof(struct lpfc_mbx_dealloc_rsrc_extents) -
6659                   sizeof(struct lpfc_sli4_cfg_mhdr));
6660         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6661                          LPFC_MBOX_OPCODE_DEALLOC_RSRC_EXTENT,
6662                          length, LPFC_SLI4_MBX_EMBED);
6663
6664         /* Send an extents count of 0 - the dealloc doesn't use it. */
6665         rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, 0, type,
6666                                         LPFC_SLI4_MBX_EMBED);
6667         if (unlikely(rc)) {
6668                 rc = -EIO;
6669                 goto out_free_mbox;
6670         }
6671         if (!phba->sli4_hba.intr_enable)
6672                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
6673         else {
6674                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
6675                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
6676         }
6677         if (unlikely(rc)) {
6678                 rc = -EIO;
6679                 goto out_free_mbox;
6680         }
6681
6682         dealloc_rsrc = &mbox->u.mqe.un.dealloc_rsrc_extents;
6683         if (bf_get(lpfc_mbox_hdr_status,
6684                    &dealloc_rsrc->header.cfg_shdr.response)) {
6685                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6686                                 "2919 Failed to release resource extents "
6687                                 "for type %d - Status 0x%x Add'l Status 0x%x. "
6688                                 "Resource memory not released.\n",
6689                                 type,
6690                                 bf_get(lpfc_mbox_hdr_status,
6691                                     &dealloc_rsrc->header.cfg_shdr.response),
6692                                 bf_get(lpfc_mbox_hdr_add_status,
6693                                     &dealloc_rsrc->header.cfg_shdr.response));
6694                 rc = -EIO;
6695                 goto out_free_mbox;
6696         }
6697
6698         /* Release kernel memory resources for the specific type. */
6699         switch (type) {
6700         case LPFC_RSC_TYPE_FCOE_VPI:
6701                 kfree(phba->vpi_bmask);
6702                 kfree(phba->vpi_ids);
6703                 bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6704                 list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6705                                     &phba->lpfc_vpi_blk_list, list) {
6706                         list_del_init(&rsrc_blk->list);
6707                         kfree(rsrc_blk);
6708                 }
6709                 phba->sli4_hba.max_cfg_param.vpi_used = 0;
6710                 break;
6711         case LPFC_RSC_TYPE_FCOE_XRI:
6712                 kfree(phba->sli4_hba.xri_bmask);
6713                 kfree(phba->sli4_hba.xri_ids);
6714                 list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6715                                     &phba->sli4_hba.lpfc_xri_blk_list, list) {
6716                         list_del_init(&rsrc_blk->list);
6717                         kfree(rsrc_blk);
6718                 }
6719                 break;
6720         case LPFC_RSC_TYPE_FCOE_VFI:
6721                 kfree(phba->sli4_hba.vfi_bmask);
6722                 kfree(phba->sli4_hba.vfi_ids);
6723                 bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6724                 list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6725                                     &phba->sli4_hba.lpfc_vfi_blk_list, list) {
6726                         list_del_init(&rsrc_blk->list);
6727                         kfree(rsrc_blk);
6728                 }
6729                 break;
6730         case LPFC_RSC_TYPE_FCOE_RPI:
6731                 /* RPI bitmask and physical id array are cleaned up earlier. */
6732                 list_for_each_entry_safe(rsrc_blk, rsrc_blk_next,
6733                                     &phba->sli4_hba.lpfc_rpi_blk_list, list) {
6734                         list_del_init(&rsrc_blk->list);
6735                         kfree(rsrc_blk);
6736                 }
6737                 break;
6738         default:
6739                 break;
6740         }
6741
6742         bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
6743
6744  out_free_mbox:
6745         mempool_free(mbox, phba->mbox_mem_pool);
6746         return rc;
6747 }
6748
6749 static void
6750 lpfc_set_features(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox,
6751                   uint32_t feature)
6752 {
6753         uint32_t len;
6754         u32 sig_freq = 0;
6755
6756         len = sizeof(struct lpfc_mbx_set_feature) -
6757                 sizeof(struct lpfc_sli4_cfg_mhdr);
6758         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
6759                          LPFC_MBOX_OPCODE_SET_FEATURES, len,
6760                          LPFC_SLI4_MBX_EMBED);
6761
6762         switch (feature) {
6763         case LPFC_SET_UE_RECOVERY:
6764                 bf_set(lpfc_mbx_set_feature_UER,
6765                        &mbox->u.mqe.un.set_feature, 1);
6766                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_UE_RECOVERY;
6767                 mbox->u.mqe.un.set_feature.param_len = 8;
6768                 break;
6769         case LPFC_SET_MDS_DIAGS:
6770                 bf_set(lpfc_mbx_set_feature_mds,
6771                        &mbox->u.mqe.un.set_feature, 1);
6772                 bf_set(lpfc_mbx_set_feature_mds_deep_loopbk,
6773                        &mbox->u.mqe.un.set_feature, 1);
6774                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_MDS_DIAGS;
6775                 mbox->u.mqe.un.set_feature.param_len = 8;
6776                 break;
6777         case LPFC_SET_CGN_SIGNAL:
6778                 if (phba->cmf_active_mode == LPFC_CFG_OFF)
6779                         sig_freq = 0;
6780                 else
6781                         sig_freq = phba->cgn_sig_freq;
6782
6783                 if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ALARM) {
6784                         bf_set(lpfc_mbx_set_feature_CGN_alarm_freq,
6785                                &mbox->u.mqe.un.set_feature, sig_freq);
6786                         bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6787                                &mbox->u.mqe.un.set_feature, sig_freq);
6788                 }
6789
6790                 if (phba->cgn_reg_signal == EDC_CG_SIG_WARN_ONLY)
6791                         bf_set(lpfc_mbx_set_feature_CGN_warn_freq,
6792                                &mbox->u.mqe.un.set_feature, sig_freq);
6793
6794                 if (phba->cmf_active_mode == LPFC_CFG_OFF ||
6795                     phba->cgn_reg_signal == EDC_CG_SIG_NOTSUPPORTED)
6796                         sig_freq = 0;
6797                 else
6798                         sig_freq = lpfc_acqe_cgn_frequency;
6799
6800                 bf_set(lpfc_mbx_set_feature_CGN_acqe_freq,
6801                        &mbox->u.mqe.un.set_feature, sig_freq);
6802
6803                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_CGN_SIGNAL;
6804                 mbox->u.mqe.un.set_feature.param_len = 12;
6805                 break;
6806         case LPFC_SET_DUAL_DUMP:
6807                 bf_set(lpfc_mbx_set_feature_dd,
6808                        &mbox->u.mqe.un.set_feature, LPFC_ENABLE_DUAL_DUMP);
6809                 bf_set(lpfc_mbx_set_feature_ddquery,
6810                        &mbox->u.mqe.un.set_feature, 0);
6811                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_DUAL_DUMP;
6812                 mbox->u.mqe.un.set_feature.param_len = 4;
6813                 break;
6814         case LPFC_SET_ENABLE_MI:
6815                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_MI;
6816                 mbox->u.mqe.un.set_feature.param_len = 4;
6817                 bf_set(lpfc_mbx_set_feature_milunq, &mbox->u.mqe.un.set_feature,
6818                        phba->pport->cfg_lun_queue_depth);
6819                 bf_set(lpfc_mbx_set_feature_mi, &mbox->u.mqe.un.set_feature,
6820                        phba->sli4_hba.pc_sli4_params.mi_ver);
6821                 break;
6822         case LPFC_SET_LD_SIGNAL:
6823                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_LD_SIGNAL;
6824                 mbox->u.mqe.un.set_feature.param_len = 16;
6825                 bf_set(lpfc_mbx_set_feature_lds_qry,
6826                        &mbox->u.mqe.un.set_feature, LPFC_QUERY_LDS_OP);
6827                 break;
6828         case LPFC_SET_ENABLE_CMF:
6829                 mbox->u.mqe.un.set_feature.feature = LPFC_SET_ENABLE_CMF;
6830                 mbox->u.mqe.un.set_feature.param_len = 4;
6831                 bf_set(lpfc_mbx_set_feature_cmf,
6832                        &mbox->u.mqe.un.set_feature, 1);
6833                 break;
6834         }
6835         return;
6836 }
6837
6838 /**
6839  * lpfc_ras_stop_fwlog: Disable FW logging by the adapter
6840  * @phba: Pointer to HBA context object.
6841  *
6842  * Disable FW logging into host memory on the adapter. To
6843  * be done before reading logs from the host memory.
6844  **/
6845 void
6846 lpfc_ras_stop_fwlog(struct lpfc_hba *phba)
6847 {
6848         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6849
6850         spin_lock_irq(&phba->ras_fwlog_lock);
6851         ras_fwlog->state = INACTIVE;
6852         spin_unlock_irq(&phba->ras_fwlog_lock);
6853
6854         /* Disable FW logging to host memory */
6855         writel(LPFC_CTL_PDEV_CTL_DDL_RAS,
6856                phba->sli4_hba.conf_regs_memmap_p + LPFC_CTL_PDEV_CTL_OFFSET);
6857
6858         /* Wait 10ms for firmware to stop using DMA buffer */
6859         usleep_range(10 * 1000, 20 * 1000);
6860 }
6861
6862 /**
6863  * lpfc_sli4_ras_dma_free - Free memory allocated for FW logging.
6864  * @phba: Pointer to HBA context object.
6865  *
6866  * This function is called to free memory allocated for RAS FW logging
6867  * support in the driver.
6868  **/
6869 void
6870 lpfc_sli4_ras_dma_free(struct lpfc_hba *phba)
6871 {
6872         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6873         struct lpfc_dmabuf *dmabuf, *next;
6874
6875         if (!list_empty(&ras_fwlog->fwlog_buff_list)) {
6876                 list_for_each_entry_safe(dmabuf, next,
6877                                     &ras_fwlog->fwlog_buff_list,
6878                                     list) {
6879                         list_del(&dmabuf->list);
6880                         dma_free_coherent(&phba->pcidev->dev,
6881                                           LPFC_RAS_MAX_ENTRY_SIZE,
6882                                           dmabuf->virt, dmabuf->phys);
6883                         kfree(dmabuf);
6884                 }
6885         }
6886
6887         if (ras_fwlog->lwpd.virt) {
6888                 dma_free_coherent(&phba->pcidev->dev,
6889                                   sizeof(uint32_t) * 2,
6890                                   ras_fwlog->lwpd.virt,
6891                                   ras_fwlog->lwpd.phys);
6892                 ras_fwlog->lwpd.virt = NULL;
6893         }
6894
6895         spin_lock_irq(&phba->ras_fwlog_lock);
6896         ras_fwlog->state = INACTIVE;
6897         spin_unlock_irq(&phba->ras_fwlog_lock);
6898 }
6899
6900 /**
6901  * lpfc_sli4_ras_dma_alloc: Allocate memory for FW support
6902  * @phba: Pointer to HBA context object.
6903  * @fwlog_buff_count: Count of buffers to be created.
6904  *
6905  * This routine DMA memory for Log Write Position Data[LPWD] and buffer
6906  * to update FW log is posted to the adapter.
6907  * Buffer count is calculated based on module param ras_fwlog_buffsize
6908  * Size of each buffer posted to FW is 64K.
6909  **/
6910
6911 static int
6912 lpfc_sli4_ras_dma_alloc(struct lpfc_hba *phba,
6913                         uint32_t fwlog_buff_count)
6914 {
6915         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6916         struct lpfc_dmabuf *dmabuf;
6917         int rc = 0, i = 0;
6918
6919         /* Initialize List */
6920         INIT_LIST_HEAD(&ras_fwlog->fwlog_buff_list);
6921
6922         /* Allocate memory for the LWPD */
6923         ras_fwlog->lwpd.virt = dma_alloc_coherent(&phba->pcidev->dev,
6924                                             sizeof(uint32_t) * 2,
6925                                             &ras_fwlog->lwpd.phys,
6926                                             GFP_KERNEL);
6927         if (!ras_fwlog->lwpd.virt) {
6928                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6929                                 "6185 LWPD Memory Alloc Failed\n");
6930
6931                 return -ENOMEM;
6932         }
6933
6934         ras_fwlog->fw_buffcount = fwlog_buff_count;
6935         for (i = 0; i < ras_fwlog->fw_buffcount; i++) {
6936                 dmabuf = kzalloc(sizeof(struct lpfc_dmabuf),
6937                                  GFP_KERNEL);
6938                 if (!dmabuf) {
6939                         rc = -ENOMEM;
6940                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6941                                         "6186 Memory Alloc failed FW logging");
6942                         goto free_mem;
6943                 }
6944
6945                 dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
6946                                                   LPFC_RAS_MAX_ENTRY_SIZE,
6947                                                   &dmabuf->phys, GFP_KERNEL);
6948                 if (!dmabuf->virt) {
6949                         kfree(dmabuf);
6950                         rc = -ENOMEM;
6951                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
6952                                         "6187 DMA Alloc Failed FW logging");
6953                         goto free_mem;
6954                 }
6955                 dmabuf->buffer_tag = i;
6956                 list_add_tail(&dmabuf->list, &ras_fwlog->fwlog_buff_list);
6957         }
6958
6959 free_mem:
6960         if (rc)
6961                 lpfc_sli4_ras_dma_free(phba);
6962
6963         return rc;
6964 }
6965
6966 /**
6967  * lpfc_sli4_ras_mbox_cmpl: Completion handler for RAS MBX command
6968  * @phba: pointer to lpfc hba data structure.
6969  * @pmb: pointer to the driver internal queue element for mailbox command.
6970  *
6971  * Completion handler for driver's RAS MBX command to the device.
6972  **/
6973 static void
6974 lpfc_sli4_ras_mbox_cmpl(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
6975 {
6976         MAILBOX_t *mb;
6977         union lpfc_sli4_cfg_shdr *shdr;
6978         uint32_t shdr_status, shdr_add_status;
6979         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
6980
6981         mb = &pmb->u.mb;
6982
6983         shdr = (union lpfc_sli4_cfg_shdr *)
6984                 &pmb->u.mqe.un.ras_fwlog.header.cfg_shdr;
6985         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
6986         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
6987
6988         if (mb->mbxStatus != MBX_SUCCESS || shdr_status) {
6989                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
6990                                 "6188 FW LOG mailbox "
6991                                 "completed with status x%x add_status x%x,"
6992                                 " mbx status x%x\n",
6993                                 shdr_status, shdr_add_status, mb->mbxStatus);
6994
6995                 ras_fwlog->ras_hwsupport = false;
6996                 goto disable_ras;
6997         }
6998
6999         spin_lock_irq(&phba->ras_fwlog_lock);
7000         ras_fwlog->state = ACTIVE;
7001         spin_unlock_irq(&phba->ras_fwlog_lock);
7002         mempool_free(pmb, phba->mbox_mem_pool);
7003
7004         return;
7005
7006 disable_ras:
7007         /* Free RAS DMA memory */
7008         lpfc_sli4_ras_dma_free(phba);
7009         mempool_free(pmb, phba->mbox_mem_pool);
7010 }
7011
7012 /**
7013  * lpfc_sli4_ras_fwlog_init: Initialize memory and post RAS MBX command
7014  * @phba: pointer to lpfc hba data structure.
7015  * @fwlog_level: Logging verbosity level.
7016  * @fwlog_enable: Enable/Disable logging.
7017  *
7018  * Initialize memory and post mailbox command to enable FW logging in host
7019  * memory.
7020  **/
7021 int
7022 lpfc_sli4_ras_fwlog_init(struct lpfc_hba *phba,
7023                          uint32_t fwlog_level,
7024                          uint32_t fwlog_enable)
7025 {
7026         struct lpfc_ras_fwlog *ras_fwlog = &phba->ras_fwlog;
7027         struct lpfc_mbx_set_ras_fwlog *mbx_fwlog = NULL;
7028         struct lpfc_dmabuf *dmabuf;
7029         LPFC_MBOXQ_t *mbox;
7030         uint32_t len = 0, fwlog_buffsize, fwlog_entry_count;
7031         int rc = 0;
7032
7033         spin_lock_irq(&phba->ras_fwlog_lock);
7034         ras_fwlog->state = INACTIVE;
7035         spin_unlock_irq(&phba->ras_fwlog_lock);
7036
7037         fwlog_buffsize = (LPFC_RAS_MIN_BUFF_POST_SIZE *
7038                           phba->cfg_ras_fwlog_buffsize);
7039         fwlog_entry_count = (fwlog_buffsize/LPFC_RAS_MAX_ENTRY_SIZE);
7040
7041         /*
7042          * If re-enabling FW logging support use earlier allocated
7043          * DMA buffers while posting MBX command.
7044          **/
7045         if (!ras_fwlog->lwpd.virt) {
7046                 rc = lpfc_sli4_ras_dma_alloc(phba, fwlog_entry_count);
7047                 if (rc) {
7048                         lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
7049                                         "6189 FW Log Memory Allocation Failed");
7050                         return rc;
7051                 }
7052         }
7053
7054         /* Setup Mailbox command */
7055         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7056         if (!mbox) {
7057                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7058                                 "6190 RAS MBX Alloc Failed");
7059                 rc = -ENOMEM;
7060                 goto mem_free;
7061         }
7062
7063         ras_fwlog->fw_loglevel = fwlog_level;
7064         len = (sizeof(struct lpfc_mbx_set_ras_fwlog) -
7065                 sizeof(struct lpfc_sli4_cfg_mhdr));
7066
7067         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_LOWLEVEL,
7068                          LPFC_MBOX_OPCODE_SET_DIAG_LOG_OPTION,
7069                          len, LPFC_SLI4_MBX_EMBED);
7070
7071         mbx_fwlog = (struct lpfc_mbx_set_ras_fwlog *)&mbox->u.mqe.un.ras_fwlog;
7072         bf_set(lpfc_fwlog_enable, &mbx_fwlog->u.request,
7073                fwlog_enable);
7074         bf_set(lpfc_fwlog_loglvl, &mbx_fwlog->u.request,
7075                ras_fwlog->fw_loglevel);
7076         bf_set(lpfc_fwlog_buffcnt, &mbx_fwlog->u.request,
7077                ras_fwlog->fw_buffcount);
7078         bf_set(lpfc_fwlog_buffsz, &mbx_fwlog->u.request,
7079                LPFC_RAS_MAX_ENTRY_SIZE/SLI4_PAGE_SIZE);
7080
7081         /* Update DMA buffer address */
7082         list_for_each_entry(dmabuf, &ras_fwlog->fwlog_buff_list, list) {
7083                 memset(dmabuf->virt, 0, LPFC_RAS_MAX_ENTRY_SIZE);
7084
7085                 mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_lo =
7086                         putPaddrLow(dmabuf->phys);
7087
7088                 mbx_fwlog->u.request.buff_fwlog[dmabuf->buffer_tag].addr_hi =
7089                         putPaddrHigh(dmabuf->phys);
7090         }
7091
7092         /* Update LPWD address */
7093         mbx_fwlog->u.request.lwpd.addr_lo = putPaddrLow(ras_fwlog->lwpd.phys);
7094         mbx_fwlog->u.request.lwpd.addr_hi = putPaddrHigh(ras_fwlog->lwpd.phys);
7095
7096         spin_lock_irq(&phba->ras_fwlog_lock);
7097         ras_fwlog->state = REG_INPROGRESS;
7098         spin_unlock_irq(&phba->ras_fwlog_lock);
7099         mbox->vport = phba->pport;
7100         mbox->mbox_cmpl = lpfc_sli4_ras_mbox_cmpl;
7101
7102         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
7103
7104         if (rc == MBX_NOT_FINISHED) {
7105                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7106                                 "6191 FW-Log Mailbox failed. "
7107                                 "status %d mbxStatus : x%x", rc,
7108                                 bf_get(lpfc_mqe_status, &mbox->u.mqe));
7109                 mempool_free(mbox, phba->mbox_mem_pool);
7110                 rc = -EIO;
7111                 goto mem_free;
7112         } else
7113                 rc = 0;
7114 mem_free:
7115         if (rc)
7116                 lpfc_sli4_ras_dma_free(phba);
7117
7118         return rc;
7119 }
7120
7121 /**
7122  * lpfc_sli4_ras_setup - Check if RAS supported on the adapter
7123  * @phba: Pointer to HBA context object.
7124  *
7125  * Check if RAS is supported on the adapter and initialize it.
7126  **/
7127 void
7128 lpfc_sli4_ras_setup(struct lpfc_hba *phba)
7129 {
7130         /* Check RAS FW Log needs to be enabled or not */
7131         if (lpfc_check_fwlog_support(phba))
7132                 return;
7133
7134         lpfc_sli4_ras_fwlog_init(phba, phba->cfg_ras_fwlog_level,
7135                                  LPFC_RAS_ENABLE_LOGGING);
7136 }
7137
7138 /**
7139  * lpfc_sli4_alloc_resource_identifiers - Allocate all SLI4 resource extents.
7140  * @phba: Pointer to HBA context object.
7141  *
7142  * This function allocates all SLI4 resource identifiers.
7143  **/
7144 int
7145 lpfc_sli4_alloc_resource_identifiers(struct lpfc_hba *phba)
7146 {
7147         int i, rc, error = 0;
7148         uint16_t count, base;
7149         unsigned long longs;
7150
7151         if (!phba->sli4_hba.rpi_hdrs_in_use)
7152                 phba->sli4_hba.next_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
7153         if (phba->sli4_hba.extents_in_use) {
7154                 /*
7155                  * The port supports resource extents. The XRI, VPI, VFI, RPI
7156                  * resource extent count must be read and allocated before
7157                  * provisioning the resource id arrays.
7158                  */
7159                 if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7160                     LPFC_IDX_RSRC_RDY) {
7161                         /*
7162                          * Extent-based resources are set - the driver could
7163                          * be in a port reset. Figure out if any corrective
7164                          * actions need to be taken.
7165                          */
7166                         rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7167                                                  LPFC_RSC_TYPE_FCOE_VFI);
7168                         if (rc != 0)
7169                                 error++;
7170                         rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7171                                                  LPFC_RSC_TYPE_FCOE_VPI);
7172                         if (rc != 0)
7173                                 error++;
7174                         rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7175                                                  LPFC_RSC_TYPE_FCOE_XRI);
7176                         if (rc != 0)
7177                                 error++;
7178                         rc = lpfc_sli4_chk_avail_extnt_rsrc(phba,
7179                                                  LPFC_RSC_TYPE_FCOE_RPI);
7180                         if (rc != 0)
7181                                 error++;
7182
7183                         /*
7184                          * It's possible that the number of resources
7185                          * provided to this port instance changed between
7186                          * resets.  Detect this condition and reallocate
7187                          * resources.  Otherwise, there is no action.
7188                          */
7189                         if (error) {
7190                                 lpfc_printf_log(phba, KERN_INFO,
7191                                                 LOG_MBOX | LOG_INIT,
7192                                                 "2931 Detected extent resource "
7193                                                 "change.  Reallocating all "
7194                                                 "extents.\n");
7195                                 rc = lpfc_sli4_dealloc_extent(phba,
7196                                                  LPFC_RSC_TYPE_FCOE_VFI);
7197                                 rc = lpfc_sli4_dealloc_extent(phba,
7198                                                  LPFC_RSC_TYPE_FCOE_VPI);
7199                                 rc = lpfc_sli4_dealloc_extent(phba,
7200                                                  LPFC_RSC_TYPE_FCOE_XRI);
7201                                 rc = lpfc_sli4_dealloc_extent(phba,
7202                                                  LPFC_RSC_TYPE_FCOE_RPI);
7203                         } else
7204                                 return 0;
7205                 }
7206
7207                 rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7208                 if (unlikely(rc))
7209                         goto err_exit;
7210
7211                 rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7212                 if (unlikely(rc))
7213                         goto err_exit;
7214
7215                 rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7216                 if (unlikely(rc))
7217                         goto err_exit;
7218
7219                 rc = lpfc_sli4_alloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7220                 if (unlikely(rc))
7221                         goto err_exit;
7222                 bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7223                        LPFC_IDX_RSRC_RDY);
7224                 return rc;
7225         } else {
7226                 /*
7227                  * The port does not support resource extents.  The XRI, VPI,
7228                  * VFI, RPI resource ids were determined from READ_CONFIG.
7229                  * Just allocate the bitmasks and provision the resource id
7230                  * arrays.  If a port reset is active, the resources don't
7231                  * need any action - just exit.
7232                  */
7233                 if (bf_get(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags) ==
7234                     LPFC_IDX_RSRC_RDY) {
7235                         lpfc_sli4_dealloc_resource_identifiers(phba);
7236                         lpfc_sli4_remove_rpis(phba);
7237                 }
7238                 /* RPIs. */
7239                 count = phba->sli4_hba.max_cfg_param.max_rpi;
7240                 if (count <= 0) {
7241                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7242                                         "3279 Invalid provisioning of "
7243                                         "rpi:%d\n", count);
7244                         rc = -EINVAL;
7245                         goto err_exit;
7246                 }
7247                 base = phba->sli4_hba.max_cfg_param.rpi_base;
7248                 longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7249                 phba->sli4_hba.rpi_bmask = kcalloc(longs,
7250                                                    sizeof(unsigned long),
7251                                                    GFP_KERNEL);
7252                 if (unlikely(!phba->sli4_hba.rpi_bmask)) {
7253                         rc = -ENOMEM;
7254                         goto err_exit;
7255                 }
7256                 phba->sli4_hba.rpi_ids = kcalloc(count, sizeof(uint16_t),
7257                                                  GFP_KERNEL);
7258                 if (unlikely(!phba->sli4_hba.rpi_ids)) {
7259                         rc = -ENOMEM;
7260                         goto free_rpi_bmask;
7261                 }
7262
7263                 for (i = 0; i < count; i++)
7264                         phba->sli4_hba.rpi_ids[i] = base + i;
7265
7266                 /* VPIs. */
7267                 count = phba->sli4_hba.max_cfg_param.max_vpi;
7268                 if (count <= 0) {
7269                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7270                                         "3280 Invalid provisioning of "
7271                                         "vpi:%d\n", count);
7272                         rc = -EINVAL;
7273                         goto free_rpi_ids;
7274                 }
7275                 base = phba->sli4_hba.max_cfg_param.vpi_base;
7276                 longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7277                 phba->vpi_bmask = kcalloc(longs, sizeof(unsigned long),
7278                                           GFP_KERNEL);
7279                 if (unlikely(!phba->vpi_bmask)) {
7280                         rc = -ENOMEM;
7281                         goto free_rpi_ids;
7282                 }
7283                 phba->vpi_ids = kcalloc(count, sizeof(uint16_t),
7284                                         GFP_KERNEL);
7285                 if (unlikely(!phba->vpi_ids)) {
7286                         rc = -ENOMEM;
7287                         goto free_vpi_bmask;
7288                 }
7289
7290                 for (i = 0; i < count; i++)
7291                         phba->vpi_ids[i] = base + i;
7292
7293                 /* XRIs. */
7294                 count = phba->sli4_hba.max_cfg_param.max_xri;
7295                 if (count <= 0) {
7296                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7297                                         "3281 Invalid provisioning of "
7298                                         "xri:%d\n", count);
7299                         rc = -EINVAL;
7300                         goto free_vpi_ids;
7301                 }
7302                 base = phba->sli4_hba.max_cfg_param.xri_base;
7303                 longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7304                 phba->sli4_hba.xri_bmask = kcalloc(longs,
7305                                                    sizeof(unsigned long),
7306                                                    GFP_KERNEL);
7307                 if (unlikely(!phba->sli4_hba.xri_bmask)) {
7308                         rc = -ENOMEM;
7309                         goto free_vpi_ids;
7310                 }
7311                 phba->sli4_hba.max_cfg_param.xri_used = 0;
7312                 phba->sli4_hba.xri_ids = kcalloc(count, sizeof(uint16_t),
7313                                                  GFP_KERNEL);
7314                 if (unlikely(!phba->sli4_hba.xri_ids)) {
7315                         rc = -ENOMEM;
7316                         goto free_xri_bmask;
7317                 }
7318
7319                 for (i = 0; i < count; i++)
7320                         phba->sli4_hba.xri_ids[i] = base + i;
7321
7322                 /* VFIs. */
7323                 count = phba->sli4_hba.max_cfg_param.max_vfi;
7324                 if (count <= 0) {
7325                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7326                                         "3282 Invalid provisioning of "
7327                                         "vfi:%d\n", count);
7328                         rc = -EINVAL;
7329                         goto free_xri_ids;
7330                 }
7331                 base = phba->sli4_hba.max_cfg_param.vfi_base;
7332                 longs = (count + BITS_PER_LONG - 1) / BITS_PER_LONG;
7333                 phba->sli4_hba.vfi_bmask = kcalloc(longs,
7334                                                    sizeof(unsigned long),
7335                                                    GFP_KERNEL);
7336                 if (unlikely(!phba->sli4_hba.vfi_bmask)) {
7337                         rc = -ENOMEM;
7338                         goto free_xri_ids;
7339                 }
7340                 phba->sli4_hba.vfi_ids = kcalloc(count, sizeof(uint16_t),
7341                                                  GFP_KERNEL);
7342                 if (unlikely(!phba->sli4_hba.vfi_ids)) {
7343                         rc = -ENOMEM;
7344                         goto free_vfi_bmask;
7345                 }
7346
7347                 for (i = 0; i < count; i++)
7348                         phba->sli4_hba.vfi_ids[i] = base + i;
7349
7350                 /*
7351                  * Mark all resources ready.  An HBA reset doesn't need
7352                  * to reset the initialization.
7353                  */
7354                 bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags,
7355                        LPFC_IDX_RSRC_RDY);
7356                 return 0;
7357         }
7358
7359  free_vfi_bmask:
7360         kfree(phba->sli4_hba.vfi_bmask);
7361         phba->sli4_hba.vfi_bmask = NULL;
7362  free_xri_ids:
7363         kfree(phba->sli4_hba.xri_ids);
7364         phba->sli4_hba.xri_ids = NULL;
7365  free_xri_bmask:
7366         kfree(phba->sli4_hba.xri_bmask);
7367         phba->sli4_hba.xri_bmask = NULL;
7368  free_vpi_ids:
7369         kfree(phba->vpi_ids);
7370         phba->vpi_ids = NULL;
7371  free_vpi_bmask:
7372         kfree(phba->vpi_bmask);
7373         phba->vpi_bmask = NULL;
7374  free_rpi_ids:
7375         kfree(phba->sli4_hba.rpi_ids);
7376         phba->sli4_hba.rpi_ids = NULL;
7377  free_rpi_bmask:
7378         kfree(phba->sli4_hba.rpi_bmask);
7379         phba->sli4_hba.rpi_bmask = NULL;
7380  err_exit:
7381         return rc;
7382 }
7383
7384 /**
7385  * lpfc_sli4_dealloc_resource_identifiers - Deallocate all SLI4 resource extents.
7386  * @phba: Pointer to HBA context object.
7387  *
7388  * This function allocates the number of elements for the specified
7389  * resource type.
7390  **/
7391 int
7392 lpfc_sli4_dealloc_resource_identifiers(struct lpfc_hba *phba)
7393 {
7394         if (phba->sli4_hba.extents_in_use) {
7395                 lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VPI);
7396                 lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_RPI);
7397                 lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_XRI);
7398                 lpfc_sli4_dealloc_extent(phba, LPFC_RSC_TYPE_FCOE_VFI);
7399         } else {
7400                 kfree(phba->vpi_bmask);
7401                 phba->sli4_hba.max_cfg_param.vpi_used = 0;
7402                 kfree(phba->vpi_ids);
7403                 bf_set(lpfc_vpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7404                 kfree(phba->sli4_hba.xri_bmask);
7405                 kfree(phba->sli4_hba.xri_ids);
7406                 kfree(phba->sli4_hba.vfi_bmask);
7407                 kfree(phba->sli4_hba.vfi_ids);
7408                 bf_set(lpfc_vfi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7409                 bf_set(lpfc_idx_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
7410         }
7411
7412         return 0;
7413 }
7414
7415 /**
7416  * lpfc_sli4_get_allocated_extnts - Get the port's allocated extents.
7417  * @phba: Pointer to HBA context object.
7418  * @type: The resource extent type.
7419  * @extnt_cnt: buffer to hold port extent count response
7420  * @extnt_size: buffer to hold port extent size response.
7421  *
7422  * This function calls the port to read the host allocated extents
7423  * for a particular type.
7424  **/
7425 int
7426 lpfc_sli4_get_allocated_extnts(struct lpfc_hba *phba, uint16_t type,
7427                                uint16_t *extnt_cnt, uint16_t *extnt_size)
7428 {
7429         bool emb;
7430         int rc = 0;
7431         uint16_t curr_blks = 0;
7432         uint32_t req_len, emb_len;
7433         uint32_t alloc_len, mbox_tmo;
7434         struct list_head *blk_list_head;
7435         struct lpfc_rsrc_blks *rsrc_blk;
7436         LPFC_MBOXQ_t *mbox;
7437         void *virtaddr = NULL;
7438         struct lpfc_mbx_nembed_rsrc_extent *n_rsrc;
7439         struct lpfc_mbx_alloc_rsrc_extents *rsrc_ext;
7440         union  lpfc_sli4_cfg_shdr *shdr;
7441
7442         switch (type) {
7443         case LPFC_RSC_TYPE_FCOE_VPI:
7444                 blk_list_head = &phba->lpfc_vpi_blk_list;
7445                 break;
7446         case LPFC_RSC_TYPE_FCOE_XRI:
7447                 blk_list_head = &phba->sli4_hba.lpfc_xri_blk_list;
7448                 break;
7449         case LPFC_RSC_TYPE_FCOE_VFI:
7450                 blk_list_head = &phba->sli4_hba.lpfc_vfi_blk_list;
7451                 break;
7452         case LPFC_RSC_TYPE_FCOE_RPI:
7453                 blk_list_head = &phba->sli4_hba.lpfc_rpi_blk_list;
7454                 break;
7455         default:
7456                 return -EIO;
7457         }
7458
7459         /* Count the number of extents currently allocatd for this type. */
7460         list_for_each_entry(rsrc_blk, blk_list_head, list) {
7461                 if (curr_blks == 0) {
7462                         /*
7463                          * The GET_ALLOCATED mailbox does not return the size,
7464                          * just the count.  The size should be just the size
7465                          * stored in the current allocated block and all sizes
7466                          * for an extent type are the same so set the return
7467                          * value now.
7468                          */
7469                         *extnt_size = rsrc_blk->rsrc_size;
7470                 }
7471                 curr_blks++;
7472         }
7473
7474         /*
7475          * Calculate the size of an embedded mailbox.  The uint32_t
7476          * accounts for extents-specific word.
7477          */
7478         emb_len = sizeof(MAILBOX_t) - sizeof(struct mbox_header) -
7479                 sizeof(uint32_t);
7480
7481         /*
7482          * Presume the allocation and response will fit into an embedded
7483          * mailbox.  If not true, reconfigure to a non-embedded mailbox.
7484          */
7485         emb = LPFC_SLI4_MBX_EMBED;
7486         req_len = emb_len;
7487         if (req_len > emb_len) {
7488                 req_len = curr_blks * sizeof(uint16_t) +
7489                         sizeof(union lpfc_sli4_cfg_shdr) +
7490                         sizeof(uint32_t);
7491                 emb = LPFC_SLI4_MBX_NEMBED;
7492         }
7493
7494         mbox = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7495         if (!mbox)
7496                 return -ENOMEM;
7497         memset(mbox, 0, sizeof(LPFC_MBOXQ_t));
7498
7499         alloc_len = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7500                                      LPFC_MBOX_OPCODE_GET_ALLOC_RSRC_EXTENT,
7501                                      req_len, emb);
7502         if (alloc_len < req_len) {
7503                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7504                         "2983 Allocated DMA memory size (x%x) is "
7505                         "less than the requested DMA memory "
7506                         "size (x%x)\n", alloc_len, req_len);
7507                 rc = -ENOMEM;
7508                 goto err_exit;
7509         }
7510         rc = lpfc_sli4_mbox_rsrc_extent(phba, mbox, curr_blks, type, emb);
7511         if (unlikely(rc)) {
7512                 rc = -EIO;
7513                 goto err_exit;
7514         }
7515
7516         if (!phba->sli4_hba.intr_enable)
7517                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
7518         else {
7519                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
7520                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
7521         }
7522
7523         if (unlikely(rc)) {
7524                 rc = -EIO;
7525                 goto err_exit;
7526         }
7527
7528         /*
7529          * Figure out where the response is located.  Then get local pointers
7530          * to the response data.  The port does not guarantee to respond to
7531          * all extents counts request so update the local variable with the
7532          * allocated count from the port.
7533          */
7534         if (emb == LPFC_SLI4_MBX_EMBED) {
7535                 rsrc_ext = &mbox->u.mqe.un.alloc_rsrc_extents;
7536                 shdr = &rsrc_ext->header.cfg_shdr;
7537                 *extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, &rsrc_ext->u.rsp);
7538         } else {
7539                 virtaddr = mbox->sge_array->addr[0];
7540                 n_rsrc = (struct lpfc_mbx_nembed_rsrc_extent *) virtaddr;
7541                 shdr = &n_rsrc->cfg_shdr;
7542                 *extnt_cnt = bf_get(lpfc_mbx_rsrc_cnt, n_rsrc);
7543         }
7544
7545         if (bf_get(lpfc_mbox_hdr_status, &shdr->response)) {
7546                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7547                         "2984 Failed to read allocated resources "
7548                         "for type %d - Status 0x%x Add'l Status 0x%x.\n",
7549                         type,
7550                         bf_get(lpfc_mbox_hdr_status, &shdr->response),
7551                         bf_get(lpfc_mbox_hdr_add_status, &shdr->response));
7552                 rc = -EIO;
7553                 goto err_exit;
7554         }
7555  err_exit:
7556         lpfc_sli4_mbox_cmd_free(phba, mbox);
7557         return rc;
7558 }
7559
7560 /**
7561  * lpfc_sli4_repost_sgl_list - Repost the buffers sgl pages as block
7562  * @phba: pointer to lpfc hba data structure.
7563  * @sgl_list: linked link of sgl buffers to post
7564  * @cnt: number of linked list buffers
7565  *
7566  * This routine walks the list of buffers that have been allocated and
7567  * repost them to the port by using SGL block post. This is needed after a
7568  * pci_function_reset/warm_start or start. It attempts to construct blocks
7569  * of buffer sgls which contains contiguous xris and uses the non-embedded
7570  * SGL block post mailbox commands to post them to the port. For single
7571  * buffer sgl with non-contiguous xri, if any, it shall use embedded SGL post
7572  * mailbox command for posting.
7573  *
7574  * Returns: 0 = success, non-zero failure.
7575  **/
7576 static int
7577 lpfc_sli4_repost_sgl_list(struct lpfc_hba *phba,
7578                           struct list_head *sgl_list, int cnt)
7579 {
7580         struct lpfc_sglq *sglq_entry = NULL;
7581         struct lpfc_sglq *sglq_entry_next = NULL;
7582         struct lpfc_sglq *sglq_entry_first = NULL;
7583         int status = 0, total_cnt;
7584         int post_cnt = 0, num_posted = 0, block_cnt = 0;
7585         int last_xritag = NO_XRI;
7586         LIST_HEAD(prep_sgl_list);
7587         LIST_HEAD(blck_sgl_list);
7588         LIST_HEAD(allc_sgl_list);
7589         LIST_HEAD(post_sgl_list);
7590         LIST_HEAD(free_sgl_list);
7591
7592         spin_lock_irq(&phba->hbalock);
7593         spin_lock(&phba->sli4_hba.sgl_list_lock);
7594         list_splice_init(sgl_list, &allc_sgl_list);
7595         spin_unlock(&phba->sli4_hba.sgl_list_lock);
7596         spin_unlock_irq(&phba->hbalock);
7597
7598         total_cnt = cnt;
7599         list_for_each_entry_safe(sglq_entry, sglq_entry_next,
7600                                  &allc_sgl_list, list) {
7601                 list_del_init(&sglq_entry->list);
7602                 block_cnt++;
7603                 if ((last_xritag != NO_XRI) &&
7604                     (sglq_entry->sli4_xritag != last_xritag + 1)) {
7605                         /* a hole in xri block, form a sgl posting block */
7606                         list_splice_init(&prep_sgl_list, &blck_sgl_list);
7607                         post_cnt = block_cnt - 1;
7608                         /* prepare list for next posting block */
7609                         list_add_tail(&sglq_entry->list, &prep_sgl_list);
7610                         block_cnt = 1;
7611                 } else {
7612                         /* prepare list for next posting block */
7613                         list_add_tail(&sglq_entry->list, &prep_sgl_list);
7614                         /* enough sgls for non-embed sgl mbox command */
7615                         if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
7616                                 list_splice_init(&prep_sgl_list,
7617                                                  &blck_sgl_list);
7618                                 post_cnt = block_cnt;
7619                                 block_cnt = 0;
7620                         }
7621                 }
7622                 num_posted++;
7623
7624                 /* keep track of last sgl's xritag */
7625                 last_xritag = sglq_entry->sli4_xritag;
7626
7627                 /* end of repost sgl list condition for buffers */
7628                 if (num_posted == total_cnt) {
7629                         if (post_cnt == 0) {
7630                                 list_splice_init(&prep_sgl_list,
7631                                                  &blck_sgl_list);
7632                                 post_cnt = block_cnt;
7633                         } else if (block_cnt == 1) {
7634                                 status = lpfc_sli4_post_sgl(phba,
7635                                                 sglq_entry->phys, 0,
7636                                                 sglq_entry->sli4_xritag);
7637                                 if (!status) {
7638                                         /* successful, put sgl to posted list */
7639                                         list_add_tail(&sglq_entry->list,
7640                                                       &post_sgl_list);
7641                                 } else {
7642                                         /* Failure, put sgl to free list */
7643                                         lpfc_printf_log(phba, KERN_WARNING,
7644                                                 LOG_SLI,
7645                                                 "3159 Failed to post "
7646                                                 "sgl, xritag:x%x\n",
7647                                                 sglq_entry->sli4_xritag);
7648                                         list_add_tail(&sglq_entry->list,
7649                                                       &free_sgl_list);
7650                                         total_cnt--;
7651                                 }
7652                         }
7653                 }
7654
7655                 /* continue until a nembed page worth of sgls */
7656                 if (post_cnt == 0)
7657                         continue;
7658
7659                 /* post the buffer list sgls as a block */
7660                 status = lpfc_sli4_post_sgl_list(phba, &blck_sgl_list,
7661                                                  post_cnt);
7662
7663                 if (!status) {
7664                         /* success, put sgl list to posted sgl list */
7665                         list_splice_init(&blck_sgl_list, &post_sgl_list);
7666                 } else {
7667                         /* Failure, put sgl list to free sgl list */
7668                         sglq_entry_first = list_first_entry(&blck_sgl_list,
7669                                                             struct lpfc_sglq,
7670                                                             list);
7671                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
7672                                         "3160 Failed to post sgl-list, "
7673                                         "xritag:x%x-x%x\n",
7674                                         sglq_entry_first->sli4_xritag,
7675                                         (sglq_entry_first->sli4_xritag +
7676                                          post_cnt - 1));
7677                         list_splice_init(&blck_sgl_list, &free_sgl_list);
7678                         total_cnt -= post_cnt;
7679                 }
7680
7681                 /* don't reset xirtag due to hole in xri block */
7682                 if (block_cnt == 0)
7683                         last_xritag = NO_XRI;
7684
7685                 /* reset sgl post count for next round of posting */
7686                 post_cnt = 0;
7687         }
7688
7689         /* free the sgls failed to post */
7690         lpfc_free_sgl_list(phba, &free_sgl_list);
7691
7692         /* push sgls posted to the available list */
7693         if (!list_empty(&post_sgl_list)) {
7694                 spin_lock_irq(&phba->hbalock);
7695                 spin_lock(&phba->sli4_hba.sgl_list_lock);
7696                 list_splice_init(&post_sgl_list, sgl_list);
7697                 spin_unlock(&phba->sli4_hba.sgl_list_lock);
7698                 spin_unlock_irq(&phba->hbalock);
7699         } else {
7700                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7701                                 "3161 Failure to post sgl to port,status %x "
7702                                 "blkcnt %d totalcnt %d postcnt %d\n",
7703                                 status, block_cnt, total_cnt, post_cnt);
7704                 return -EIO;
7705         }
7706
7707         /* return the number of XRIs actually posted */
7708         return total_cnt;
7709 }
7710
7711 /**
7712  * lpfc_sli4_repost_io_sgl_list - Repost all the allocated nvme buffer sgls
7713  * @phba: pointer to lpfc hba data structure.
7714  *
7715  * This routine walks the list of nvme buffers that have been allocated and
7716  * repost them to the port by using SGL block post. This is needed after a
7717  * pci_function_reset/warm_start or start. The lpfc_hba_down_post_s4 routine
7718  * is responsible for moving all nvme buffers on the lpfc_abts_nvme_sgl_list
7719  * to the lpfc_io_buf_list. If the repost fails, reject all nvme buffers.
7720  *
7721  * Returns: 0 = success, non-zero failure.
7722  **/
7723 static int
7724 lpfc_sli4_repost_io_sgl_list(struct lpfc_hba *phba)
7725 {
7726         LIST_HEAD(post_nblist);
7727         int num_posted, rc = 0;
7728
7729         /* get all NVME buffers need to repost to a local list */
7730         lpfc_io_buf_flush(phba, &post_nblist);
7731
7732         /* post the list of nvme buffer sgls to port if available */
7733         if (!list_empty(&post_nblist)) {
7734                 num_posted = lpfc_sli4_post_io_sgl_list(
7735                         phba, &post_nblist, phba->sli4_hba.io_xri_cnt);
7736                 /* failed to post any nvme buffer, return error */
7737                 if (num_posted == 0)
7738                         rc = -EIO;
7739         }
7740         return rc;
7741 }
7742
7743 static void
7744 lpfc_set_host_data(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
7745 {
7746         uint32_t len;
7747
7748         len = sizeof(struct lpfc_mbx_set_host_data) -
7749                 sizeof(struct lpfc_sli4_cfg_mhdr);
7750         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
7751                          LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
7752                          LPFC_SLI4_MBX_EMBED);
7753
7754         mbox->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_OS_DRIVER_VERSION;
7755         mbox->u.mqe.un.set_host_data.param_len =
7756                                         LPFC_HOST_OS_DRIVER_VERSION_SIZE;
7757         snprintf(mbox->u.mqe.un.set_host_data.un.data,
7758                  LPFC_HOST_OS_DRIVER_VERSION_SIZE,
7759                  "Linux %s v"LPFC_DRIVER_VERSION,
7760                  test_bit(HBA_FCOE_MODE, &phba->hba_flag) ? "FCoE" : "FC");
7761 }
7762
7763 int
7764 lpfc_post_rq_buffer(struct lpfc_hba *phba, struct lpfc_queue *hrq,
7765                     struct lpfc_queue *drq, int count, int idx)
7766 {
7767         int rc, i;
7768         struct lpfc_rqe hrqe;
7769         struct lpfc_rqe drqe;
7770         struct lpfc_rqb *rqbp;
7771         unsigned long flags;
7772         struct rqb_dmabuf *rqb_buffer;
7773         LIST_HEAD(rqb_buf_list);
7774
7775         rqbp = hrq->rqbp;
7776         for (i = 0; i < count; i++) {
7777                 spin_lock_irqsave(&phba->hbalock, flags);
7778                 /* IF RQ is already full, don't bother */
7779                 if (rqbp->buffer_count + i >= rqbp->entry_count - 1) {
7780                         spin_unlock_irqrestore(&phba->hbalock, flags);
7781                         break;
7782                 }
7783                 spin_unlock_irqrestore(&phba->hbalock, flags);
7784
7785                 rqb_buffer = rqbp->rqb_alloc_buffer(phba);
7786                 if (!rqb_buffer)
7787                         break;
7788                 rqb_buffer->hrq = hrq;
7789                 rqb_buffer->drq = drq;
7790                 rqb_buffer->idx = idx;
7791                 list_add_tail(&rqb_buffer->hbuf.list, &rqb_buf_list);
7792         }
7793
7794         spin_lock_irqsave(&phba->hbalock, flags);
7795         while (!list_empty(&rqb_buf_list)) {
7796                 list_remove_head(&rqb_buf_list, rqb_buffer, struct rqb_dmabuf,
7797                                  hbuf.list);
7798
7799                 hrqe.address_lo = putPaddrLow(rqb_buffer->hbuf.phys);
7800                 hrqe.address_hi = putPaddrHigh(rqb_buffer->hbuf.phys);
7801                 drqe.address_lo = putPaddrLow(rqb_buffer->dbuf.phys);
7802                 drqe.address_hi = putPaddrHigh(rqb_buffer->dbuf.phys);
7803                 rc = lpfc_sli4_rq_put(hrq, drq, &hrqe, &drqe);
7804                 if (rc < 0) {
7805                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
7806                                         "6421 Cannot post to HRQ %d: %x %x %x "
7807                                         "DRQ %x %x\n",
7808                                         hrq->queue_id,
7809                                         hrq->host_index,
7810                                         hrq->hba_index,
7811                                         hrq->entry_count,
7812                                         drq->host_index,
7813                                         drq->hba_index);
7814                         rqbp->rqb_free_buffer(phba, rqb_buffer);
7815                 } else {
7816                         list_add_tail(&rqb_buffer->hbuf.list,
7817                                       &rqbp->rqb_buffer_list);
7818                         rqbp->buffer_count++;
7819                 }
7820         }
7821         spin_unlock_irqrestore(&phba->hbalock, flags);
7822         return 1;
7823 }
7824
7825 static void
7826 lpfc_mbx_cmpl_read_lds_params(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7827 {
7828         union lpfc_sli4_cfg_shdr *shdr;
7829         u32 shdr_status, shdr_add_status;
7830
7831         shdr = (union lpfc_sli4_cfg_shdr *)
7832                 &pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7833         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7834         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7835         if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7836                 lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT | LOG_MBOX,
7837                                 "4622 SET_FEATURE (x%x) mbox failed, "
7838                                 "status x%x add_status x%x, mbx status x%x\n",
7839                                 LPFC_SET_LD_SIGNAL, shdr_status,
7840                                 shdr_add_status, pmb->u.mb.mbxStatus);
7841                 phba->degrade_activate_threshold = 0;
7842                 phba->degrade_deactivate_threshold = 0;
7843                 phba->fec_degrade_interval = 0;
7844                 goto out;
7845         }
7846
7847         phba->degrade_activate_threshold = pmb->u.mqe.un.set_feature.word7;
7848         phba->degrade_deactivate_threshold = pmb->u.mqe.un.set_feature.word8;
7849         phba->fec_degrade_interval = pmb->u.mqe.un.set_feature.word10;
7850
7851         lpfc_printf_log(phba, KERN_INFO, LOG_LDS_EVENT,
7852                         "4624 Success: da x%x dd x%x interval x%x\n",
7853                         phba->degrade_activate_threshold,
7854                         phba->degrade_deactivate_threshold,
7855                         phba->fec_degrade_interval);
7856 out:
7857         mempool_free(pmb, phba->mbox_mem_pool);
7858 }
7859
7860 int
7861 lpfc_read_lds_params(struct lpfc_hba *phba)
7862 {
7863         LPFC_MBOXQ_t *mboxq;
7864         int rc;
7865
7866         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7867         if (!mboxq)
7868                 return -ENOMEM;
7869
7870         lpfc_set_features(phba, mboxq, LPFC_SET_LD_SIGNAL);
7871         mboxq->vport = phba->pport;
7872         mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_lds_params;
7873         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7874         if (rc == MBX_NOT_FINISHED) {
7875                 mempool_free(mboxq, phba->mbox_mem_pool);
7876                 return -EIO;
7877         }
7878         return 0;
7879 }
7880
7881 static void
7882 lpfc_mbx_cmpl_cgn_set_ftrs(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmb)
7883 {
7884         struct lpfc_vport *vport = pmb->vport;
7885         union lpfc_sli4_cfg_shdr *shdr;
7886         u32 shdr_status, shdr_add_status;
7887         u32 sig, acqe;
7888
7889         /* Two outcomes. (1) Set featurs was successul and EDC negotiation
7890          * is done. (2) Mailbox failed and send FPIN support only.
7891          */
7892         shdr = (union lpfc_sli4_cfg_shdr *)
7893                 &pmb->u.mqe.un.sli4_config.header.cfg_shdr;
7894         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
7895         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
7896         if (shdr_status || shdr_add_status || pmb->u.mb.mbxStatus) {
7897                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
7898                                 "2516 CGN SET_FEATURE mbox failed with "
7899                                 "status x%x add_status x%x, mbx status x%x "
7900                                 "Reset Congestion to FPINs only\n",
7901                                 shdr_status, shdr_add_status,
7902                                 pmb->u.mb.mbxStatus);
7903                 /* If there is a mbox error, move on to RDF */
7904                 phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7905                 phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7906                 goto out;
7907         }
7908
7909         /* Zero out Congestion Signal ACQE counter */
7910         phba->cgn_acqe_cnt = 0;
7911
7912         acqe = bf_get(lpfc_mbx_set_feature_CGN_acqe_freq,
7913                       &pmb->u.mqe.un.set_feature);
7914         sig = bf_get(lpfc_mbx_set_feature_CGN_warn_freq,
7915                      &pmb->u.mqe.un.set_feature);
7916         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7917                         "4620 SET_FEATURES Success: Freq: %ds %dms "
7918                         " Reg: x%x x%x\n", acqe, sig,
7919                         phba->cgn_reg_signal, phba->cgn_reg_fpin);
7920 out:
7921         mempool_free(pmb, phba->mbox_mem_pool);
7922
7923         /* Register for FPIN events from the fabric now that the
7924          * EDC common_set_features has completed.
7925          */
7926         lpfc_issue_els_rdf(vport, 0);
7927 }
7928
7929 int
7930 lpfc_config_cgn_signal(struct lpfc_hba *phba)
7931 {
7932         LPFC_MBOXQ_t *mboxq;
7933         u32 rc;
7934
7935         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
7936         if (!mboxq)
7937                 goto out_rdf;
7938
7939         lpfc_set_features(phba, mboxq, LPFC_SET_CGN_SIGNAL);
7940         mboxq->vport = phba->pport;
7941         mboxq->mbox_cmpl = lpfc_mbx_cmpl_cgn_set_ftrs;
7942
7943         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
7944                         "4621 SET_FEATURES: FREQ sig x%x acqe x%x: "
7945                         "Reg: x%x x%x\n",
7946                         phba->cgn_sig_freq, lpfc_acqe_cgn_frequency,
7947                         phba->cgn_reg_signal, phba->cgn_reg_fpin);
7948
7949         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
7950         if (rc == MBX_NOT_FINISHED)
7951                 goto out;
7952         return 0;
7953
7954 out:
7955         mempool_free(mboxq, phba->mbox_mem_pool);
7956 out_rdf:
7957         /* If there is a mbox error, move on to RDF */
7958         phba->cgn_reg_fpin = LPFC_CGN_FPIN_WARN | LPFC_CGN_FPIN_ALARM;
7959         phba->cgn_reg_signal = EDC_CG_SIG_NOTSUPPORTED;
7960         lpfc_issue_els_rdf(phba->pport, 0);
7961         return -EIO;
7962 }
7963
7964 /**
7965  * lpfc_init_idle_stat_hb - Initialize idle_stat tracking
7966  * @phba: pointer to lpfc hba data structure.
7967  *
7968  * This routine initializes the per-eq idle_stat to dynamically dictate
7969  * polling decisions.
7970  *
7971  * Return codes:
7972  *   None
7973  **/
7974 static void lpfc_init_idle_stat_hb(struct lpfc_hba *phba)
7975 {
7976         int i;
7977         struct lpfc_sli4_hdw_queue *hdwq;
7978         struct lpfc_queue *eq;
7979         struct lpfc_idle_stat *idle_stat;
7980         u64 wall;
7981
7982         for_each_present_cpu(i) {
7983                 hdwq = &phba->sli4_hba.hdwq[phba->sli4_hba.cpu_map[i].hdwq];
7984                 eq = hdwq->hba_eq;
7985
7986                 /* Skip if we've already handled this eq's primary CPU */
7987                 if (eq->chann != i)
7988                         continue;
7989
7990                 idle_stat = &phba->sli4_hba.idle_stat[i];
7991
7992                 idle_stat->prev_idle = get_cpu_idle_time(i, &wall, 1);
7993                 idle_stat->prev_wall = wall;
7994
7995                 if (phba->nvmet_support ||
7996                     phba->cmf_active_mode != LPFC_CFG_OFF ||
7997                     phba->intr_type != MSIX)
7998                         eq->poll_mode = LPFC_QUEUE_WORK;
7999                 else
8000                         eq->poll_mode = LPFC_THREADED_IRQ;
8001         }
8002
8003         if (!phba->nvmet_support && phba->intr_type == MSIX)
8004                 schedule_delayed_work(&phba->idle_stat_delay_work,
8005                                       msecs_to_jiffies(LPFC_IDLE_STAT_DELAY));
8006 }
8007
8008 static void lpfc_sli4_dip(struct lpfc_hba *phba)
8009 {
8010         uint32_t if_type;
8011
8012         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
8013         if (if_type == LPFC_SLI_INTF_IF_TYPE_2 ||
8014             if_type == LPFC_SLI_INTF_IF_TYPE_6) {
8015                 struct lpfc_register reg_data;
8016
8017                 if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
8018                                &reg_data.word0))
8019                         return;
8020
8021                 if (bf_get(lpfc_sliport_status_dip, &reg_data))
8022                         lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8023                                         "2904 Firmware Dump Image Present"
8024                                         " on Adapter");
8025         }
8026 }
8027
8028 /**
8029  * lpfc_rx_monitor_create_ring - Initialize ring buffer for rx_monitor
8030  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8031  * @entries: Number of rx_info_entry objects to allocate in ring
8032  *
8033  * Return:
8034  * 0 - Success
8035  * ENOMEM - Failure to kmalloc
8036  **/
8037 int lpfc_rx_monitor_create_ring(struct lpfc_rx_info_monitor *rx_monitor,
8038                                 u32 entries)
8039 {
8040         rx_monitor->ring = kmalloc_array(entries, sizeof(struct rx_info_entry),
8041                                          GFP_KERNEL);
8042         if (!rx_monitor->ring)
8043                 return -ENOMEM;
8044
8045         rx_monitor->head_idx = 0;
8046         rx_monitor->tail_idx = 0;
8047         spin_lock_init(&rx_monitor->lock);
8048         rx_monitor->entries = entries;
8049
8050         return 0;
8051 }
8052
8053 /**
8054  * lpfc_rx_monitor_destroy_ring - Free ring buffer for rx_monitor
8055  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8056  *
8057  * Called after cancellation of cmf_timer.
8058  **/
8059 void lpfc_rx_monitor_destroy_ring(struct lpfc_rx_info_monitor *rx_monitor)
8060 {
8061         kfree(rx_monitor->ring);
8062         rx_monitor->ring = NULL;
8063         rx_monitor->entries = 0;
8064         rx_monitor->head_idx = 0;
8065         rx_monitor->tail_idx = 0;
8066 }
8067
8068 /**
8069  * lpfc_rx_monitor_record - Insert an entry into rx_monitor's ring
8070  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8071  * @entry: Pointer to rx_info_entry
8072  *
8073  * Used to insert an rx_info_entry into rx_monitor's ring.  Note that this is a
8074  * deep copy of rx_info_entry not a shallow copy of the rx_info_entry ptr.
8075  *
8076  * This is called from lpfc_cmf_timer, which is in timer/softirq context.
8077  *
8078  * In cases of old data overflow, we do a best effort of FIFO order.
8079  **/
8080 void lpfc_rx_monitor_record(struct lpfc_rx_info_monitor *rx_monitor,
8081                             struct rx_info_entry *entry)
8082 {
8083         struct rx_info_entry *ring = rx_monitor->ring;
8084         u32 *head_idx = &rx_monitor->head_idx;
8085         u32 *tail_idx = &rx_monitor->tail_idx;
8086         spinlock_t *ring_lock = &rx_monitor->lock;
8087         u32 ring_size = rx_monitor->entries;
8088
8089         spin_lock(ring_lock);
8090         memcpy(&ring[*tail_idx], entry, sizeof(*entry));
8091         *tail_idx = (*tail_idx + 1) % ring_size;
8092
8093         /* Best effort of FIFO saved data */
8094         if (*tail_idx == *head_idx)
8095                 *head_idx = (*head_idx + 1) % ring_size;
8096
8097         spin_unlock(ring_lock);
8098 }
8099
8100 /**
8101  * lpfc_rx_monitor_report - Read out rx_monitor's ring
8102  * @phba: Pointer to lpfc_hba object
8103  * @rx_monitor: Pointer to lpfc_rx_info_monitor object
8104  * @buf: Pointer to char buffer that will contain rx monitor info data
8105  * @buf_len: Length buf including null char
8106  * @max_read_entries: Maximum number of entries to read out of ring
8107  *
8108  * Used to dump/read what's in rx_monitor's ring buffer.
8109  *
8110  * If buf is NULL || buf_len == 0, then it is implied that we want to log the
8111  * information to kmsg instead of filling out buf.
8112  *
8113  * Return:
8114  * Number of entries read out of the ring
8115  **/
8116 u32 lpfc_rx_monitor_report(struct lpfc_hba *phba,
8117                            struct lpfc_rx_info_monitor *rx_monitor, char *buf,
8118                            u32 buf_len, u32 max_read_entries)
8119 {
8120         struct rx_info_entry *ring = rx_monitor->ring;
8121         struct rx_info_entry *entry;
8122         u32 *head_idx = &rx_monitor->head_idx;
8123         u32 *tail_idx = &rx_monitor->tail_idx;
8124         spinlock_t *ring_lock = &rx_monitor->lock;
8125         u32 ring_size = rx_monitor->entries;
8126         u32 cnt = 0;
8127         char tmp[DBG_LOG_STR_SZ] = {0};
8128         bool log_to_kmsg = (!buf || !buf_len) ? true : false;
8129
8130         if (!log_to_kmsg) {
8131                 /* clear the buffer to be sure */
8132                 memset(buf, 0, buf_len);
8133
8134                 scnprintf(buf, buf_len, "\t%-16s%-16s%-16s%-16s%-8s%-8s%-8s"
8135                                         "%-8s%-8s%-8s%-16s\n",
8136                                         "MaxBPI", "Tot_Data_CMF",
8137                                         "Tot_Data_Cmd", "Tot_Data_Cmpl",
8138                                         "Lat(us)", "Avg_IO", "Max_IO", "Bsy",
8139                                         "IO_cnt", "Info", "BWutil(ms)");
8140         }
8141
8142         /* Needs to be _irq because record is called from timer interrupt
8143          * context
8144          */
8145         spin_lock_irq(ring_lock);
8146         while (*head_idx != *tail_idx) {
8147                 entry = &ring[*head_idx];
8148
8149                 /* Read out this entry's data. */
8150                 if (!log_to_kmsg) {
8151                         /* If !log_to_kmsg, then store to buf. */
8152                         scnprintf(tmp, sizeof(tmp),
8153                                   "%03d:\t%-16llu%-16llu%-16llu%-16llu%-8llu"
8154                                   "%-8llu%-8llu%-8u%-8u%-8u%u(%u)\n",
8155                                   *head_idx, entry->max_bytes_per_interval,
8156                                   entry->cmf_bytes, entry->total_bytes,
8157                                   entry->rcv_bytes, entry->avg_io_latency,
8158                                   entry->avg_io_size, entry->max_read_cnt,
8159                                   entry->cmf_busy, entry->io_cnt,
8160                                   entry->cmf_info, entry->timer_utilization,
8161                                   entry->timer_interval);
8162
8163                         /* Check for buffer overflow */
8164                         if ((strlen(buf) + strlen(tmp)) >= buf_len)
8165                                 break;
8166
8167                         /* Append entry's data to buffer */
8168                         strlcat(buf, tmp, buf_len);
8169                 } else {
8170                         lpfc_printf_log(phba, KERN_INFO, LOG_CGN_MGMT,
8171                                         "4410 %02u: MBPI %llu Xmit %llu "
8172                                         "Cmpl %llu Lat %llu ASz %llu Info %02u "
8173                                         "BWUtil %u Int %u slot %u\n",
8174                                         cnt, entry->max_bytes_per_interval,
8175                                         entry->total_bytes, entry->rcv_bytes,
8176                                         entry->avg_io_latency,
8177                                         entry->avg_io_size, entry->cmf_info,
8178                                         entry->timer_utilization,
8179                                         entry->timer_interval, *head_idx);
8180                 }
8181
8182                 *head_idx = (*head_idx + 1) % ring_size;
8183
8184                 /* Don't feed more than max_read_entries */
8185                 cnt++;
8186                 if (cnt >= max_read_entries)
8187                         break;
8188         }
8189         spin_unlock_irq(ring_lock);
8190
8191         return cnt;
8192 }
8193
8194 /**
8195  * lpfc_cmf_setup - Initialize idle_stat tracking
8196  * @phba: Pointer to HBA context object.
8197  *
8198  * This is called from HBA setup during driver load or when the HBA
8199  * comes online. this does all the initialization to support CMF and MI.
8200  **/
8201 static int
8202 lpfc_cmf_setup(struct lpfc_hba *phba)
8203 {
8204         LPFC_MBOXQ_t *mboxq;
8205         struct lpfc_dmabuf *mp;
8206         struct lpfc_pc_sli4_params *sli4_params;
8207         int rc, cmf, mi_ver;
8208
8209         rc = lpfc_sli4_refresh_params(phba);
8210         if (unlikely(rc))
8211                 return rc;
8212
8213         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8214         if (!mboxq)
8215                 return -ENOMEM;
8216
8217         sli4_params = &phba->sli4_hba.pc_sli4_params;
8218
8219         /* Always try to enable MI feature if we can */
8220         if (sli4_params->mi_ver) {
8221                 lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_MI);
8222                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8223                 mi_ver = bf_get(lpfc_mbx_set_feature_mi,
8224                                  &mboxq->u.mqe.un.set_feature);
8225
8226                 if (rc == MBX_SUCCESS) {
8227                         if (mi_ver) {
8228                                 lpfc_printf_log(phba,
8229                                                 KERN_WARNING, LOG_CGN_MGMT,
8230                                                 "6215 MI is enabled\n");
8231                                 sli4_params->mi_ver = mi_ver;
8232                         } else {
8233                                 lpfc_printf_log(phba,
8234                                                 KERN_WARNING, LOG_CGN_MGMT,
8235                                                 "6338 MI is disabled\n");
8236                                 sli4_params->mi_ver = 0;
8237                         }
8238                 } else {
8239                         /* mi_ver is already set from GET_SLI4_PARAMETERS */
8240                         lpfc_printf_log(phba, KERN_INFO,
8241                                         LOG_CGN_MGMT | LOG_INIT,
8242                                         "6245 Enable MI Mailbox x%x (x%x/x%x) "
8243                                         "failed, rc:x%x mi:x%x\n",
8244                                         bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8245                                         lpfc_sli_config_mbox_subsys_get
8246                                                 (phba, mboxq),
8247                                         lpfc_sli_config_mbox_opcode_get
8248                                                 (phba, mboxq),
8249                                         rc, sli4_params->mi_ver);
8250                 }
8251         } else {
8252                 lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8253                                 "6217 MI is disabled\n");
8254         }
8255
8256         /* Ensure FDMI is enabled for MI if enable_mi is set */
8257         if (sli4_params->mi_ver)
8258                 phba->cfg_fdmi_on = LPFC_FDMI_SUPPORT;
8259
8260         /* Always try to enable CMF feature if we can */
8261         if (sli4_params->cmf) {
8262                 lpfc_set_features(phba, mboxq, LPFC_SET_ENABLE_CMF);
8263                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8264                 cmf = bf_get(lpfc_mbx_set_feature_cmf,
8265                              &mboxq->u.mqe.un.set_feature);
8266                 if (rc == MBX_SUCCESS && cmf) {
8267                         lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8268                                         "6218 CMF is enabled: mode %d\n",
8269                                         phba->cmf_active_mode);
8270                 } else {
8271                         lpfc_printf_log(phba, KERN_WARNING,
8272                                         LOG_CGN_MGMT | LOG_INIT,
8273                                         "6219 Enable CMF Mailbox x%x (x%x/x%x) "
8274                                         "failed, rc:x%x dd:x%x\n",
8275                                         bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8276                                         lpfc_sli_config_mbox_subsys_get
8277                                                 (phba, mboxq),
8278                                         lpfc_sli_config_mbox_opcode_get
8279                                                 (phba, mboxq),
8280                                         rc, cmf);
8281                         sli4_params->cmf = 0;
8282                         phba->cmf_active_mode = LPFC_CFG_OFF;
8283                         goto no_cmf;
8284                 }
8285
8286                 /* Allocate Congestion Information Buffer */
8287                 if (!phba->cgn_i) {
8288                         mp = kmalloc(sizeof(*mp), GFP_KERNEL);
8289                         if (mp)
8290                                 mp->virt = dma_alloc_coherent
8291                                                 (&phba->pcidev->dev,
8292                                                 sizeof(struct lpfc_cgn_info),
8293                                                 &mp->phys, GFP_KERNEL);
8294                         if (!mp || !mp->virt) {
8295                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8296                                                 "2640 Failed to alloc memory "
8297                                                 "for Congestion Info\n");
8298                                 kfree(mp);
8299                                 sli4_params->cmf = 0;
8300                                 phba->cmf_active_mode = LPFC_CFG_OFF;
8301                                 goto no_cmf;
8302                         }
8303                         phba->cgn_i = mp;
8304
8305                         /* initialize congestion buffer info */
8306                         lpfc_init_congestion_buf(phba);
8307                         lpfc_init_congestion_stat(phba);
8308
8309                         /* Zero out Congestion Signal counters */
8310                         atomic64_set(&phba->cgn_acqe_stat.alarm, 0);
8311                         atomic64_set(&phba->cgn_acqe_stat.warn, 0);
8312                 }
8313
8314                 rc = lpfc_sli4_cgn_params_read(phba);
8315                 if (rc < 0) {
8316                         lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8317                                         "6242 Error reading Cgn Params (%d)\n",
8318                                         rc);
8319                         /* Ensure CGN Mode is off */
8320                         sli4_params->cmf = 0;
8321                 } else if (!rc) {
8322                         lpfc_printf_log(phba, KERN_ERR, LOG_CGN_MGMT | LOG_INIT,
8323                                         "6243 CGN Event empty object.\n");
8324                         /* Ensure CGN Mode is off */
8325                         sli4_params->cmf = 0;
8326                 }
8327         } else {
8328 no_cmf:
8329                 lpfc_printf_log(phba, KERN_WARNING, LOG_CGN_MGMT,
8330                                 "6220 CMF is disabled\n");
8331         }
8332
8333         /* Only register congestion buffer with firmware if BOTH
8334          * CMF and E2E are enabled.
8335          */
8336         if (sli4_params->cmf && sli4_params->mi_ver) {
8337                 rc = lpfc_reg_congestion_buf(phba);
8338                 if (rc) {
8339                         dma_free_coherent(&phba->pcidev->dev,
8340                                           sizeof(struct lpfc_cgn_info),
8341                                           phba->cgn_i->virt, phba->cgn_i->phys);
8342                         kfree(phba->cgn_i);
8343                         phba->cgn_i = NULL;
8344                         /* Ensure CGN Mode is off */
8345                         phba->cmf_active_mode = LPFC_CFG_OFF;
8346                         sli4_params->cmf = 0;
8347                         return 0;
8348                 }
8349         }
8350         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8351                         "6470 Setup MI version %d CMF %d mode %d\n",
8352                         sli4_params->mi_ver, sli4_params->cmf,
8353                         phba->cmf_active_mode);
8354
8355         mempool_free(mboxq, phba->mbox_mem_pool);
8356
8357         /* Initialize atomic counters */
8358         atomic_set(&phba->cgn_fabric_warn_cnt, 0);
8359         atomic_set(&phba->cgn_fabric_alarm_cnt, 0);
8360         atomic_set(&phba->cgn_sync_alarm_cnt, 0);
8361         atomic_set(&phba->cgn_sync_warn_cnt, 0);
8362         atomic_set(&phba->cgn_driver_evt_cnt, 0);
8363         atomic_set(&phba->cgn_latency_evt_cnt, 0);
8364         atomic64_set(&phba->cgn_latency_evt, 0);
8365
8366         phba->cmf_interval_rate = LPFC_CMF_INTERVAL;
8367
8368         /* Allocate RX Monitor Buffer */
8369         if (!phba->rx_monitor) {
8370                 phba->rx_monitor = kzalloc(sizeof(*phba->rx_monitor),
8371                                            GFP_KERNEL);
8372
8373                 if (!phba->rx_monitor) {
8374                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8375                                         "2644 Failed to alloc memory "
8376                                         "for RX Monitor Buffer\n");
8377                         return -ENOMEM;
8378                 }
8379
8380                 /* Instruct the rx_monitor object to instantiate its ring */
8381                 if (lpfc_rx_monitor_create_ring(phba->rx_monitor,
8382                                                 LPFC_MAX_RXMONITOR_ENTRY)) {
8383                         kfree(phba->rx_monitor);
8384                         phba->rx_monitor = NULL;
8385                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
8386                                         "2645 Failed to alloc memory "
8387                                         "for RX Monitor's Ring\n");
8388                         return -ENOMEM;
8389                 }
8390         }
8391
8392         return 0;
8393 }
8394
8395 static int
8396 lpfc_set_host_tm(struct lpfc_hba *phba)
8397 {
8398         LPFC_MBOXQ_t *mboxq;
8399         uint32_t len, rc;
8400         struct timespec64 cur_time;
8401         struct tm broken;
8402         uint32_t month, day, year;
8403         uint32_t hour, minute, second;
8404         struct lpfc_mbx_set_host_date_time *tm;
8405
8406         mboxq = (LPFC_MBOXQ_t *)mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8407         if (!mboxq)
8408                 return -ENOMEM;
8409
8410         len = sizeof(struct lpfc_mbx_set_host_data) -
8411                 sizeof(struct lpfc_sli4_cfg_mhdr);
8412         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_COMMON,
8413                          LPFC_MBOX_OPCODE_SET_HOST_DATA, len,
8414                          LPFC_SLI4_MBX_EMBED);
8415
8416         mboxq->u.mqe.un.set_host_data.param_id = LPFC_SET_HOST_DATE_TIME;
8417         mboxq->u.mqe.un.set_host_data.param_len =
8418                         sizeof(struct lpfc_mbx_set_host_date_time);
8419         tm = &mboxq->u.mqe.un.set_host_data.un.tm;
8420         ktime_get_real_ts64(&cur_time);
8421         time64_to_tm(cur_time.tv_sec, 0, &broken);
8422         month = broken.tm_mon + 1;
8423         day = broken.tm_mday;
8424         year = broken.tm_year - 100;
8425         hour = broken.tm_hour;
8426         minute = broken.tm_min;
8427         second = broken.tm_sec;
8428         bf_set(lpfc_mbx_set_host_month, tm, month);
8429         bf_set(lpfc_mbx_set_host_day, tm, day);
8430         bf_set(lpfc_mbx_set_host_year, tm, year);
8431         bf_set(lpfc_mbx_set_host_hour, tm, hour);
8432         bf_set(lpfc_mbx_set_host_min, tm, minute);
8433         bf_set(lpfc_mbx_set_host_sec, tm, second);
8434
8435         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8436         mempool_free(mboxq, phba->mbox_mem_pool);
8437         return rc;
8438 }
8439
8440 /**
8441  * lpfc_sli4_hba_setup - SLI4 device initialization PCI function
8442  * @phba: Pointer to HBA context object.
8443  *
8444  * This function is the main SLI4 device initialization PCI function. This
8445  * function is called by the HBA initialization code, HBA reset code and
8446  * HBA error attention handler code. Caller is not required to hold any
8447  * locks.
8448  **/
8449 int
8450 lpfc_sli4_hba_setup(struct lpfc_hba *phba)
8451 {
8452         int rc, i, cnt, len, dd;
8453         LPFC_MBOXQ_t *mboxq;
8454         struct lpfc_mqe *mqe;
8455         uint8_t *vpd;
8456         uint32_t vpd_size;
8457         uint32_t ftr_rsp = 0;
8458         struct Scsi_Host *shost = lpfc_shost_from_vport(phba->pport);
8459         struct lpfc_vport *vport = phba->pport;
8460         struct lpfc_dmabuf *mp;
8461         struct lpfc_rqb *rqbp;
8462         u32 flg;
8463
8464         /* Perform a PCI function reset to start from clean */
8465         rc = lpfc_pci_function_reset(phba);
8466         if (unlikely(rc))
8467                 return -ENODEV;
8468
8469         /* Check the HBA Host Status Register for readyness */
8470         rc = lpfc_sli4_post_status_check(phba);
8471         if (unlikely(rc))
8472                 return -ENODEV;
8473         else {
8474                 spin_lock_irq(&phba->hbalock);
8475                 phba->sli.sli_flag |= LPFC_SLI_ACTIVE;
8476                 flg = phba->sli.sli_flag;
8477                 spin_unlock_irq(&phba->hbalock);
8478                 /* Allow a little time after setting SLI_ACTIVE for any polled
8479                  * MBX commands to complete via BSG.
8480                  */
8481                 for (i = 0; i < 50 && (flg & LPFC_SLI_MBOX_ACTIVE); i++) {
8482                         msleep(20);
8483                         spin_lock_irq(&phba->hbalock);
8484                         flg = phba->sli.sli_flag;
8485                         spin_unlock_irq(&phba->hbalock);
8486                 }
8487         }
8488         clear_bit(HBA_SETUP, &phba->hba_flag);
8489
8490         lpfc_sli4_dip(phba);
8491
8492         /*
8493          * Allocate a single mailbox container for initializing the
8494          * port.
8495          */
8496         mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
8497         if (!mboxq)
8498                 return -ENOMEM;
8499
8500         /* Issue READ_REV to collect vpd and FW information. */
8501         vpd_size = SLI4_PAGE_SIZE;
8502         vpd = kzalloc(vpd_size, GFP_KERNEL);
8503         if (!vpd) {
8504                 rc = -ENOMEM;
8505                 goto out_free_mbox;
8506         }
8507
8508         rc = lpfc_sli4_read_rev(phba, mboxq, vpd, &vpd_size);
8509         if (unlikely(rc)) {
8510                 kfree(vpd);
8511                 goto out_free_mbox;
8512         }
8513
8514         mqe = &mboxq->u.mqe;
8515         phba->sli_rev = bf_get(lpfc_mbx_rd_rev_sli_lvl, &mqe->un.read_rev);
8516         if (bf_get(lpfc_mbx_rd_rev_fcoe, &mqe->un.read_rev)) {
8517                 set_bit(HBA_FCOE_MODE, &phba->hba_flag);
8518                 phba->fcp_embed_io = 0; /* SLI4 FC support only */
8519         } else {
8520                 clear_bit(HBA_FCOE_MODE, &phba->hba_flag);
8521         }
8522
8523         if (bf_get(lpfc_mbx_rd_rev_cee_ver, &mqe->un.read_rev) ==
8524                 LPFC_DCBX_CEE_MODE)
8525                 set_bit(HBA_FIP_SUPPORT, &phba->hba_flag);
8526         else
8527                 clear_bit(HBA_FIP_SUPPORT, &phba->hba_flag);
8528
8529         clear_bit(HBA_IOQ_FLUSH, &phba->hba_flag);
8530
8531         if (phba->sli_rev != LPFC_SLI_REV4) {
8532                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8533                         "0376 READ_REV Error. SLI Level %d "
8534                         "FCoE enabled %d\n",
8535                         phba->sli_rev,
8536                         test_bit(HBA_FCOE_MODE, &phba->hba_flag) ? 1 : 0);
8537                 rc = -EIO;
8538                 kfree(vpd);
8539                 goto out_free_mbox;
8540         }
8541
8542         rc = lpfc_set_host_tm(phba);
8543         lpfc_printf_log(phba, KERN_ERR, LOG_MBOX | LOG_INIT,
8544                         "6468 Set host date / time: Status x%x:\n", rc);
8545
8546         /*
8547          * Continue initialization with default values even if driver failed
8548          * to read FCoE param config regions, only read parameters if the
8549          * board is FCoE
8550          */
8551         if (test_bit(HBA_FCOE_MODE, &phba->hba_flag) &&
8552             lpfc_sli4_read_fcoe_params(phba))
8553                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_INIT,
8554                         "2570 Failed to read FCoE parameters\n");
8555
8556         /*
8557          * Retrieve sli4 device physical port name, failure of doing it
8558          * is considered as non-fatal.
8559          */
8560         rc = lpfc_sli4_retrieve_pport_name(phba);
8561         if (!rc)
8562                 lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8563                                 "3080 Successful retrieving SLI4 device "
8564                                 "physical port name: %s.\n", phba->Port);
8565
8566         rc = lpfc_sli4_get_ctl_attr(phba);
8567         if (!rc)
8568                 lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8569                                 "8351 Successful retrieving SLI4 device "
8570                                 "CTL ATTR\n");
8571
8572         /*
8573          * Evaluate the read rev and vpd data. Populate the driver
8574          * state with the results. If this routine fails, the failure
8575          * is not fatal as the driver will use generic values.
8576          */
8577         rc = lpfc_parse_vpd(phba, vpd, vpd_size);
8578         if (unlikely(!rc))
8579                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8580                                 "0377 Error %d parsing vpd. "
8581                                 "Using defaults.\n", rc);
8582         kfree(vpd);
8583
8584         /* Save information as VPD data */
8585         phba->vpd.rev.biuRev = mqe->un.read_rev.first_hw_rev;
8586         phba->vpd.rev.smRev = mqe->un.read_rev.second_hw_rev;
8587
8588         /*
8589          * This is because first G7 ASIC doesn't support the standard
8590          * 0x5a NVME cmd descriptor type/subtype
8591          */
8592         if ((bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8593                         LPFC_SLI_INTF_IF_TYPE_6) &&
8594             (phba->vpd.rev.biuRev == LPFC_G7_ASIC_1) &&
8595             (phba->vpd.rev.smRev == 0) &&
8596             (phba->cfg_nvme_embed_cmd == 1))
8597                 phba->cfg_nvme_embed_cmd = 0;
8598
8599         phba->vpd.rev.endecRev = mqe->un.read_rev.third_hw_rev;
8600         phba->vpd.rev.fcphHigh = bf_get(lpfc_mbx_rd_rev_fcph_high,
8601                                          &mqe->un.read_rev);
8602         phba->vpd.rev.fcphLow = bf_get(lpfc_mbx_rd_rev_fcph_low,
8603                                        &mqe->un.read_rev);
8604         phba->vpd.rev.feaLevelHigh = bf_get(lpfc_mbx_rd_rev_ftr_lvl_high,
8605                                             &mqe->un.read_rev);
8606         phba->vpd.rev.feaLevelLow = bf_get(lpfc_mbx_rd_rev_ftr_lvl_low,
8607                                            &mqe->un.read_rev);
8608         phba->vpd.rev.sli1FwRev = mqe->un.read_rev.fw_id_rev;
8609         memcpy(phba->vpd.rev.sli1FwName, mqe->un.read_rev.fw_name, 16);
8610         phba->vpd.rev.sli2FwRev = mqe->un.read_rev.ulp_fw_id_rev;
8611         memcpy(phba->vpd.rev.sli2FwName, mqe->un.read_rev.ulp_fw_name, 16);
8612         phba->vpd.rev.opFwRev = mqe->un.read_rev.fw_id_rev;
8613         memcpy(phba->vpd.rev.opFwName, mqe->un.read_rev.fw_name, 16);
8614         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
8615                         "(%d):0380 READ_REV Status x%x "
8616                         "fw_rev:%s fcphHi:%x fcphLo:%x flHi:%x flLo:%x\n",
8617                         mboxq->vport ? mboxq->vport->vpi : 0,
8618                         bf_get(lpfc_mqe_status, mqe),
8619                         phba->vpd.rev.opFwName,
8620                         phba->vpd.rev.fcphHigh, phba->vpd.rev.fcphLow,
8621                         phba->vpd.rev.feaLevelHigh, phba->vpd.rev.feaLevelLow);
8622
8623         if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) ==
8624             LPFC_SLI_INTF_IF_TYPE_0) {
8625                 lpfc_set_features(phba, mboxq, LPFC_SET_UE_RECOVERY);
8626                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8627                 if (rc == MBX_SUCCESS) {
8628                         set_bit(HBA_RECOVERABLE_UE, &phba->hba_flag);
8629                         /* Set 1Sec interval to detect UE */
8630                         phba->eratt_poll_interval = 1;
8631                         phba->sli4_hba.ue_to_sr = bf_get(
8632                                         lpfc_mbx_set_feature_UESR,
8633                                         &mboxq->u.mqe.un.set_feature);
8634                         phba->sli4_hba.ue_to_rp = bf_get(
8635                                         lpfc_mbx_set_feature_UERP,
8636                                         &mboxq->u.mqe.un.set_feature);
8637                 }
8638         }
8639
8640         if (phba->cfg_enable_mds_diags && phba->mds_diags_support) {
8641                 /* Enable MDS Diagnostics only if the SLI Port supports it */
8642                 lpfc_set_features(phba, mboxq, LPFC_SET_MDS_DIAGS);
8643                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8644                 if (rc != MBX_SUCCESS)
8645                         phba->mds_diags_support = 0;
8646         }
8647
8648         /*
8649          * Discover the port's supported feature set and match it against the
8650          * hosts requests.
8651          */
8652         lpfc_request_features(phba, mboxq);
8653         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8654         if (unlikely(rc)) {
8655                 rc = -EIO;
8656                 goto out_free_mbox;
8657         }
8658
8659         /* Disable VMID if app header is not supported */
8660         if (phba->cfg_vmid_app_header && !(bf_get(lpfc_mbx_rq_ftr_rsp_ashdr,
8661                                                   &mqe->un.req_ftrs))) {
8662                 bf_set(lpfc_ftr_ashdr, &phba->sli4_hba.sli4_flags, 0);
8663                 phba->cfg_vmid_app_header = 0;
8664                 lpfc_printf_log(phba, KERN_DEBUG, LOG_SLI,
8665                                 "1242 vmid feature not supported\n");
8666         }
8667
8668         /*
8669          * The port must support FCP initiator mode as this is the
8670          * only mode running in the host.
8671          */
8672         if (!(bf_get(lpfc_mbx_rq_ftr_rsp_fcpi, &mqe->un.req_ftrs))) {
8673                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8674                                 "0378 No support for fcpi mode.\n");
8675                 ftr_rsp++;
8676         }
8677
8678         /* Performance Hints are ONLY for FCoE */
8679         if (test_bit(HBA_FCOE_MODE, &phba->hba_flag)) {
8680                 if (bf_get(lpfc_mbx_rq_ftr_rsp_perfh, &mqe->un.req_ftrs))
8681                         phba->sli3_options |= LPFC_SLI4_PERFH_ENABLED;
8682                 else
8683                         phba->sli3_options &= ~LPFC_SLI4_PERFH_ENABLED;
8684         }
8685
8686         /*
8687          * If the port cannot support the host's requested features
8688          * then turn off the global config parameters to disable the
8689          * feature in the driver.  This is not a fatal error.
8690          */
8691         if (phba->sli3_options & LPFC_SLI3_BG_ENABLED) {
8692                 if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs))) {
8693                         phba->cfg_enable_bg = 0;
8694                         phba->sli3_options &= ~LPFC_SLI3_BG_ENABLED;
8695                         ftr_rsp++;
8696                 }
8697         }
8698
8699         if (phba->max_vpi && phba->cfg_enable_npiv &&
8700             !(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8701                 ftr_rsp++;
8702
8703         if (ftr_rsp) {
8704                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8705                                 "0379 Feature Mismatch Data: x%08x %08x "
8706                                 "x%x x%x x%x\n", mqe->un.req_ftrs.word2,
8707                                 mqe->un.req_ftrs.word3, phba->cfg_enable_bg,
8708                                 phba->cfg_enable_npiv, phba->max_vpi);
8709                 if (!(bf_get(lpfc_mbx_rq_ftr_rsp_dif, &mqe->un.req_ftrs)))
8710                         phba->cfg_enable_bg = 0;
8711                 if (!(bf_get(lpfc_mbx_rq_ftr_rsp_npiv, &mqe->un.req_ftrs)))
8712                         phba->cfg_enable_npiv = 0;
8713         }
8714
8715         /* These SLI3 features are assumed in SLI4 */
8716         spin_lock_irq(&phba->hbalock);
8717         phba->sli3_options |= (LPFC_SLI3_NPIV_ENABLED | LPFC_SLI3_HBQ_ENABLED);
8718         spin_unlock_irq(&phba->hbalock);
8719
8720         /* Always try to enable dual dump feature if we can */
8721         lpfc_set_features(phba, mboxq, LPFC_SET_DUAL_DUMP);
8722         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8723         dd = bf_get(lpfc_mbx_set_feature_dd, &mboxq->u.mqe.un.set_feature);
8724         if ((rc == MBX_SUCCESS) && (dd == LPFC_ENABLE_DUAL_DUMP))
8725                 lpfc_printf_log(phba, KERN_ERR, LOG_SLI,
8726                                 "6448 Dual Dump is enabled\n");
8727         else
8728                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI | LOG_INIT,
8729                                 "6447 Dual Dump Mailbox x%x (x%x/x%x) failed, "
8730                                 "rc:x%x dd:x%x\n",
8731                                 bf_get(lpfc_mqe_command, &mboxq->u.mqe),
8732                                 lpfc_sli_config_mbox_subsys_get(
8733                                         phba, mboxq),
8734                                 lpfc_sli_config_mbox_opcode_get(
8735                                         phba, mboxq),
8736                                 rc, dd);
8737
8738         /*
8739          * Allocate all resources (xri,rpi,vpi,vfi) now.  Subsequent
8740          * calls depends on these resources to complete port setup.
8741          */
8742         rc = lpfc_sli4_alloc_resource_identifiers(phba);
8743         if (rc) {
8744                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8745                                 "2920 Failed to alloc Resource IDs "
8746                                 "rc = x%x\n", rc);
8747                 goto out_free_mbox;
8748         }
8749
8750         lpfc_sli4_node_rpi_restore(phba);
8751
8752         lpfc_set_host_data(phba, mboxq);
8753
8754         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8755         if (rc) {
8756                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
8757                                 "2134 Failed to set host os driver version %x",
8758                                 rc);
8759         }
8760
8761         /* Read the port's service parameters. */
8762         rc = lpfc_read_sparam(phba, mboxq, vport->vpi);
8763         if (rc) {
8764                 phba->link_state = LPFC_HBA_ERROR;
8765                 rc = -ENOMEM;
8766                 goto out_free_mbox;
8767         }
8768
8769         mboxq->vport = vport;
8770         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8771         mp = mboxq->ctx_buf;
8772         if (rc == MBX_SUCCESS) {
8773                 memcpy(&vport->fc_sparam, mp->virt, sizeof(struct serv_parm));
8774                 rc = 0;
8775         }
8776
8777         /*
8778          * This memory was allocated by the lpfc_read_sparam routine but is
8779          * no longer needed.  It is released and ctx_buf NULLed to prevent
8780          * unintended pointer access as the mbox is reused.
8781          */
8782         lpfc_mbuf_free(phba, mp->virt, mp->phys);
8783         kfree(mp);
8784         mboxq->ctx_buf = NULL;
8785         if (unlikely(rc)) {
8786                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8787                                 "0382 READ_SPARAM command failed "
8788                                 "status %d, mbxStatus x%x\n",
8789                                 rc, bf_get(lpfc_mqe_status, mqe));
8790                 phba->link_state = LPFC_HBA_ERROR;
8791                 rc = -EIO;
8792                 goto out_free_mbox;
8793         }
8794
8795         lpfc_update_vport_wwn(vport);
8796
8797         /* Update the fc_host data structures with new wwn. */
8798         fc_host_node_name(shost) = wwn_to_u64(vport->fc_nodename.u.wwn);
8799         fc_host_port_name(shost) = wwn_to_u64(vport->fc_portname.u.wwn);
8800
8801         /* Create all the SLI4 queues */
8802         rc = lpfc_sli4_queue_create(phba);
8803         if (rc) {
8804                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8805                                 "3089 Failed to allocate queues\n");
8806                 rc = -ENODEV;
8807                 goto out_free_mbox;
8808         }
8809         /* Set up all the queues to the device */
8810         rc = lpfc_sli4_queue_setup(phba);
8811         if (unlikely(rc)) {
8812                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8813                                 "0381 Error %d during queue setup.\n", rc);
8814                 goto out_stop_timers;
8815         }
8816         /* Initialize the driver internal SLI layer lists. */
8817         lpfc_sli4_setup(phba);
8818         lpfc_sli4_queue_init(phba);
8819
8820         /* update host els xri-sgl sizes and mappings */
8821         rc = lpfc_sli4_els_sgl_update(phba);
8822         if (unlikely(rc)) {
8823                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8824                                 "1400 Failed to update xri-sgl size and "
8825                                 "mapping: %d\n", rc);
8826                 goto out_destroy_queue;
8827         }
8828
8829         /* register the els sgl pool to the port */
8830         rc = lpfc_sli4_repost_sgl_list(phba, &phba->sli4_hba.lpfc_els_sgl_list,
8831                                        phba->sli4_hba.els_xri_cnt);
8832         if (unlikely(rc < 0)) {
8833                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8834                                 "0582 Error %d during els sgl post "
8835                                 "operation\n", rc);
8836                 rc = -ENODEV;
8837                 goto out_destroy_queue;
8838         }
8839         phba->sli4_hba.els_xri_cnt = rc;
8840
8841         if (phba->nvmet_support) {
8842                 /* update host nvmet xri-sgl sizes and mappings */
8843                 rc = lpfc_sli4_nvmet_sgl_update(phba);
8844                 if (unlikely(rc)) {
8845                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8846                                         "6308 Failed to update nvmet-sgl size "
8847                                         "and mapping: %d\n", rc);
8848                         goto out_destroy_queue;
8849                 }
8850
8851                 /* register the nvmet sgl pool to the port */
8852                 rc = lpfc_sli4_repost_sgl_list(
8853                         phba,
8854                         &phba->sli4_hba.lpfc_nvmet_sgl_list,
8855                         phba->sli4_hba.nvmet_xri_cnt);
8856                 if (unlikely(rc < 0)) {
8857                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8858                                         "3117 Error %d during nvmet "
8859                                         "sgl post\n", rc);
8860                         rc = -ENODEV;
8861                         goto out_destroy_queue;
8862                 }
8863                 phba->sli4_hba.nvmet_xri_cnt = rc;
8864
8865                 /* We allocate an iocbq for every receive context SGL.
8866                  * The additional allocation is for abort and ls handling.
8867                  */
8868                 cnt = phba->sli4_hba.nvmet_xri_cnt +
8869                         phba->sli4_hba.max_cfg_param.max_xri;
8870         } else {
8871                 /* update host common xri-sgl sizes and mappings */
8872                 rc = lpfc_sli4_io_sgl_update(phba);
8873                 if (unlikely(rc)) {
8874                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8875                                         "6082 Failed to update nvme-sgl size "
8876                                         "and mapping: %d\n", rc);
8877                         goto out_destroy_queue;
8878                 }
8879
8880                 /* register the allocated common sgl pool to the port */
8881                 rc = lpfc_sli4_repost_io_sgl_list(phba);
8882                 if (unlikely(rc)) {
8883                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8884                                         "6116 Error %d during nvme sgl post "
8885                                         "operation\n", rc);
8886                         /* Some NVME buffers were moved to abort nvme list */
8887                         /* A pci function reset will repost them */
8888                         rc = -ENODEV;
8889                         goto out_destroy_queue;
8890                 }
8891                 /* Each lpfc_io_buf job structure has an iocbq element.
8892                  * This cnt provides for abort, els, ct and ls requests.
8893                  */
8894                 cnt = phba->sli4_hba.max_cfg_param.max_xri;
8895         }
8896
8897         if (!phba->sli.iocbq_lookup) {
8898                 /* Initialize and populate the iocb list per host */
8899                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
8900                                 "2821 initialize iocb list with %d entries\n",
8901                                 cnt);
8902                 rc = lpfc_init_iocb_list(phba, cnt);
8903                 if (rc) {
8904                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8905                                         "1413 Failed to init iocb list.\n");
8906                         goto out_destroy_queue;
8907                 }
8908         }
8909
8910         if (phba->nvmet_support)
8911                 lpfc_nvmet_create_targetport(phba);
8912
8913         if (phba->nvmet_support && phba->cfg_nvmet_mrq) {
8914                 /* Post initial buffers to all RQs created */
8915                 for (i = 0; i < phba->cfg_nvmet_mrq; i++) {
8916                         rqbp = phba->sli4_hba.nvmet_mrq_hdr[i]->rqbp;
8917                         INIT_LIST_HEAD(&rqbp->rqb_buffer_list);
8918                         rqbp->rqb_alloc_buffer = lpfc_sli4_nvmet_alloc;
8919                         rqbp->rqb_free_buffer = lpfc_sli4_nvmet_free;
8920                         rqbp->entry_count = LPFC_NVMET_RQE_DEF_COUNT;
8921                         rqbp->buffer_count = 0;
8922
8923                         lpfc_post_rq_buffer(
8924                                 phba, phba->sli4_hba.nvmet_mrq_hdr[i],
8925                                 phba->sli4_hba.nvmet_mrq_data[i],
8926                                 phba->cfg_nvmet_mrq_post, i);
8927                 }
8928         }
8929
8930         /* Post the rpi header region to the device. */
8931         rc = lpfc_sli4_post_all_rpi_hdrs(phba);
8932         if (unlikely(rc)) {
8933                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
8934                                 "0393 Error %d during rpi post operation\n",
8935                                 rc);
8936                 rc = -ENODEV;
8937                 goto out_free_iocblist;
8938         }
8939
8940         if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag)) {
8941                 if ((phba->nvmet_support == 0) || (phba->cfg_nvmet_mrq == 1)) {
8942                         /*
8943                          * The FC Port needs to register FCFI (index 0)
8944                          */
8945                         lpfc_reg_fcfi(phba, mboxq);
8946                         mboxq->vport = phba->pport;
8947                         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8948                         if (rc != MBX_SUCCESS)
8949                                 goto out_unset_queue;
8950                         rc = 0;
8951                         phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_fcfi,
8952                                                 &mboxq->u.mqe.un.reg_fcfi);
8953                 } else {
8954                         /* We are a NVME Target mode with MRQ > 1 */
8955
8956                         /* First register the FCFI */
8957                         lpfc_reg_fcfi_mrq(phba, mboxq, 0);
8958                         mboxq->vport = phba->pport;
8959                         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8960                         if (rc != MBX_SUCCESS)
8961                                 goto out_unset_queue;
8962                         rc = 0;
8963                         phba->fcf.fcfi = bf_get(lpfc_reg_fcfi_mrq_fcfi,
8964                                                 &mboxq->u.mqe.un.reg_fcfi_mrq);
8965
8966                         /* Next register the MRQs */
8967                         lpfc_reg_fcfi_mrq(phba, mboxq, 1);
8968                         mboxq->vport = phba->pport;
8969                         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
8970                         if (rc != MBX_SUCCESS)
8971                                 goto out_unset_queue;
8972                         rc = 0;
8973                 }
8974                 /* Check if the port is configured to be disabled */
8975                 lpfc_sli_read_link_ste(phba);
8976         }
8977
8978         /* Don't post more new bufs if repost already recovered
8979          * the nvme sgls.
8980          */
8981         if (phba->nvmet_support == 0) {
8982                 if (phba->sli4_hba.io_xri_cnt == 0) {
8983                         len = lpfc_new_io_buf(
8984                                               phba, phba->sli4_hba.io_xri_max);
8985                         if (len == 0) {
8986                                 rc = -ENOMEM;
8987                                 goto out_unset_queue;
8988                         }
8989
8990                         if (phba->cfg_xri_rebalancing)
8991                                 lpfc_create_multixri_pools(phba);
8992                 }
8993         } else {
8994                 phba->cfg_xri_rebalancing = 0;
8995         }
8996
8997         /* Allow asynchronous mailbox command to go through */
8998         spin_lock_irq(&phba->hbalock);
8999         phba->sli.sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9000         spin_unlock_irq(&phba->hbalock);
9001
9002         /* Post receive buffers to the device */
9003         lpfc_sli4_rb_setup(phba);
9004
9005         /* Reset HBA FCF states after HBA reset */
9006         phba->fcf.fcf_flag = 0;
9007         phba->fcf.current_rec.flag = 0;
9008
9009         /* Start the ELS watchdog timer */
9010         mod_timer(&vport->els_tmofunc,
9011                   jiffies + msecs_to_jiffies(1000 * (phba->fc_ratov * 2)));
9012
9013         /* Start heart beat timer */
9014         mod_timer(&phba->hb_tmofunc,
9015                   jiffies + msecs_to_jiffies(1000 * LPFC_HB_MBOX_INTERVAL));
9016         clear_bit(HBA_HBEAT_INP, &phba->hba_flag);
9017         clear_bit(HBA_HBEAT_TMO, &phba->hba_flag);
9018         phba->last_completion_time = jiffies;
9019
9020         /* start eq_delay heartbeat */
9021         if (phba->cfg_auto_imax)
9022                 queue_delayed_work(phba->wq, &phba->eq_delay_work,
9023                                    msecs_to_jiffies(LPFC_EQ_DELAY_MSECS));
9024
9025         /* start per phba idle_stat_delay heartbeat */
9026         lpfc_init_idle_stat_hb(phba);
9027
9028         /* Start error attention (ERATT) polling timer */
9029         mod_timer(&phba->eratt_poll,
9030                   jiffies + msecs_to_jiffies(1000 * phba->eratt_poll_interval));
9031
9032         /*
9033          * The port is ready, set the host's link state to LINK_DOWN
9034          * in preparation for link interrupts.
9035          */
9036         spin_lock_irq(&phba->hbalock);
9037         phba->link_state = LPFC_LINK_DOWN;
9038
9039         /* Check if physical ports are trunked */
9040         if (bf_get(lpfc_conf_trunk_port0, &phba->sli4_hba))
9041                 phba->trunk_link.link0.state = LPFC_LINK_DOWN;
9042         if (bf_get(lpfc_conf_trunk_port1, &phba->sli4_hba))
9043                 phba->trunk_link.link1.state = LPFC_LINK_DOWN;
9044         if (bf_get(lpfc_conf_trunk_port2, &phba->sli4_hba))
9045                 phba->trunk_link.link2.state = LPFC_LINK_DOWN;
9046         if (bf_get(lpfc_conf_trunk_port3, &phba->sli4_hba))
9047                 phba->trunk_link.link3.state = LPFC_LINK_DOWN;
9048         spin_unlock_irq(&phba->hbalock);
9049
9050         /* Arm the CQs and then EQs on device */
9051         lpfc_sli4_arm_cqeq_intr(phba);
9052
9053         /* Indicate device interrupt mode */
9054         phba->sli4_hba.intr_enable = 1;
9055
9056         /* Setup CMF after HBA is initialized */
9057         lpfc_cmf_setup(phba);
9058
9059         if (!test_bit(HBA_FCOE_MODE, &phba->hba_flag) &&
9060             test_bit(LINK_DISABLED, &phba->hba_flag)) {
9061                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9062                                 "3103 Adapter Link is disabled.\n");
9063                 lpfc_down_link(phba, mboxq);
9064                 rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
9065                 if (rc != MBX_SUCCESS) {
9066                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9067                                         "3104 Adapter failed to issue "
9068                                         "DOWN_LINK mbox cmd, rc:x%x\n", rc);
9069                         goto out_io_buff_free;
9070                 }
9071         } else if (phba->cfg_suppress_link_up == LPFC_INITIALIZE_LINK) {
9072                 /* don't perform init_link on SLI4 FC port loopback test */
9073                 if (!(phba->link_flag & LS_LOOPBACK_MODE)) {
9074                         rc = phba->lpfc_hba_init_link(phba, MBX_NOWAIT);
9075                         if (rc)
9076                                 goto out_io_buff_free;
9077                 }
9078         }
9079         mempool_free(mboxq, phba->mbox_mem_pool);
9080
9081         /* Enable RAS FW log support */
9082         lpfc_sli4_ras_setup(phba);
9083
9084         set_bit(HBA_SETUP, &phba->hba_flag);
9085         return rc;
9086
9087 out_io_buff_free:
9088         /* Free allocated IO Buffers */
9089         lpfc_io_free(phba);
9090 out_unset_queue:
9091         /* Unset all the queues set up in this routine when error out */
9092         lpfc_sli4_queue_unset(phba);
9093 out_free_iocblist:
9094         lpfc_free_iocb_list(phba);
9095 out_destroy_queue:
9096         lpfc_sli4_queue_destroy(phba);
9097 out_stop_timers:
9098         lpfc_stop_hba_timers(phba);
9099 out_free_mbox:
9100         mempool_free(mboxq, phba->mbox_mem_pool);
9101         return rc;
9102 }
9103
9104 /**
9105  * lpfc_mbox_timeout - Timeout call back function for mbox timer
9106  * @t: Context to fetch pointer to hba structure from.
9107  *
9108  * This is the callback function for mailbox timer. The mailbox
9109  * timer is armed when a new mailbox command is issued and the timer
9110  * is deleted when the mailbox complete. The function is called by
9111  * the kernel timer code when a mailbox does not complete within
9112  * expected time. This function wakes up the worker thread to
9113  * process the mailbox timeout and returns. All the processing is
9114  * done by the worker thread function lpfc_mbox_timeout_handler.
9115  **/
9116 void
9117 lpfc_mbox_timeout(struct timer_list *t)
9118 {
9119         struct lpfc_hba  *phba = from_timer(phba, t, sli.mbox_tmo);
9120         unsigned long iflag;
9121         uint32_t tmo_posted;
9122
9123         spin_lock_irqsave(&phba->pport->work_port_lock, iflag);
9124         tmo_posted = phba->pport->work_port_events & WORKER_MBOX_TMO;
9125         if (!tmo_posted)
9126                 phba->pport->work_port_events |= WORKER_MBOX_TMO;
9127         spin_unlock_irqrestore(&phba->pport->work_port_lock, iflag);
9128
9129         if (!tmo_posted)
9130                 lpfc_worker_wake_up(phba);
9131         return;
9132 }
9133
9134 /**
9135  * lpfc_sli4_mbox_completions_pending - check to see if any mailbox completions
9136  *                                    are pending
9137  * @phba: Pointer to HBA context object.
9138  *
9139  * This function checks if any mailbox completions are present on the mailbox
9140  * completion queue.
9141  **/
9142 static bool
9143 lpfc_sli4_mbox_completions_pending(struct lpfc_hba *phba)
9144 {
9145
9146         uint32_t idx;
9147         struct lpfc_queue *mcq;
9148         struct lpfc_mcqe *mcqe;
9149         bool pending_completions = false;
9150         uint8_t qe_valid;
9151
9152         if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9153                 return false;
9154
9155         /* Check for completions on mailbox completion queue */
9156
9157         mcq = phba->sli4_hba.mbx_cq;
9158         idx = mcq->hba_index;
9159         qe_valid = mcq->qe_valid;
9160         while (bf_get_le32(lpfc_cqe_valid,
9161                (struct lpfc_cqe *)lpfc_sli4_qe(mcq, idx)) == qe_valid) {
9162                 mcqe = (struct lpfc_mcqe *)(lpfc_sli4_qe(mcq, idx));
9163                 if (bf_get_le32(lpfc_trailer_completed, mcqe) &&
9164                     (!bf_get_le32(lpfc_trailer_async, mcqe))) {
9165                         pending_completions = true;
9166                         break;
9167                 }
9168                 idx = (idx + 1) % mcq->entry_count;
9169                 if (mcq->hba_index == idx)
9170                         break;
9171
9172                 /* if the index wrapped around, toggle the valid bit */
9173                 if (phba->sli4_hba.pc_sli4_params.cqav && !idx)
9174                         qe_valid = (qe_valid) ? 0 : 1;
9175         }
9176         return pending_completions;
9177
9178 }
9179
9180 /**
9181  * lpfc_sli4_process_missed_mbox_completions - process mbox completions
9182  *                                            that were missed.
9183  * @phba: Pointer to HBA context object.
9184  *
9185  * For sli4, it is possible to miss an interrupt. As such mbox completions
9186  * maybe missed causing erroneous mailbox timeouts to occur. This function
9187  * checks to see if mbox completions are on the mailbox completion queue
9188  * and will process all the completions associated with the eq for the
9189  * mailbox completion queue.
9190  **/
9191 static bool
9192 lpfc_sli4_process_missed_mbox_completions(struct lpfc_hba *phba)
9193 {
9194         struct lpfc_sli4_hba *sli4_hba = &phba->sli4_hba;
9195         uint32_t eqidx;
9196         struct lpfc_queue *fpeq = NULL;
9197         struct lpfc_queue *eq;
9198         bool mbox_pending;
9199
9200         if (unlikely(!phba) || (phba->sli_rev != LPFC_SLI_REV4))
9201                 return false;
9202
9203         /* Find the EQ associated with the mbox CQ */
9204         if (sli4_hba->hdwq) {
9205                 for (eqidx = 0; eqidx < phba->cfg_irq_chann; eqidx++) {
9206                         eq = phba->sli4_hba.hba_eq_hdl[eqidx].eq;
9207                         if (eq && eq->queue_id == sli4_hba->mbx_cq->assoc_qid) {
9208                                 fpeq = eq;
9209                                 break;
9210                         }
9211                 }
9212         }
9213         if (!fpeq)
9214                 return false;
9215
9216         /* Turn off interrupts from this EQ */
9217
9218         sli4_hba->sli4_eq_clr_intr(fpeq);
9219
9220         /* Check to see if a mbox completion is pending */
9221
9222         mbox_pending = lpfc_sli4_mbox_completions_pending(phba);
9223
9224         /*
9225          * If a mbox completion is pending, process all the events on EQ
9226          * associated with the mbox completion queue (this could include
9227          * mailbox commands, async events, els commands, receive queue data
9228          * and fcp commands)
9229          */
9230
9231         if (mbox_pending)
9232                 /* process and rearm the EQ */
9233                 lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
9234                                      LPFC_QUEUE_WORK);
9235         else
9236                 /* Always clear and re-arm the EQ */
9237                 sli4_hba->sli4_write_eq_db(phba, fpeq, 0, LPFC_QUEUE_REARM);
9238
9239         return mbox_pending;
9240
9241 }
9242
9243 /**
9244  * lpfc_mbox_timeout_handler - Worker thread function to handle mailbox timeout
9245  * @phba: Pointer to HBA context object.
9246  *
9247  * This function is called from worker thread when a mailbox command times out.
9248  * The caller is not required to hold any locks. This function will reset the
9249  * HBA and recover all the pending commands.
9250  **/
9251 void
9252 lpfc_mbox_timeout_handler(struct lpfc_hba *phba)
9253 {
9254         LPFC_MBOXQ_t *pmbox = phba->sli.mbox_active;
9255         MAILBOX_t *mb = NULL;
9256
9257         struct lpfc_sli *psli = &phba->sli;
9258
9259         /* If the mailbox completed, process the completion */
9260         lpfc_sli4_process_missed_mbox_completions(phba);
9261
9262         if (!(psli->sli_flag & LPFC_SLI_ACTIVE))
9263                 return;
9264
9265         if (pmbox != NULL)
9266                 mb = &pmbox->u.mb;
9267         /* Check the pmbox pointer first.  There is a race condition
9268          * between the mbox timeout handler getting executed in the
9269          * worklist and the mailbox actually completing. When this
9270          * race condition occurs, the mbox_active will be NULL.
9271          */
9272         spin_lock_irq(&phba->hbalock);
9273         if (pmbox == NULL) {
9274                 lpfc_printf_log(phba, KERN_WARNING,
9275                                 LOG_MBOX | LOG_SLI,
9276                                 "0353 Active Mailbox cleared - mailbox timeout "
9277                                 "exiting\n");
9278                 spin_unlock_irq(&phba->hbalock);
9279                 return;
9280         }
9281
9282         /* Mbox cmd <mbxCommand> timeout */
9283         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9284                         "0310 Mailbox command x%x timeout Data: x%x x%x x%px\n",
9285                         mb->mbxCommand,
9286                         phba->pport->port_state,
9287                         phba->sli.sli_flag,
9288                         phba->sli.mbox_active);
9289         spin_unlock_irq(&phba->hbalock);
9290
9291         /* Setting state unknown so lpfc_sli_abort_iocb_ring
9292          * would get IOCB_ERROR from lpfc_sli_issue_iocb, allowing
9293          * it to fail all outstanding SCSI IO.
9294          */
9295         set_bit(MBX_TMO_ERR, &phba->bit_flags);
9296         spin_lock_irq(&phba->pport->work_port_lock);
9297         phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
9298         spin_unlock_irq(&phba->pport->work_port_lock);
9299         spin_lock_irq(&phba->hbalock);
9300         phba->link_state = LPFC_LINK_UNKNOWN;
9301         psli->sli_flag &= ~LPFC_SLI_ACTIVE;
9302         spin_unlock_irq(&phba->hbalock);
9303
9304         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9305                         "0345 Resetting board due to mailbox timeout\n");
9306
9307         /* Reset the HBA device */
9308         lpfc_reset_hba(phba);
9309 }
9310
9311 /**
9312  * lpfc_sli_issue_mbox_s3 - Issue an SLI3 mailbox command to firmware
9313  * @phba: Pointer to HBA context object.
9314  * @pmbox: Pointer to mailbox object.
9315  * @flag: Flag indicating how the mailbox need to be processed.
9316  *
9317  * This function is called by discovery code and HBA management code
9318  * to submit a mailbox command to firmware with SLI-3 interface spec. This
9319  * function gets the hbalock to protect the data structures.
9320  * The mailbox command can be submitted in polling mode, in which case
9321  * this function will wait in a polling loop for the completion of the
9322  * mailbox.
9323  * If the mailbox is submitted in no_wait mode (not polling) the
9324  * function will submit the command and returns immediately without waiting
9325  * for the mailbox completion. The no_wait is supported only when HBA
9326  * is in SLI2/SLI3 mode - interrupts are enabled.
9327  * The SLI interface allows only one mailbox pending at a time. If the
9328  * mailbox is issued in polling mode and there is already a mailbox
9329  * pending, then the function will return an error. If the mailbox is issued
9330  * in NO_WAIT mode and there is a mailbox pending already, the function
9331  * will return MBX_BUSY after queuing the mailbox into mailbox queue.
9332  * The sli layer owns the mailbox object until the completion of mailbox
9333  * command if this function return MBX_BUSY or MBX_SUCCESS. For all other
9334  * return codes the caller owns the mailbox command after the return of
9335  * the function.
9336  **/
9337 static int
9338 lpfc_sli_issue_mbox_s3(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox,
9339                        uint32_t flag)
9340 {
9341         MAILBOX_t *mbx;
9342         struct lpfc_sli *psli = &phba->sli;
9343         uint32_t status, evtctr;
9344         uint32_t ha_copy, hc_copy;
9345         int i;
9346         unsigned long timeout;
9347         unsigned long drvr_flag = 0;
9348         uint32_t word0, ldata;
9349         void __iomem *to_slim;
9350         int processing_queue = 0;
9351
9352         spin_lock_irqsave(&phba->hbalock, drvr_flag);
9353         if (!pmbox) {
9354                 phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9355                 /* processing mbox queue from intr_handler */
9356                 if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9357                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9358                         return MBX_SUCCESS;
9359                 }
9360                 processing_queue = 1;
9361                 pmbox = lpfc_mbox_get(phba);
9362                 if (!pmbox) {
9363                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9364                         return MBX_SUCCESS;
9365                 }
9366         }
9367
9368         if (pmbox->mbox_cmpl && pmbox->mbox_cmpl != lpfc_sli_def_mbox_cmpl &&
9369                 pmbox->mbox_cmpl != lpfc_sli_wake_mbox_wait) {
9370                 if(!pmbox->vport) {
9371                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9372                         lpfc_printf_log(phba, KERN_ERR,
9373                                         LOG_MBOX | LOG_VPORT,
9374                                         "1806 Mbox x%x failed. No vport\n",
9375                                         pmbox->u.mb.mbxCommand);
9376                         dump_stack();
9377                         goto out_not_finished;
9378                 }
9379         }
9380
9381         /* If the PCI channel is in offline state, do not post mbox. */
9382         if (unlikely(pci_channel_offline(phba->pcidev))) {
9383                 spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9384                 goto out_not_finished;
9385         }
9386
9387         /* If HBA has a deferred error attention, fail the iocb. */
9388         if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag))) {
9389                 spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9390                 goto out_not_finished;
9391         }
9392
9393         psli = &phba->sli;
9394
9395         mbx = &pmbox->u.mb;
9396         status = MBX_SUCCESS;
9397
9398         if (phba->link_state == LPFC_HBA_ERROR) {
9399                 spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9400
9401                 /* Mbox command <mbxCommand> cannot issue */
9402                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9403                                 "(%d):0311 Mailbox command x%x cannot "
9404                                 "issue Data: x%x x%x\n",
9405                                 pmbox->vport ? pmbox->vport->vpi : 0,
9406                                 pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9407                 goto out_not_finished;
9408         }
9409
9410         if (mbx->mbxCommand != MBX_KILL_BOARD && flag & MBX_NOWAIT) {
9411                 if (lpfc_readl(phba->HCregaddr, &hc_copy) ||
9412                         !(hc_copy & HC_MBINT_ENA)) {
9413                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9414                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9415                                 "(%d):2528 Mailbox command x%x cannot "
9416                                 "issue Data: x%x x%x\n",
9417                                 pmbox->vport ? pmbox->vport->vpi : 0,
9418                                 pmbox->u.mb.mbxCommand, psli->sli_flag, flag);
9419                         goto out_not_finished;
9420                 }
9421         }
9422
9423         if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9424                 /* Polling for a mbox command when another one is already active
9425                  * is not allowed in SLI. Also, the driver must have established
9426                  * SLI2 mode to queue and process multiple mbox commands.
9427                  */
9428
9429                 if (flag & MBX_POLL) {
9430                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9431
9432                         /* Mbox command <mbxCommand> cannot issue */
9433                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9434                                         "(%d):2529 Mailbox command x%x "
9435                                         "cannot issue Data: x%x x%x\n",
9436                                         pmbox->vport ? pmbox->vport->vpi : 0,
9437                                         pmbox->u.mb.mbxCommand,
9438                                         psli->sli_flag, flag);
9439                         goto out_not_finished;
9440                 }
9441
9442                 if (!(psli->sli_flag & LPFC_SLI_ACTIVE)) {
9443                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9444                         /* Mbox command <mbxCommand> cannot issue */
9445                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9446                                         "(%d):2530 Mailbox command x%x "
9447                                         "cannot issue Data: x%x x%x\n",
9448                                         pmbox->vport ? pmbox->vport->vpi : 0,
9449                                         pmbox->u.mb.mbxCommand,
9450                                         psli->sli_flag, flag);
9451                         goto out_not_finished;
9452                 }
9453
9454                 /* Another mailbox command is still being processed, queue this
9455                  * command to be processed later.
9456                  */
9457                 lpfc_mbox_put(phba, pmbox);
9458
9459                 /* Mbox cmd issue - BUSY */
9460                 lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9461                                 "(%d):0308 Mbox cmd issue - BUSY Data: "
9462                                 "x%x x%x x%x x%x\n",
9463                                 pmbox->vport ? pmbox->vport->vpi : 0xffffff,
9464                                 mbx->mbxCommand,
9465                                 phba->pport ? phba->pport->port_state : 0xff,
9466                                 psli->sli_flag, flag);
9467
9468                 psli->slistat.mbox_busy++;
9469                 spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9470
9471                 if (pmbox->vport) {
9472                         lpfc_debugfs_disc_trc(pmbox->vport,
9473                                 LPFC_DISC_TRC_MBOX_VPORT,
9474                                 "MBOX Bsy vport:  cmd:x%x mb:x%x x%x",
9475                                 (uint32_t)mbx->mbxCommand,
9476                                 mbx->un.varWords[0], mbx->un.varWords[1]);
9477                 }
9478                 else {
9479                         lpfc_debugfs_disc_trc(phba->pport,
9480                                 LPFC_DISC_TRC_MBOX,
9481                                 "MBOX Bsy:        cmd:x%x mb:x%x x%x",
9482                                 (uint32_t)mbx->mbxCommand,
9483                                 mbx->un.varWords[0], mbx->un.varWords[1]);
9484                 }
9485
9486                 return MBX_BUSY;
9487         }
9488
9489         psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9490
9491         /* If we are not polling, we MUST be in SLI2 mode */
9492         if (flag != MBX_POLL) {
9493                 if (!(psli->sli_flag & LPFC_SLI_ACTIVE) &&
9494                     (mbx->mbxCommand != MBX_KILL_BOARD)) {
9495                         psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9496                         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9497                         /* Mbox command <mbxCommand> cannot issue */
9498                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9499                                         "(%d):2531 Mailbox command x%x "
9500                                         "cannot issue Data: x%x x%x\n",
9501                                         pmbox->vport ? pmbox->vport->vpi : 0,
9502                                         pmbox->u.mb.mbxCommand,
9503                                         psli->sli_flag, flag);
9504                         goto out_not_finished;
9505                 }
9506                 /* timeout active mbox command */
9507                 timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9508                                            1000);
9509                 mod_timer(&psli->mbox_tmo, jiffies + timeout);
9510         }
9511
9512         /* Mailbox cmd <cmd> issue */
9513         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
9514                         "(%d):0309 Mailbox cmd x%x issue Data: x%x x%x "
9515                         "x%x\n",
9516                         pmbox->vport ? pmbox->vport->vpi : 0,
9517                         mbx->mbxCommand,
9518                         phba->pport ? phba->pport->port_state : 0xff,
9519                         psli->sli_flag, flag);
9520
9521         if (mbx->mbxCommand != MBX_HEARTBEAT) {
9522                 if (pmbox->vport) {
9523                         lpfc_debugfs_disc_trc(pmbox->vport,
9524                                 LPFC_DISC_TRC_MBOX_VPORT,
9525                                 "MBOX Send vport: cmd:x%x mb:x%x x%x",
9526                                 (uint32_t)mbx->mbxCommand,
9527                                 mbx->un.varWords[0], mbx->un.varWords[1]);
9528                 }
9529                 else {
9530                         lpfc_debugfs_disc_trc(phba->pport,
9531                                 LPFC_DISC_TRC_MBOX,
9532                                 "MBOX Send:       cmd:x%x mb:x%x x%x",
9533                                 (uint32_t)mbx->mbxCommand,
9534                                 mbx->un.varWords[0], mbx->un.varWords[1]);
9535                 }
9536         }
9537
9538         psli->slistat.mbox_cmd++;
9539         evtctr = psli->slistat.mbox_event;
9540
9541         /* next set own bit for the adapter and copy over command word */
9542         mbx->mbxOwner = OWN_CHIP;
9543
9544         if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9545                 /* Populate mbox extension offset word. */
9546                 if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len) {
9547                         *(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9548                                 = (uint8_t *)phba->mbox_ext
9549                                   - (uint8_t *)phba->mbox;
9550                 }
9551
9552                 /* Copy the mailbox extension data */
9553                 if (pmbox->in_ext_byte_len && pmbox->ext_buf) {
9554                         lpfc_sli_pcimem_bcopy(pmbox->ext_buf,
9555                                               (uint8_t *)phba->mbox_ext,
9556                                               pmbox->in_ext_byte_len);
9557                 }
9558                 /* Copy command data to host SLIM area */
9559                 lpfc_sli_pcimem_bcopy(mbx, phba->mbox, MAILBOX_CMD_SIZE);
9560         } else {
9561                 /* Populate mbox extension offset word. */
9562                 if (pmbox->in_ext_byte_len || pmbox->out_ext_byte_len)
9563                         *(((uint32_t *)mbx) + pmbox->mbox_offset_word)
9564                                 = MAILBOX_HBA_EXT_OFFSET;
9565
9566                 /* Copy the mailbox extension data */
9567                 if (pmbox->in_ext_byte_len && pmbox->ext_buf)
9568                         lpfc_memcpy_to_slim(phba->MBslimaddr +
9569                                 MAILBOX_HBA_EXT_OFFSET,
9570                                 pmbox->ext_buf, pmbox->in_ext_byte_len);
9571
9572                 if (mbx->mbxCommand == MBX_CONFIG_PORT)
9573                         /* copy command data into host mbox for cmpl */
9574                         lpfc_sli_pcimem_bcopy(mbx, phba->mbox,
9575                                               MAILBOX_CMD_SIZE);
9576
9577                 /* First copy mbox command data to HBA SLIM, skip past first
9578                    word */
9579                 to_slim = phba->MBslimaddr + sizeof (uint32_t);
9580                 lpfc_memcpy_to_slim(to_slim, &mbx->un.varWords[0],
9581                             MAILBOX_CMD_SIZE - sizeof (uint32_t));
9582
9583                 /* Next copy over first word, with mbxOwner set */
9584                 ldata = *((uint32_t *)mbx);
9585                 to_slim = phba->MBslimaddr;
9586                 writel(ldata, to_slim);
9587                 readl(to_slim); /* flush */
9588
9589                 if (mbx->mbxCommand == MBX_CONFIG_PORT)
9590                         /* switch over to host mailbox */
9591                         psli->sli_flag |= LPFC_SLI_ACTIVE;
9592         }
9593
9594         wmb();
9595
9596         switch (flag) {
9597         case MBX_NOWAIT:
9598                 /* Set up reference to mailbox command */
9599                 psli->mbox_active = pmbox;
9600                 /* Interrupt board to do it */
9601                 writel(CA_MBATT, phba->CAregaddr);
9602                 readl(phba->CAregaddr); /* flush */
9603                 /* Don't wait for it to finish, just return */
9604                 break;
9605
9606         case MBX_POLL:
9607                 /* Set up null reference to mailbox command */
9608                 psli->mbox_active = NULL;
9609                 /* Interrupt board to do it */
9610                 writel(CA_MBATT, phba->CAregaddr);
9611                 readl(phba->CAregaddr); /* flush */
9612
9613                 if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9614                         /* First read mbox status word */
9615                         word0 = *((uint32_t *)phba->mbox);
9616                         word0 = le32_to_cpu(word0);
9617                 } else {
9618                         /* First read mbox status word */
9619                         if (lpfc_readl(phba->MBslimaddr, &word0)) {
9620                                 spin_unlock_irqrestore(&phba->hbalock,
9621                                                        drvr_flag);
9622                                 goto out_not_finished;
9623                         }
9624                 }
9625
9626                 /* Read the HBA Host Attention Register */
9627                 if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9628                         spin_unlock_irqrestore(&phba->hbalock,
9629                                                        drvr_flag);
9630                         goto out_not_finished;
9631                 }
9632                 timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, pmbox) *
9633                                                         1000) + jiffies;
9634                 i = 0;
9635                 /* Wait for command to complete */
9636                 while (((word0 & OWN_CHIP) == OWN_CHIP) ||
9637                        (!(ha_copy & HA_MBATT) &&
9638                         (phba->link_state > LPFC_WARM_START))) {
9639                         if (time_after(jiffies, timeout)) {
9640                                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9641                                 spin_unlock_irqrestore(&phba->hbalock,
9642                                                        drvr_flag);
9643                                 goto out_not_finished;
9644                         }
9645
9646                         /* Check if we took a mbox interrupt while we were
9647                            polling */
9648                         if (((word0 & OWN_CHIP) != OWN_CHIP)
9649                             && (evtctr != psli->slistat.mbox_event))
9650                                 break;
9651
9652                         if (i++ > 10) {
9653                                 spin_unlock_irqrestore(&phba->hbalock,
9654                                                        drvr_flag);
9655                                 msleep(1);
9656                                 spin_lock_irqsave(&phba->hbalock, drvr_flag);
9657                         }
9658
9659                         if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9660                                 /* First copy command data */
9661                                 word0 = *((uint32_t *)phba->mbox);
9662                                 word0 = le32_to_cpu(word0);
9663                                 if (mbx->mbxCommand == MBX_CONFIG_PORT) {
9664                                         MAILBOX_t *slimmb;
9665                                         uint32_t slimword0;
9666                                         /* Check real SLIM for any errors */
9667                                         slimword0 = readl(phba->MBslimaddr);
9668                                         slimmb = (MAILBOX_t *) & slimword0;
9669                                         if (((slimword0 & OWN_CHIP) != OWN_CHIP)
9670                                             && slimmb->mbxStatus) {
9671                                                 psli->sli_flag &=
9672                                                     ~LPFC_SLI_ACTIVE;
9673                                                 word0 = slimword0;
9674                                         }
9675                                 }
9676                         } else {
9677                                 /* First copy command data */
9678                                 word0 = readl(phba->MBslimaddr);
9679                         }
9680                         /* Read the HBA Host Attention Register */
9681                         if (lpfc_readl(phba->HAregaddr, &ha_copy)) {
9682                                 spin_unlock_irqrestore(&phba->hbalock,
9683                                                        drvr_flag);
9684                                 goto out_not_finished;
9685                         }
9686                 }
9687
9688                 if (psli->sli_flag & LPFC_SLI_ACTIVE) {
9689                         /* copy results back to user */
9690                         lpfc_sli_pcimem_bcopy(phba->mbox, mbx,
9691                                                 MAILBOX_CMD_SIZE);
9692                         /* Copy the mailbox extension data */
9693                         if (pmbox->out_ext_byte_len && pmbox->ext_buf) {
9694                                 lpfc_sli_pcimem_bcopy(phba->mbox_ext,
9695                                                       pmbox->ext_buf,
9696                                                       pmbox->out_ext_byte_len);
9697                         }
9698                 } else {
9699                         /* First copy command data */
9700                         lpfc_memcpy_from_slim(mbx, phba->MBslimaddr,
9701                                                 MAILBOX_CMD_SIZE);
9702                         /* Copy the mailbox extension data */
9703                         if (pmbox->out_ext_byte_len && pmbox->ext_buf) {
9704                                 lpfc_memcpy_from_slim(
9705                                         pmbox->ext_buf,
9706                                         phba->MBslimaddr +
9707                                         MAILBOX_HBA_EXT_OFFSET,
9708                                         pmbox->out_ext_byte_len);
9709                         }
9710                 }
9711
9712                 writel(HA_MBATT, phba->HAregaddr);
9713                 readl(phba->HAregaddr); /* flush */
9714
9715                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
9716                 status = mbx->mbxStatus;
9717         }
9718
9719         spin_unlock_irqrestore(&phba->hbalock, drvr_flag);
9720         return status;
9721
9722 out_not_finished:
9723         if (processing_queue) {
9724                 pmbox->u.mb.mbxStatus = MBX_NOT_FINISHED;
9725                 lpfc_mbox_cmpl_put(phba, pmbox);
9726         }
9727         return MBX_NOT_FINISHED;
9728 }
9729
9730 /**
9731  * lpfc_sli4_async_mbox_block - Block posting SLI4 asynchronous mailbox command
9732  * @phba: Pointer to HBA context object.
9733  *
9734  * The function blocks the posting of SLI4 asynchronous mailbox commands from
9735  * the driver internal pending mailbox queue. It will then try to wait out the
9736  * possible outstanding mailbox command before return.
9737  *
9738  * Returns:
9739  *      0 - the outstanding mailbox command completed; otherwise, the wait for
9740  *      the outstanding mailbox command timed out.
9741  **/
9742 static int
9743 lpfc_sli4_async_mbox_block(struct lpfc_hba *phba)
9744 {
9745         struct lpfc_sli *psli = &phba->sli;
9746         LPFC_MBOXQ_t *mboxq;
9747         int rc = 0;
9748         unsigned long timeout = 0;
9749         u32 sli_flag;
9750         u8 cmd, subsys, opcode;
9751
9752         /* Mark the asynchronous mailbox command posting as blocked */
9753         spin_lock_irq(&phba->hbalock);
9754         psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
9755         /* Determine how long we might wait for the active mailbox
9756          * command to be gracefully completed by firmware.
9757          */
9758         if (phba->sli.mbox_active)
9759                 timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
9760                                                 phba->sli.mbox_active) *
9761                                                 1000) + jiffies;
9762         spin_unlock_irq(&phba->hbalock);
9763
9764         /* Make sure the mailbox is really active */
9765         if (timeout)
9766                 lpfc_sli4_process_missed_mbox_completions(phba);
9767
9768         /* Wait for the outstanding mailbox command to complete */
9769         while (phba->sli.mbox_active) {
9770                 /* Check active mailbox complete status every 2ms */
9771                 msleep(2);
9772                 if (time_after(jiffies, timeout)) {
9773                         /* Timeout, mark the outstanding cmd not complete */
9774
9775                         /* Sanity check sli.mbox_active has not completed or
9776                          * cancelled from another context during last 2ms sleep,
9777                          * so take hbalock to be sure before logging.
9778                          */
9779                         spin_lock_irq(&phba->hbalock);
9780                         if (phba->sli.mbox_active) {
9781                                 mboxq = phba->sli.mbox_active;
9782                                 cmd = mboxq->u.mb.mbxCommand;
9783                                 subsys = lpfc_sli_config_mbox_subsys_get(phba,
9784                                                                          mboxq);
9785                                 opcode = lpfc_sli_config_mbox_opcode_get(phba,
9786                                                                          mboxq);
9787                                 sli_flag = psli->sli_flag;
9788                                 spin_unlock_irq(&phba->hbalock);
9789                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9790                                                 "2352 Mailbox command x%x "
9791                                                 "(x%x/x%x) sli_flag x%x could "
9792                                                 "not complete\n",
9793                                                 cmd, subsys, opcode,
9794                                                 sli_flag);
9795                         } else {
9796                                 spin_unlock_irq(&phba->hbalock);
9797                         }
9798
9799                         rc = 1;
9800                         break;
9801                 }
9802         }
9803
9804         /* Can not cleanly block async mailbox command, fails it */
9805         if (rc) {
9806                 spin_lock_irq(&phba->hbalock);
9807                 psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9808                 spin_unlock_irq(&phba->hbalock);
9809         }
9810         return rc;
9811 }
9812
9813 /**
9814  * lpfc_sli4_async_mbox_unblock - Block posting SLI4 async mailbox command
9815  * @phba: Pointer to HBA context object.
9816  *
9817  * The function unblocks and resume posting of SLI4 asynchronous mailbox
9818  * commands from the driver internal pending mailbox queue. It makes sure
9819  * that there is no outstanding mailbox command before resuming posting
9820  * asynchronous mailbox commands. If, for any reason, there is outstanding
9821  * mailbox command, it will try to wait it out before resuming asynchronous
9822  * mailbox command posting.
9823  **/
9824 static void
9825 lpfc_sli4_async_mbox_unblock(struct lpfc_hba *phba)
9826 {
9827         struct lpfc_sli *psli = &phba->sli;
9828
9829         spin_lock_irq(&phba->hbalock);
9830         if (!(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
9831                 /* Asynchronous mailbox posting is not blocked, do nothing */
9832                 spin_unlock_irq(&phba->hbalock);
9833                 return;
9834         }
9835
9836         /* Outstanding synchronous mailbox command is guaranteed to be done,
9837          * successful or timeout, after timing-out the outstanding mailbox
9838          * command shall always be removed, so just unblock posting async
9839          * mailbox command and resume
9840          */
9841         psli->sli_flag &= ~LPFC_SLI_ASYNC_MBX_BLK;
9842         spin_unlock_irq(&phba->hbalock);
9843
9844         /* wake up worker thread to post asynchronous mailbox command */
9845         lpfc_worker_wake_up(phba);
9846 }
9847
9848 /**
9849  * lpfc_sli4_wait_bmbx_ready - Wait for bootstrap mailbox register ready
9850  * @phba: Pointer to HBA context object.
9851  * @mboxq: Pointer to mailbox object.
9852  *
9853  * The function waits for the bootstrap mailbox register ready bit from
9854  * port for twice the regular mailbox command timeout value.
9855  *
9856  *      0 - no timeout on waiting for bootstrap mailbox register ready.
9857  *      MBXERR_ERROR - wait for bootstrap mailbox register timed out or port
9858  *                     is in an unrecoverable state.
9859  **/
9860 static int
9861 lpfc_sli4_wait_bmbx_ready(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9862 {
9863         uint32_t db_ready;
9864         unsigned long timeout;
9865         struct lpfc_register bmbx_reg;
9866         struct lpfc_register portstat_reg = {-1};
9867
9868         /* Sanity check - there is no point to wait if the port is in an
9869          * unrecoverable state.
9870          */
9871         if (bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf) >=
9872             LPFC_SLI_INTF_IF_TYPE_2) {
9873                 if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
9874                                &portstat_reg.word0) ||
9875                     lpfc_sli4_unrecoverable_port(&portstat_reg)) {
9876                         lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
9877                                         "3858 Skipping bmbx ready because "
9878                                         "Port Status x%x\n",
9879                                         portstat_reg.word0);
9880                         return MBXERR_ERROR;
9881                 }
9882         }
9883
9884         timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba, mboxq)
9885                                    * 1000) + jiffies;
9886
9887         do {
9888                 bmbx_reg.word0 = readl(phba->sli4_hba.BMBXregaddr);
9889                 db_ready = bf_get(lpfc_bmbx_rdy, &bmbx_reg);
9890                 if (!db_ready)
9891                         mdelay(2);
9892
9893                 if (time_after(jiffies, timeout))
9894                         return MBXERR_ERROR;
9895         } while (!db_ready);
9896
9897         return 0;
9898 }
9899
9900 /**
9901  * lpfc_sli4_post_sync_mbox - Post an SLI4 mailbox to the bootstrap mailbox
9902  * @phba: Pointer to HBA context object.
9903  * @mboxq: Pointer to mailbox object.
9904  *
9905  * The function posts a mailbox to the port.  The mailbox is expected
9906  * to be comletely filled in and ready for the port to operate on it.
9907  * This routine executes a synchronous completion operation on the
9908  * mailbox by polling for its completion.
9909  *
9910  * The caller must not be holding any locks when calling this routine.
9911  *
9912  * Returns:
9913  *      MBX_SUCCESS - mailbox posted successfully
9914  *      Any of the MBX error values.
9915  **/
9916 static int
9917 lpfc_sli4_post_sync_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
9918 {
9919         int rc = MBX_SUCCESS;
9920         unsigned long iflag;
9921         uint32_t mcqe_status;
9922         uint32_t mbx_cmnd;
9923         struct lpfc_sli *psli = &phba->sli;
9924         struct lpfc_mqe *mb = &mboxq->u.mqe;
9925         struct lpfc_bmbx_create *mbox_rgn;
9926         struct dma_address *dma_address;
9927
9928         /*
9929          * Only one mailbox can be active to the bootstrap mailbox region
9930          * at a time and there is no queueing provided.
9931          */
9932         spin_lock_irqsave(&phba->hbalock, iflag);
9933         if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
9934                 spin_unlock_irqrestore(&phba->hbalock, iflag);
9935                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
9936                                 "(%d):2532 Mailbox command x%x (x%x/x%x) "
9937                                 "cannot issue Data: x%x x%x\n",
9938                                 mboxq->vport ? mboxq->vport->vpi : 0,
9939                                 mboxq->u.mb.mbxCommand,
9940                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
9941                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
9942                                 psli->sli_flag, MBX_POLL);
9943                 return MBXERR_ERROR;
9944         }
9945         /* The server grabs the token and owns it until release */
9946         psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
9947         phba->sli.mbox_active = mboxq;
9948         spin_unlock_irqrestore(&phba->hbalock, iflag);
9949
9950         /* wait for bootstrap mbox register for readyness */
9951         rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9952         if (rc)
9953                 goto exit;
9954         /*
9955          * Initialize the bootstrap memory region to avoid stale data areas
9956          * in the mailbox post.  Then copy the caller's mailbox contents to
9957          * the bmbx mailbox region.
9958          */
9959         mbx_cmnd = bf_get(lpfc_mqe_command, mb);
9960         memset(phba->sli4_hba.bmbx.avirt, 0, sizeof(struct lpfc_bmbx_create));
9961         lpfc_sli4_pcimem_bcopy(mb, phba->sli4_hba.bmbx.avirt,
9962                                sizeof(struct lpfc_mqe));
9963
9964         /* Post the high mailbox dma address to the port and wait for ready. */
9965         dma_address = &phba->sli4_hba.bmbx.dma_address;
9966         writel(dma_address->addr_hi, phba->sli4_hba.BMBXregaddr);
9967
9968         /* wait for bootstrap mbox register for hi-address write done */
9969         rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9970         if (rc)
9971                 goto exit;
9972
9973         /* Post the low mailbox dma address to the port. */
9974         writel(dma_address->addr_lo, phba->sli4_hba.BMBXregaddr);
9975
9976         /* wait for bootstrap mbox register for low address write done */
9977         rc = lpfc_sli4_wait_bmbx_ready(phba, mboxq);
9978         if (rc)
9979                 goto exit;
9980
9981         /*
9982          * Read the CQ to ensure the mailbox has completed.
9983          * If so, update the mailbox status so that the upper layers
9984          * can complete the request normally.
9985          */
9986         lpfc_sli4_pcimem_bcopy(phba->sli4_hba.bmbx.avirt, mb,
9987                                sizeof(struct lpfc_mqe));
9988         mbox_rgn = (struct lpfc_bmbx_create *) phba->sli4_hba.bmbx.avirt;
9989         lpfc_sli4_pcimem_bcopy(&mbox_rgn->mcqe, &mboxq->mcqe,
9990                                sizeof(struct lpfc_mcqe));
9991         mcqe_status = bf_get(lpfc_mcqe_status, &mbox_rgn->mcqe);
9992         /*
9993          * When the CQE status indicates a failure and the mailbox status
9994          * indicates success then copy the CQE status into the mailbox status
9995          * (and prefix it with x4000).
9996          */
9997         if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
9998                 if (bf_get(lpfc_mqe_status, mb) == MBX_SUCCESS)
9999                         bf_set(lpfc_mqe_status, mb,
10000                                (LPFC_MBX_ERROR_RANGE | mcqe_status));
10001                 rc = MBXERR_ERROR;
10002         } else
10003                 lpfc_sli4_swap_str(phba, mboxq);
10004
10005         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10006                         "(%d):0356 Mailbox cmd x%x (x%x/x%x) Status x%x "
10007                         "Data: x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x x%x"
10008                         " x%x x%x CQ: x%x x%x x%x x%x\n",
10009                         mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10010                         lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10011                         lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10012                         bf_get(lpfc_mqe_status, mb),
10013                         mb->un.mb_words[0], mb->un.mb_words[1],
10014                         mb->un.mb_words[2], mb->un.mb_words[3],
10015                         mb->un.mb_words[4], mb->un.mb_words[5],
10016                         mb->un.mb_words[6], mb->un.mb_words[7],
10017                         mb->un.mb_words[8], mb->un.mb_words[9],
10018                         mb->un.mb_words[10], mb->un.mb_words[11],
10019                         mb->un.mb_words[12], mboxq->mcqe.word0,
10020                         mboxq->mcqe.mcqe_tag0,  mboxq->mcqe.mcqe_tag1,
10021                         mboxq->mcqe.trailer);
10022 exit:
10023         /* We are holding the token, no needed for lock when release */
10024         spin_lock_irqsave(&phba->hbalock, iflag);
10025         psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10026         phba->sli.mbox_active = NULL;
10027         spin_unlock_irqrestore(&phba->hbalock, iflag);
10028         return rc;
10029 }
10030
10031 /**
10032  * lpfc_sli_issue_mbox_s4 - Issue an SLI4 mailbox command to firmware
10033  * @phba: Pointer to HBA context object.
10034  * @mboxq: Pointer to mailbox object.
10035  * @flag: Flag indicating how the mailbox need to be processed.
10036  *
10037  * This function is called by discovery code and HBA management code to submit
10038  * a mailbox command to firmware with SLI-4 interface spec.
10039  *
10040  * Return codes the caller owns the mailbox command after the return of the
10041  * function.
10042  **/
10043 static int
10044 lpfc_sli_issue_mbox_s4(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq,
10045                        uint32_t flag)
10046 {
10047         struct lpfc_sli *psli = &phba->sli;
10048         unsigned long iflags;
10049         int rc;
10050
10051         /* dump from issue mailbox command if setup */
10052         lpfc_idiag_mbxacc_dump_issue_mbox(phba, &mboxq->u.mb);
10053
10054         rc = lpfc_mbox_dev_check(phba);
10055         if (unlikely(rc)) {
10056                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10057                                 "(%d):2544 Mailbox command x%x (x%x/x%x) "
10058                                 "cannot issue Data: x%x x%x\n",
10059                                 mboxq->vport ? mboxq->vport->vpi : 0,
10060                                 mboxq->u.mb.mbxCommand,
10061                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10062                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10063                                 psli->sli_flag, flag);
10064                 goto out_not_finished;
10065         }
10066
10067         /* Detect polling mode and jump to a handler */
10068         if (!phba->sli4_hba.intr_enable) {
10069                 if (flag == MBX_POLL)
10070                         rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10071                 else
10072                         rc = -EIO;
10073                 if (rc != MBX_SUCCESS)
10074                         lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10075                                         "(%d):2541 Mailbox command x%x "
10076                                         "(x%x/x%x) failure: "
10077                                         "mqe_sta: x%x mcqe_sta: x%x/x%x "
10078                                         "Data: x%x x%x\n",
10079                                         mboxq->vport ? mboxq->vport->vpi : 0,
10080                                         mboxq->u.mb.mbxCommand,
10081                                         lpfc_sli_config_mbox_subsys_get(phba,
10082                                                                         mboxq),
10083                                         lpfc_sli_config_mbox_opcode_get(phba,
10084                                                                         mboxq),
10085                                         bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10086                                         bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10087                                         bf_get(lpfc_mcqe_ext_status,
10088                                                &mboxq->mcqe),
10089                                         psli->sli_flag, flag);
10090                 return rc;
10091         } else if (flag == MBX_POLL) {
10092                 lpfc_printf_log(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
10093                                 "(%d):2542 Try to issue mailbox command "
10094                                 "x%x (x%x/x%x) synchronously ahead of async "
10095                                 "mailbox command queue: x%x x%x\n",
10096                                 mboxq->vport ? mboxq->vport->vpi : 0,
10097                                 mboxq->u.mb.mbxCommand,
10098                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10099                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10100                                 psli->sli_flag, flag);
10101                 /* Try to block the asynchronous mailbox posting */
10102                 rc = lpfc_sli4_async_mbox_block(phba);
10103                 if (!rc) {
10104                         /* Successfully blocked, now issue sync mbox cmd */
10105                         rc = lpfc_sli4_post_sync_mbox(phba, mboxq);
10106                         if (rc != MBX_SUCCESS)
10107                                 lpfc_printf_log(phba, KERN_WARNING,
10108                                         LOG_MBOX | LOG_SLI,
10109                                         "(%d):2597 Sync Mailbox command "
10110                                         "x%x (x%x/x%x) failure: "
10111                                         "mqe_sta: x%x mcqe_sta: x%x/x%x "
10112                                         "Data: x%x x%x\n",
10113                                         mboxq->vport ? mboxq->vport->vpi : 0,
10114                                         mboxq->u.mb.mbxCommand,
10115                                         lpfc_sli_config_mbox_subsys_get(phba,
10116                                                                         mboxq),
10117                                         lpfc_sli_config_mbox_opcode_get(phba,
10118                                                                         mboxq),
10119                                         bf_get(lpfc_mqe_status, &mboxq->u.mqe),
10120                                         bf_get(lpfc_mcqe_status, &mboxq->mcqe),
10121                                         bf_get(lpfc_mcqe_ext_status,
10122                                                &mboxq->mcqe),
10123                                         psli->sli_flag, flag);
10124                         /* Unblock the async mailbox posting afterward */
10125                         lpfc_sli4_async_mbox_unblock(phba);
10126                 }
10127                 return rc;
10128         }
10129
10130         /* Now, interrupt mode asynchronous mailbox command */
10131         rc = lpfc_mbox_cmd_check(phba, mboxq);
10132         if (rc) {
10133                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10134                                 "(%d):2543 Mailbox command x%x (x%x/x%x) "
10135                                 "cannot issue Data: x%x x%x\n",
10136                                 mboxq->vport ? mboxq->vport->vpi : 0,
10137                                 mboxq->u.mb.mbxCommand,
10138                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10139                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10140                                 psli->sli_flag, flag);
10141                 goto out_not_finished;
10142         }
10143
10144         /* Put the mailbox command to the driver internal FIFO */
10145         psli->slistat.mbox_busy++;
10146         spin_lock_irqsave(&phba->hbalock, iflags);
10147         lpfc_mbox_put(phba, mboxq);
10148         spin_unlock_irqrestore(&phba->hbalock, iflags);
10149         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10150                         "(%d):0354 Mbox cmd issue - Enqueue Data: "
10151                         "x%x (x%x/x%x) x%x x%x x%x x%x\n",
10152                         mboxq->vport ? mboxq->vport->vpi : 0xffffff,
10153                         bf_get(lpfc_mqe_command, &mboxq->u.mqe),
10154                         lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10155                         lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10156                         mboxq->u.mb.un.varUnregLogin.rpi,
10157                         phba->pport->port_state,
10158                         psli->sli_flag, MBX_NOWAIT);
10159         /* Wake up worker thread to transport mailbox command from head */
10160         lpfc_worker_wake_up(phba);
10161
10162         return MBX_BUSY;
10163
10164 out_not_finished:
10165         return MBX_NOT_FINISHED;
10166 }
10167
10168 /**
10169  * lpfc_sli4_post_async_mbox - Post an SLI4 mailbox command to device
10170  * @phba: Pointer to HBA context object.
10171  *
10172  * This function is called by worker thread to send a mailbox command to
10173  * SLI4 HBA firmware.
10174  *
10175  **/
10176 int
10177 lpfc_sli4_post_async_mbox(struct lpfc_hba *phba)
10178 {
10179         struct lpfc_sli *psli = &phba->sli;
10180         LPFC_MBOXQ_t *mboxq;
10181         int rc = MBX_SUCCESS;
10182         unsigned long iflags;
10183         struct lpfc_mqe *mqe;
10184         uint32_t mbx_cmnd;
10185
10186         /* Check interrupt mode before post async mailbox command */
10187         if (unlikely(!phba->sli4_hba.intr_enable))
10188                 return MBX_NOT_FINISHED;
10189
10190         /* Check for mailbox command service token */
10191         spin_lock_irqsave(&phba->hbalock, iflags);
10192         if (unlikely(psli->sli_flag & LPFC_SLI_ASYNC_MBX_BLK)) {
10193                 spin_unlock_irqrestore(&phba->hbalock, iflags);
10194                 return MBX_NOT_FINISHED;
10195         }
10196         if (psli->sli_flag & LPFC_SLI_MBOX_ACTIVE) {
10197                 spin_unlock_irqrestore(&phba->hbalock, iflags);
10198                 return MBX_NOT_FINISHED;
10199         }
10200         if (unlikely(phba->sli.mbox_active)) {
10201                 spin_unlock_irqrestore(&phba->hbalock, iflags);
10202                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10203                                 "0384 There is pending active mailbox cmd\n");
10204                 return MBX_NOT_FINISHED;
10205         }
10206         /* Take the mailbox command service token */
10207         psli->sli_flag |= LPFC_SLI_MBOX_ACTIVE;
10208
10209         /* Get the next mailbox command from head of queue */
10210         mboxq = lpfc_mbox_get(phba);
10211
10212         /* If no more mailbox command waiting for post, we're done */
10213         if (!mboxq) {
10214                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10215                 spin_unlock_irqrestore(&phba->hbalock, iflags);
10216                 return MBX_SUCCESS;
10217         }
10218         phba->sli.mbox_active = mboxq;
10219         spin_unlock_irqrestore(&phba->hbalock, iflags);
10220
10221         /* Check device readiness for posting mailbox command */
10222         rc = lpfc_mbox_dev_check(phba);
10223         if (unlikely(rc))
10224                 /* Driver clean routine will clean up pending mailbox */
10225                 goto out_not_finished;
10226
10227         /* Prepare the mbox command to be posted */
10228         mqe = &mboxq->u.mqe;
10229         mbx_cmnd = bf_get(lpfc_mqe_command, mqe);
10230
10231         /* Start timer for the mbox_tmo and log some mailbox post messages */
10232         mod_timer(&psli->mbox_tmo, (jiffies +
10233                   msecs_to_jiffies(1000 * lpfc_mbox_tmo_val(phba, mboxq))));
10234
10235         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
10236                         "(%d):0355 Mailbox cmd x%x (x%x/x%x) issue Data: "
10237                         "x%x x%x\n",
10238                         mboxq->vport ? mboxq->vport->vpi : 0, mbx_cmnd,
10239                         lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10240                         lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10241                         phba->pport->port_state, psli->sli_flag);
10242
10243         if (mbx_cmnd != MBX_HEARTBEAT) {
10244                 if (mboxq->vport) {
10245                         lpfc_debugfs_disc_trc(mboxq->vport,
10246                                 LPFC_DISC_TRC_MBOX_VPORT,
10247                                 "MBOX Send vport: cmd:x%x mb:x%x x%x",
10248                                 mbx_cmnd, mqe->un.mb_words[0],
10249                                 mqe->un.mb_words[1]);
10250                 } else {
10251                         lpfc_debugfs_disc_trc(phba->pport,
10252                                 LPFC_DISC_TRC_MBOX,
10253                                 "MBOX Send: cmd:x%x mb:x%x x%x",
10254                                 mbx_cmnd, mqe->un.mb_words[0],
10255                                 mqe->un.mb_words[1]);
10256                 }
10257         }
10258         psli->slistat.mbox_cmd++;
10259
10260         /* Post the mailbox command to the port */
10261         rc = lpfc_sli4_mq_put(phba->sli4_hba.mbx_wq, mqe);
10262         if (rc != MBX_SUCCESS) {
10263                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10264                                 "(%d):2533 Mailbox command x%x (x%x/x%x) "
10265                                 "cannot issue Data: x%x x%x\n",
10266                                 mboxq->vport ? mboxq->vport->vpi : 0,
10267                                 mboxq->u.mb.mbxCommand,
10268                                 lpfc_sli_config_mbox_subsys_get(phba, mboxq),
10269                                 lpfc_sli_config_mbox_opcode_get(phba, mboxq),
10270                                 psli->sli_flag, MBX_NOWAIT);
10271                 goto out_not_finished;
10272         }
10273
10274         return rc;
10275
10276 out_not_finished:
10277         spin_lock_irqsave(&phba->hbalock, iflags);
10278         if (phba->sli.mbox_active) {
10279                 mboxq->u.mb.mbxStatus = MBX_NOT_FINISHED;
10280                 __lpfc_mbox_cmpl_put(phba, mboxq);
10281                 /* Release the token */
10282                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
10283                 phba->sli.mbox_active = NULL;
10284         }
10285         spin_unlock_irqrestore(&phba->hbalock, iflags);
10286
10287         return MBX_NOT_FINISHED;
10288 }
10289
10290 /**
10291  * lpfc_sli_issue_mbox - Wrapper func for issuing mailbox command
10292  * @phba: Pointer to HBA context object.
10293  * @pmbox: Pointer to mailbox object.
10294  * @flag: Flag indicating how the mailbox need to be processed.
10295  *
10296  * This routine wraps the actual SLI3 or SLI4 mailbox issuing routine from
10297  * the API jump table function pointer from the lpfc_hba struct.
10298  *
10299  * Return codes the caller owns the mailbox command after the return of the
10300  * function.
10301  **/
10302 int
10303 lpfc_sli_issue_mbox(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmbox, uint32_t flag)
10304 {
10305         return phba->lpfc_sli_issue_mbox(phba, pmbox, flag);
10306 }
10307
10308 /**
10309  * lpfc_mbox_api_table_setup - Set up mbox api function jump table
10310  * @phba: The hba struct for which this call is being executed.
10311  * @dev_grp: The HBA PCI-Device group number.
10312  *
10313  * This routine sets up the mbox interface API function jump table in @phba
10314  * struct.
10315  * Returns: 0 - success, -ENODEV - failure.
10316  **/
10317 int
10318 lpfc_mbox_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
10319 {
10320
10321         switch (dev_grp) {
10322         case LPFC_PCI_DEV_LP:
10323                 phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s3;
10324                 phba->lpfc_sli_handle_slow_ring_event =
10325                                 lpfc_sli_handle_slow_ring_event_s3;
10326                 phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s3;
10327                 phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s3;
10328                 phba->lpfc_sli_brdready = lpfc_sli_brdready_s3;
10329                 break;
10330         case LPFC_PCI_DEV_OC:
10331                 phba->lpfc_sli_issue_mbox = lpfc_sli_issue_mbox_s4;
10332                 phba->lpfc_sli_handle_slow_ring_event =
10333                                 lpfc_sli_handle_slow_ring_event_s4;
10334                 phba->lpfc_sli_hbq_to_firmware = lpfc_sli_hbq_to_firmware_s4;
10335                 phba->lpfc_sli_brdrestart = lpfc_sli_brdrestart_s4;
10336                 phba->lpfc_sli_brdready = lpfc_sli_brdready_s4;
10337                 break;
10338         default:
10339                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
10340                                 "1420 Invalid HBA PCI-device group: 0x%x\n",
10341                                 dev_grp);
10342                 return -ENODEV;
10343         }
10344         return 0;
10345 }
10346
10347 /**
10348  * __lpfc_sli_ringtx_put - Add an iocb to the txq
10349  * @phba: Pointer to HBA context object.
10350  * @pring: Pointer to driver SLI ring object.
10351  * @piocb: Pointer to address of newly added command iocb.
10352  *
10353  * This function is called with hbalock held for SLI3 ports or
10354  * the ring lock held for SLI4 ports to add a command
10355  * iocb to the txq when SLI layer cannot submit the command iocb
10356  * to the ring.
10357  **/
10358 void
10359 __lpfc_sli_ringtx_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10360                     struct lpfc_iocbq *piocb)
10361 {
10362         if (phba->sli_rev == LPFC_SLI_REV4)
10363                 lockdep_assert_held(&pring->ring_lock);
10364         else
10365                 lockdep_assert_held(&phba->hbalock);
10366         /* Insert the caller's iocb in the txq tail for later processing. */
10367         list_add_tail(&piocb->list, &pring->txq);
10368 }
10369
10370 /**
10371  * lpfc_sli_next_iocb - Get the next iocb in the txq
10372  * @phba: Pointer to HBA context object.
10373  * @pring: Pointer to driver SLI ring object.
10374  * @piocb: Pointer to address of newly added command iocb.
10375  *
10376  * This function is called with hbalock held before a new
10377  * iocb is submitted to the firmware. This function checks
10378  * txq to flush the iocbs in txq to Firmware before
10379  * submitting new iocbs to the Firmware.
10380  * If there are iocbs in the txq which need to be submitted
10381  * to firmware, lpfc_sli_next_iocb returns the first element
10382  * of the txq after dequeuing it from txq.
10383  * If there is no iocb in the txq then the function will return
10384  * *piocb and *piocb is set to NULL. Caller needs to check
10385  * *piocb to find if there are more commands in the txq.
10386  **/
10387 static struct lpfc_iocbq *
10388 lpfc_sli_next_iocb(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
10389                    struct lpfc_iocbq **piocb)
10390 {
10391         struct lpfc_iocbq * nextiocb;
10392
10393         lockdep_assert_held(&phba->hbalock);
10394
10395         nextiocb = lpfc_sli_ringtx_get(phba, pring);
10396         if (!nextiocb) {
10397                 nextiocb = *piocb;
10398                 *piocb = NULL;
10399         }
10400
10401         return nextiocb;
10402 }
10403
10404 /**
10405  * __lpfc_sli_issue_iocb_s3 - SLI3 device lockless ver of lpfc_sli_issue_iocb
10406  * @phba: Pointer to HBA context object.
10407  * @ring_number: SLI ring number to issue iocb on.
10408  * @piocb: Pointer to command iocb.
10409  * @flag: Flag indicating if this command can be put into txq.
10410  *
10411  * __lpfc_sli_issue_iocb_s3 is used by other functions in the driver to issue
10412  * an iocb command to an HBA with SLI-3 interface spec. If the PCI slot is
10413  * recovering from error state, if HBA is resetting or if LPFC_STOP_IOCB_EVENT
10414  * flag is turned on, the function returns IOCB_ERROR. When the link is down,
10415  * this function allows only iocbs for posting buffers. This function finds
10416  * next available slot in the command ring and posts the command to the
10417  * available slot and writes the port attention register to request HBA start
10418  * processing new iocb. If there is no slot available in the ring and
10419  * flag & SLI_IOCB_RET_IOCB is set, the new iocb is added to the txq, otherwise
10420  * the function returns IOCB_BUSY.
10421  *
10422  * This function is called with hbalock held. The function will return success
10423  * after it successfully submit the iocb to firmware or after adding to the
10424  * txq.
10425  **/
10426 static int
10427 __lpfc_sli_issue_iocb_s3(struct lpfc_hba *phba, uint32_t ring_number,
10428                     struct lpfc_iocbq *piocb, uint32_t flag)
10429 {
10430         struct lpfc_iocbq *nextiocb;
10431         IOCB_t *iocb;
10432         struct lpfc_sli_ring *pring = &phba->sli.sli3_ring[ring_number];
10433
10434         lockdep_assert_held(&phba->hbalock);
10435
10436         if (piocb->cmd_cmpl && (!piocb->vport) &&
10437            (piocb->iocb.ulpCommand != CMD_ABORT_XRI_CN) &&
10438            (piocb->iocb.ulpCommand != CMD_CLOSE_XRI_CN)) {
10439                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
10440                                 "1807 IOCB x%x failed. No vport\n",
10441                                 piocb->iocb.ulpCommand);
10442                 dump_stack();
10443                 return IOCB_ERROR;
10444         }
10445
10446
10447         /* If the PCI channel is in offline state, do not post iocbs. */
10448         if (unlikely(pci_channel_offline(phba->pcidev)))
10449                 return IOCB_ERROR;
10450
10451         /* If HBA has a deferred error attention, fail the iocb. */
10452         if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag)))
10453                 return IOCB_ERROR;
10454
10455         /*
10456          * We should never get an IOCB if we are in a < LINK_DOWN state
10457          */
10458         if (unlikely(phba->link_state < LPFC_LINK_DOWN))
10459                 return IOCB_ERROR;
10460
10461         /*
10462          * Check to see if we are blocking IOCB processing because of a
10463          * outstanding event.
10464          */
10465         if (unlikely(pring->flag & LPFC_STOP_IOCB_EVENT))
10466                 goto iocb_busy;
10467
10468         if (unlikely(phba->link_state == LPFC_LINK_DOWN)) {
10469                 /*
10470                  * Only CREATE_XRI, CLOSE_XRI, and QUE_RING_BUF
10471                  * can be issued if the link is not up.
10472                  */
10473                 switch (piocb->iocb.ulpCommand) {
10474                 case CMD_QUE_RING_BUF_CN:
10475                 case CMD_QUE_RING_BUF64_CN:
10476                         /*
10477                          * For IOCBs, like QUE_RING_BUF, that have no rsp ring
10478                          * completion, cmd_cmpl MUST be 0.
10479                          */
10480                         if (piocb->cmd_cmpl)
10481                                 piocb->cmd_cmpl = NULL;
10482                         fallthrough;
10483                 case CMD_CREATE_XRI_CR:
10484                 case CMD_CLOSE_XRI_CN:
10485                 case CMD_CLOSE_XRI_CX:
10486                         break;
10487                 default:
10488                         goto iocb_busy;
10489                 }
10490
10491         /*
10492          * For FCP commands, we must be in a state where we can process link
10493          * attention events.
10494          */
10495         } else if (unlikely(pring->ringno == LPFC_FCP_RING &&
10496                             !(phba->sli.sli_flag & LPFC_PROCESS_LA))) {
10497                 goto iocb_busy;
10498         }
10499
10500         while ((iocb = lpfc_sli_next_iocb_slot(phba, pring)) &&
10501                (nextiocb = lpfc_sli_next_iocb(phba, pring, &piocb)))
10502                 lpfc_sli_submit_iocb(phba, pring, iocb, nextiocb);
10503
10504         if (iocb)
10505                 lpfc_sli_update_ring(phba, pring);
10506         else
10507                 lpfc_sli_update_full_ring(phba, pring);
10508
10509         if (!piocb)
10510                 return IOCB_SUCCESS;
10511
10512         goto out_busy;
10513
10514  iocb_busy:
10515         pring->stats.iocb_cmd_delay++;
10516
10517  out_busy:
10518
10519         if (!(flag & SLI_IOCB_RET_IOCB)) {
10520                 __lpfc_sli_ringtx_put(phba, pring, piocb);
10521                 return IOCB_SUCCESS;
10522         }
10523
10524         return IOCB_BUSY;
10525 }
10526
10527 /**
10528  * __lpfc_sli_issue_fcp_io_s3 - SLI3 device for sending fcp io iocb
10529  * @phba: Pointer to HBA context object.
10530  * @ring_number: SLI ring number to issue wqe on.
10531  * @piocb: Pointer to command iocb.
10532  * @flag: Flag indicating if this command can be put into txq.
10533  *
10534  * __lpfc_sli_issue_fcp_io_s3 is wrapper function to invoke lockless func to
10535  * send  an iocb command to an HBA with SLI-3 interface spec.
10536  *
10537  * This function takes the hbalock before invoking the lockless version.
10538  * The function will return success after it successfully submit the wqe to
10539  * firmware or after adding to the txq.
10540  **/
10541 static int
10542 __lpfc_sli_issue_fcp_io_s3(struct lpfc_hba *phba, uint32_t ring_number,
10543                            struct lpfc_iocbq *piocb, uint32_t flag)
10544 {
10545         unsigned long iflags;
10546         int rc;
10547
10548         spin_lock_irqsave(&phba->hbalock, iflags);
10549         rc = __lpfc_sli_issue_iocb_s3(phba, ring_number, piocb, flag);
10550         spin_unlock_irqrestore(&phba->hbalock, iflags);
10551
10552         return rc;
10553 }
10554
10555 /**
10556  * __lpfc_sli_issue_fcp_io_s4 - SLI4 device for sending fcp io wqe
10557  * @phba: Pointer to HBA context object.
10558  * @ring_number: SLI ring number to issue wqe on.
10559  * @piocb: Pointer to command iocb.
10560  * @flag: Flag indicating if this command can be put into txq.
10561  *
10562  * __lpfc_sli_issue_fcp_io_s4 is used by other functions in the driver to issue
10563  * an wqe command to an HBA with SLI-4 interface spec.
10564  *
10565  * This function is a lockless version. The function will return success
10566  * after it successfully submit the wqe to firmware or after adding to the
10567  * txq.
10568  **/
10569 static int
10570 __lpfc_sli_issue_fcp_io_s4(struct lpfc_hba *phba, uint32_t ring_number,
10571                            struct lpfc_iocbq *piocb, uint32_t flag)
10572 {
10573         struct lpfc_io_buf *lpfc_cmd = piocb->io_buf;
10574
10575         lpfc_prep_embed_io(phba, lpfc_cmd);
10576         return lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, piocb);
10577 }
10578
10579 void
10580 lpfc_prep_embed_io(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_cmd)
10581 {
10582         struct lpfc_iocbq *piocb = &lpfc_cmd->cur_iocbq;
10583         union lpfc_wqe128 *wqe = &lpfc_cmd->cur_iocbq.wqe;
10584         struct sli4_sge_le *sgl;
10585         u32 type_size;
10586
10587         /* 128 byte wqe support here */
10588         sgl = (struct sli4_sge_le *)lpfc_cmd->dma_sgl;
10589
10590         if (phba->fcp_embed_io) {
10591                 struct fcp_cmnd *fcp_cmnd;
10592                 u32 *ptr;
10593
10594                 fcp_cmnd = lpfc_cmd->fcp_cmnd;
10595
10596                 /* Word 0-2 - FCP_CMND */
10597                 type_size = le32_to_cpu(sgl->sge_len);
10598                 type_size |= ULP_BDE64_TYPE_BDE_IMMED;
10599                 wqe->generic.bde.tus.w = type_size;
10600                 wqe->generic.bde.addrHigh = 0;
10601                 wqe->generic.bde.addrLow =  72;  /* Word 18 */
10602
10603                 bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10604                 bf_set(wqe_dbde, &wqe->fcp_iwrite.wqe_com, 0);
10605
10606                 /* Word 18-29  FCP CMND Payload */
10607                 ptr = &wqe->words[18];
10608                 lpfc_sli_pcimem_bcopy(fcp_cmnd, ptr, le32_to_cpu(sgl->sge_len));
10609         } else {
10610                 /* Word 0-2 - Inline BDE */
10611                 wqe->generic.bde.tus.f.bdeFlags =  BUFF_TYPE_BDE_64;
10612                 wqe->generic.bde.tus.f.bdeSize = le32_to_cpu(sgl->sge_len);
10613                 wqe->generic.bde.addrHigh = le32_to_cpu(sgl->addr_hi);
10614                 wqe->generic.bde.addrLow = le32_to_cpu(sgl->addr_lo);
10615
10616                 /* Word 10 */
10617                 bf_set(wqe_dbde, &wqe->generic.wqe_com, 1);
10618                 bf_set(wqe_wqes, &wqe->generic.wqe_com, 0);
10619         }
10620
10621         /* add the VMID tags as per switch response */
10622         if (unlikely(piocb->cmd_flag & LPFC_IO_VMID)) {
10623                 if (phba->pport->vmid_flag & LPFC_VMID_TYPE_PRIO) {
10624                         bf_set(wqe_ccpe, &wqe->fcp_iwrite.wqe_com, 1);
10625                         bf_set(wqe_ccp, &wqe->fcp_iwrite.wqe_com,
10626                                         (piocb->vmid_tag.cs_ctl_vmid));
10627                 } else if (phba->cfg_vmid_app_header) {
10628                         bf_set(wqe_appid, &wqe->fcp_iwrite.wqe_com, 1);
10629                         bf_set(wqe_wqes, &wqe->fcp_iwrite.wqe_com, 1);
10630                         wqe->words[31] = piocb->vmid_tag.app_id;
10631                 }
10632         }
10633 }
10634
10635 /**
10636  * __lpfc_sli_issue_iocb_s4 - SLI4 device lockless ver of lpfc_sli_issue_iocb
10637  * @phba: Pointer to HBA context object.
10638  * @ring_number: SLI ring number to issue iocb on.
10639  * @piocb: Pointer to command iocb.
10640  * @flag: Flag indicating if this command can be put into txq.
10641  *
10642  * __lpfc_sli_issue_iocb_s4 is used by other functions in the driver to issue
10643  * an iocb command to an HBA with SLI-4 interface spec.
10644  *
10645  * This function is called with ringlock held. The function will return success
10646  * after it successfully submit the iocb to firmware or after adding to the
10647  * txq.
10648  **/
10649 static int
10650 __lpfc_sli_issue_iocb_s4(struct lpfc_hba *phba, uint32_t ring_number,
10651                          struct lpfc_iocbq *piocb, uint32_t flag)
10652 {
10653         struct lpfc_sglq *sglq;
10654         union lpfc_wqe128 *wqe;
10655         struct lpfc_queue *wq;
10656         struct lpfc_sli_ring *pring;
10657         u32 ulp_command = get_job_cmnd(phba, piocb);
10658
10659         /* Get the WQ */
10660         if ((piocb->cmd_flag & LPFC_IO_FCP) ||
10661             (piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
10662                 wq = phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq;
10663         } else {
10664                 wq = phba->sli4_hba.els_wq;
10665         }
10666
10667         /* Get corresponding ring */
10668         pring = wq->pring;
10669
10670         /*
10671          * The WQE can be either 64 or 128 bytes,
10672          */
10673
10674         lockdep_assert_held(&pring->ring_lock);
10675         wqe = &piocb->wqe;
10676         if (piocb->sli4_xritag == NO_XRI) {
10677                 if (ulp_command == CMD_ABORT_XRI_CX)
10678                         sglq = NULL;
10679                 else {
10680                         sglq = __lpfc_sli_get_els_sglq(phba, piocb);
10681                         if (!sglq) {
10682                                 if (!(flag & SLI_IOCB_RET_IOCB)) {
10683                                         __lpfc_sli_ringtx_put(phba,
10684                                                         pring,
10685                                                         piocb);
10686                                         return IOCB_SUCCESS;
10687                                 } else {
10688                                         return IOCB_BUSY;
10689                                 }
10690                         }
10691                 }
10692         } else if (piocb->cmd_flag &  LPFC_IO_FCP) {
10693                 /* These IO's already have an XRI and a mapped sgl. */
10694                 sglq = NULL;
10695         }
10696         else {
10697                 /*
10698                  * This is a continuation of a commandi,(CX) so this
10699                  * sglq is on the active list
10700                  */
10701                 sglq = __lpfc_get_active_sglq(phba, piocb->sli4_lxritag);
10702                 if (!sglq)
10703                         return IOCB_ERROR;
10704         }
10705
10706         if (sglq) {
10707                 piocb->sli4_lxritag = sglq->sli4_lxritag;
10708                 piocb->sli4_xritag = sglq->sli4_xritag;
10709
10710                 /* ABTS sent by initiator to CT exchange, the
10711                  * RX_ID field will be filled with the newly
10712                  * allocated responder XRI.
10713                  */
10714                 if (ulp_command == CMD_XMIT_BLS_RSP64_CX &&
10715                     piocb->abort_bls == LPFC_ABTS_UNSOL_INT)
10716                         bf_set(xmit_bls_rsp64_rxid, &wqe->xmit_bls_rsp,
10717                                piocb->sli4_xritag);
10718
10719                 bf_set(wqe_xri_tag, &wqe->generic.wqe_com,
10720                        piocb->sli4_xritag);
10721
10722                 if (lpfc_wqe_bpl2sgl(phba, piocb, sglq) == NO_XRI)
10723                         return IOCB_ERROR;
10724         }
10725
10726         if (lpfc_sli4_wq_put(wq, wqe))
10727                 return IOCB_ERROR;
10728
10729         lpfc_sli_ringtxcmpl_put(phba, pring, piocb);
10730
10731         return 0;
10732 }
10733
10734 /*
10735  * lpfc_sli_issue_fcp_io - Wrapper func for issuing fcp i/o
10736  *
10737  * This routine wraps the actual fcp i/o function for issusing WQE for sli-4
10738  * or IOCB for sli-3  function.
10739  * pointer from the lpfc_hba struct.
10740  *
10741  * Return codes:
10742  * IOCB_ERROR - Error
10743  * IOCB_SUCCESS - Success
10744  * IOCB_BUSY - Busy
10745  **/
10746 int
10747 lpfc_sli_issue_fcp_io(struct lpfc_hba *phba, uint32_t ring_number,
10748                       struct lpfc_iocbq *piocb, uint32_t flag)
10749 {
10750         return phba->__lpfc_sli_issue_fcp_io(phba, ring_number, piocb, flag);
10751 }
10752
10753 /*
10754  * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb
10755  *
10756  * This routine wraps the actual lockless version for issusing IOCB function
10757  * pointer from the lpfc_hba struct.
10758  *
10759  * Return codes:
10760  * IOCB_ERROR - Error
10761  * IOCB_SUCCESS - Success
10762  * IOCB_BUSY - Busy
10763  **/
10764 int
10765 __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
10766                 struct lpfc_iocbq *piocb, uint32_t flag)
10767 {
10768         return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
10769 }
10770
10771 static void
10772 __lpfc_sli_prep_els_req_rsp_s3(struct lpfc_iocbq *cmdiocbq,
10773                                struct lpfc_vport *vport,
10774                                struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10775                                u32 elscmd, u8 tmo, u8 expect_rsp)
10776 {
10777         struct lpfc_hba *phba = vport->phba;
10778         IOCB_t *cmd;
10779
10780         cmd = &cmdiocbq->iocb;
10781         memset(cmd, 0, sizeof(*cmd));
10782
10783         cmd->un.elsreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10784         cmd->un.elsreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10785         cmd->un.elsreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10786
10787         if (expect_rsp) {
10788                 cmd->un.elsreq64.bdl.bdeSize = (2 * sizeof(struct ulp_bde64));
10789                 cmd->un.elsreq64.remoteID = did; /* DID */
10790                 cmd->ulpCommand = CMD_ELS_REQUEST64_CR;
10791                 cmd->ulpTimeout = tmo;
10792         } else {
10793                 cmd->un.elsreq64.bdl.bdeSize = sizeof(struct ulp_bde64);
10794                 cmd->un.genreq64.xmit_els_remoteID = did; /* DID */
10795                 cmd->ulpCommand = CMD_XMIT_ELS_RSP64_CX;
10796                 cmd->ulpPU = PARM_NPIV_DID;
10797         }
10798         cmd->ulpBdeCount = 1;
10799         cmd->ulpLe = 1;
10800         cmd->ulpClass = CLASS3;
10801
10802         /* If we have NPIV enabled, we want to send ELS traffic by VPI. */
10803         if (phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) {
10804                 if (expect_rsp) {
10805                         cmd->un.elsreq64.myID = vport->fc_myDID;
10806
10807                         /* For ELS_REQUEST64_CR, use the VPI by default */
10808                         cmd->ulpContext = phba->vpi_ids[vport->vpi];
10809                 }
10810
10811                 cmd->ulpCt_h = 0;
10812                 /* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10813                 if (elscmd == ELS_CMD_ECHO)
10814                         cmd->ulpCt_l = 0; /* context = invalid RPI */
10815                 else
10816                         cmd->ulpCt_l = 1; /* context = VPI */
10817         }
10818 }
10819
10820 static void
10821 __lpfc_sli_prep_els_req_rsp_s4(struct lpfc_iocbq *cmdiocbq,
10822                                struct lpfc_vport *vport,
10823                                struct lpfc_dmabuf *bmp, u16 cmd_size, u32 did,
10824                                u32 elscmd, u8 tmo, u8 expect_rsp)
10825 {
10826         struct lpfc_hba  *phba = vport->phba;
10827         union lpfc_wqe128 *wqe;
10828         struct ulp_bde64_le *bde;
10829         u8 els_id;
10830
10831         wqe = &cmdiocbq->wqe;
10832         memset(wqe, 0, sizeof(*wqe));
10833
10834         /* Word 0 - 2 BDE */
10835         bde = (struct ulp_bde64_le *)&wqe->generic.bde;
10836         bde->addr_low = cpu_to_le32(putPaddrLow(bmp->phys));
10837         bde->addr_high = cpu_to_le32(putPaddrHigh(bmp->phys));
10838         bde->type_size = cpu_to_le32(cmd_size);
10839         bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10840
10841         if (expect_rsp) {
10842                 bf_set(wqe_cmnd, &wqe->els_req.wqe_com, CMD_ELS_REQUEST64_WQE);
10843
10844                 /* Transfer length */
10845                 wqe->els_req.payload_len = cmd_size;
10846                 wqe->els_req.max_response_payload_len = FCELSSIZE;
10847
10848                 /* DID */
10849                 bf_set(wqe_els_did, &wqe->els_req.wqe_dest, did);
10850
10851                 /* Word 11 - ELS_ID */
10852                 switch (elscmd) {
10853                 case ELS_CMD_PLOGI:
10854                         els_id = LPFC_ELS_ID_PLOGI;
10855                         break;
10856                 case ELS_CMD_FLOGI:
10857                         els_id = LPFC_ELS_ID_FLOGI;
10858                         break;
10859                 case ELS_CMD_LOGO:
10860                         els_id = LPFC_ELS_ID_LOGO;
10861                         break;
10862                 case ELS_CMD_FDISC:
10863                         if (!vport->fc_myDID) {
10864                                 els_id = LPFC_ELS_ID_FDISC;
10865                                 break;
10866                         }
10867                         fallthrough;
10868                 default:
10869                         els_id = LPFC_ELS_ID_DEFAULT;
10870                         break;
10871                 }
10872
10873                 bf_set(wqe_els_id, &wqe->els_req.wqe_com, els_id);
10874         } else {
10875                 /* DID */
10876                 bf_set(wqe_els_did, &wqe->xmit_els_rsp.wqe_dest, did);
10877
10878                 /* Transfer length */
10879                 wqe->xmit_els_rsp.response_payload_len = cmd_size;
10880
10881                 bf_set(wqe_cmnd, &wqe->xmit_els_rsp.wqe_com,
10882                        CMD_XMIT_ELS_RSP64_WQE);
10883         }
10884
10885         bf_set(wqe_tmo, &wqe->generic.wqe_com, tmo);
10886         bf_set(wqe_reqtag, &wqe->generic.wqe_com, cmdiocbq->iotag);
10887         bf_set(wqe_class, &wqe->generic.wqe_com, CLASS3);
10888
10889         /* If we have NPIV enabled, we want to send ELS traffic by VPI.
10890          * For SLI4, since the driver controls VPIs we also want to include
10891          * all ELS pt2pt protocol traffic as well.
10892          */
10893         if ((phba->sli3_options & LPFC_SLI3_NPIV_ENABLED) ||
10894             test_bit(FC_PT2PT, &vport->fc_flag)) {
10895                 if (expect_rsp) {
10896                         bf_set(els_req64_sid, &wqe->els_req, vport->fc_myDID);
10897
10898                         /* For ELS_REQUEST64_WQE, use the VPI by default */
10899                         bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
10900                                phba->vpi_ids[vport->vpi]);
10901                 }
10902
10903                 /* The CT field must be 0=INVALID_RPI for the ECHO cmd */
10904                 if (elscmd == ELS_CMD_ECHO)
10905                         bf_set(wqe_ct, &wqe->generic.wqe_com, 0);
10906                 else
10907                         bf_set(wqe_ct, &wqe->generic.wqe_com, 1);
10908         }
10909 }
10910
10911 void
10912 lpfc_sli_prep_els_req_rsp(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
10913                           struct lpfc_vport *vport, struct lpfc_dmabuf *bmp,
10914                           u16 cmd_size, u32 did, u32 elscmd, u8 tmo,
10915                           u8 expect_rsp)
10916 {
10917         phba->__lpfc_sli_prep_els_req_rsp(cmdiocbq, vport, bmp, cmd_size, did,
10918                                           elscmd, tmo, expect_rsp);
10919 }
10920
10921 static void
10922 __lpfc_sli_prep_gen_req_s3(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10923                            u16 rpi, u32 num_entry, u8 tmo)
10924 {
10925         IOCB_t *cmd;
10926
10927         cmd = &cmdiocbq->iocb;
10928         memset(cmd, 0, sizeof(*cmd));
10929
10930         cmd->un.genreq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
10931         cmd->un.genreq64.bdl.addrLow = putPaddrLow(bmp->phys);
10932         cmd->un.genreq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
10933         cmd->un.genreq64.bdl.bdeSize = num_entry * sizeof(struct ulp_bde64);
10934
10935         cmd->un.genreq64.w5.hcsw.Rctl = FC_RCTL_DD_UNSOL_CTL;
10936         cmd->un.genreq64.w5.hcsw.Type = FC_TYPE_CT;
10937         cmd->un.genreq64.w5.hcsw.Fctl = (SI | LA);
10938
10939         cmd->ulpContext = rpi;
10940         cmd->ulpClass = CLASS3;
10941         cmd->ulpCommand = CMD_GEN_REQUEST64_CR;
10942         cmd->ulpBdeCount = 1;
10943         cmd->ulpLe = 1;
10944         cmd->ulpOwner = OWN_CHIP;
10945         cmd->ulpTimeout = tmo;
10946 }
10947
10948 static void
10949 __lpfc_sli_prep_gen_req_s4(struct lpfc_iocbq *cmdiocbq, struct lpfc_dmabuf *bmp,
10950                            u16 rpi, u32 num_entry, u8 tmo)
10951 {
10952         union lpfc_wqe128 *cmdwqe;
10953         struct ulp_bde64_le *bde, *bpl;
10954         u32 xmit_len = 0, total_len = 0, size, type, i;
10955
10956         cmdwqe = &cmdiocbq->wqe;
10957         memset(cmdwqe, 0, sizeof(*cmdwqe));
10958
10959         /* Calculate total_len and xmit_len */
10960         bpl = (struct ulp_bde64_le *)bmp->virt;
10961         for (i = 0; i < num_entry; i++) {
10962                 size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
10963                 total_len += size;
10964         }
10965         for (i = 0; i < num_entry; i++) {
10966                 size = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_SIZE_MASK;
10967                 type = le32_to_cpu(bpl[i].type_size) & ULP_BDE64_TYPE_MASK;
10968                 if (type != ULP_BDE64_TYPE_BDE_64)
10969                         break;
10970                 xmit_len += size;
10971         }
10972
10973         /* Words 0 - 2 */
10974         bde = (struct ulp_bde64_le *)&cmdwqe->generic.bde;
10975         bde->addr_low = bpl->addr_low;
10976         bde->addr_high = bpl->addr_high;
10977         bde->type_size = cpu_to_le32(xmit_len);
10978         bde->type_size |= cpu_to_le32(ULP_BDE64_TYPE_BDE_64);
10979
10980         /* Word 3 */
10981         cmdwqe->gen_req.request_payload_len = xmit_len;
10982
10983         /* Word 5 */
10984         bf_set(wqe_type, &cmdwqe->gen_req.wge_ctl, FC_TYPE_CT);
10985         bf_set(wqe_rctl, &cmdwqe->gen_req.wge_ctl, FC_RCTL_DD_UNSOL_CTL);
10986         bf_set(wqe_si, &cmdwqe->gen_req.wge_ctl, 1);
10987         bf_set(wqe_la, &cmdwqe->gen_req.wge_ctl, 1);
10988
10989         /* Word 6 */
10990         bf_set(wqe_ctxt_tag, &cmdwqe->gen_req.wqe_com, rpi);
10991
10992         /* Word 7 */
10993         bf_set(wqe_tmo, &cmdwqe->gen_req.wqe_com, tmo);
10994         bf_set(wqe_class, &cmdwqe->gen_req.wqe_com, CLASS3);
10995         bf_set(wqe_cmnd, &cmdwqe->gen_req.wqe_com, CMD_GEN_REQUEST64_CR);
10996         bf_set(wqe_ct, &cmdwqe->gen_req.wqe_com, SLI4_CT_RPI);
10997
10998         /* Word 12 */
10999         cmdwqe->gen_req.max_response_payload_len = total_len - xmit_len;
11000 }
11001
11002 void
11003 lpfc_sli_prep_gen_req(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11004                       struct lpfc_dmabuf *bmp, u16 rpi, u32 num_entry, u8 tmo)
11005 {
11006         phba->__lpfc_sli_prep_gen_req(cmdiocbq, bmp, rpi, num_entry, tmo);
11007 }
11008
11009 static void
11010 __lpfc_sli_prep_xmit_seq64_s3(struct lpfc_iocbq *cmdiocbq,
11011                               struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11012                               u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11013 {
11014         IOCB_t *icmd;
11015
11016         icmd = &cmdiocbq->iocb;
11017         memset(icmd, 0, sizeof(*icmd));
11018
11019         icmd->un.xseq64.bdl.addrHigh = putPaddrHigh(bmp->phys);
11020         icmd->un.xseq64.bdl.addrLow = putPaddrLow(bmp->phys);
11021         icmd->un.xseq64.bdl.bdeFlags = BUFF_TYPE_BLP_64;
11022         icmd->un.xseq64.bdl.bdeSize = (num_entry * sizeof(struct ulp_bde64));
11023         icmd->un.xseq64.w5.hcsw.Fctl = LA;
11024         if (last_seq)
11025                 icmd->un.xseq64.w5.hcsw.Fctl |= LS;
11026         icmd->un.xseq64.w5.hcsw.Dfctl = 0;
11027         icmd->un.xseq64.w5.hcsw.Rctl = rctl;
11028         icmd->un.xseq64.w5.hcsw.Type = FC_TYPE_CT;
11029
11030         icmd->ulpBdeCount = 1;
11031         icmd->ulpLe = 1;
11032         icmd->ulpClass = CLASS3;
11033
11034         switch (cr_cx_cmd) {
11035         case CMD_XMIT_SEQUENCE64_CR:
11036                 icmd->ulpContext = rpi;
11037                 icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CR;
11038                 break;
11039         case CMD_XMIT_SEQUENCE64_CX:
11040                 icmd->ulpContext = ox_id;
11041                 icmd->ulpCommand = CMD_XMIT_SEQUENCE64_CX;
11042                 break;
11043         default:
11044                 break;
11045         }
11046 }
11047
11048 static void
11049 __lpfc_sli_prep_xmit_seq64_s4(struct lpfc_iocbq *cmdiocbq,
11050                               struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11051                               u32 full_size, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11052 {
11053         union lpfc_wqe128 *wqe;
11054         struct ulp_bde64 *bpl;
11055
11056         wqe = &cmdiocbq->wqe;
11057         memset(wqe, 0, sizeof(*wqe));
11058
11059         /* Words 0 - 2 */
11060         bpl = (struct ulp_bde64 *)bmp->virt;
11061         wqe->xmit_sequence.bde.addrHigh = bpl->addrHigh;
11062         wqe->xmit_sequence.bde.addrLow = bpl->addrLow;
11063         wqe->xmit_sequence.bde.tus.w = bpl->tus.w;
11064
11065         /* Word 5 */
11066         bf_set(wqe_ls, &wqe->xmit_sequence.wge_ctl, last_seq);
11067         bf_set(wqe_la, &wqe->xmit_sequence.wge_ctl, 1);
11068         bf_set(wqe_dfctl, &wqe->xmit_sequence.wge_ctl, 0);
11069         bf_set(wqe_rctl, &wqe->xmit_sequence.wge_ctl, rctl);
11070         bf_set(wqe_type, &wqe->xmit_sequence.wge_ctl, FC_TYPE_CT);
11071
11072         /* Word 6 */
11073         bf_set(wqe_ctxt_tag, &wqe->xmit_sequence.wqe_com, rpi);
11074
11075         bf_set(wqe_cmnd, &wqe->xmit_sequence.wqe_com,
11076                CMD_XMIT_SEQUENCE64_WQE);
11077
11078         /* Word 7 */
11079         bf_set(wqe_class, &wqe->xmit_sequence.wqe_com, CLASS3);
11080
11081         /* Word 9 */
11082         bf_set(wqe_rcvoxid, &wqe->xmit_sequence.wqe_com, ox_id);
11083
11084         if (cmdiocbq->cmd_flag & (LPFC_IO_LIBDFC | LPFC_IO_LOOPBACK)) {
11085                 /* Word 10 */
11086                 if (cmdiocbq->cmd_flag & LPFC_IO_VMID) {
11087                         bf_set(wqe_appid, &wqe->xmit_sequence.wqe_com, 1);
11088                         bf_set(wqe_wqes, &wqe->xmit_sequence.wqe_com, 1);
11089                         wqe->words[31] = LOOPBACK_SRC_APPID;
11090                 }
11091
11092                 /* Word 12 */
11093                 wqe->xmit_sequence.xmit_len = full_size;
11094         }
11095         else
11096                 wqe->xmit_sequence.xmit_len =
11097                         wqe->xmit_sequence.bde.tus.f.bdeSize;
11098 }
11099
11100 void
11101 lpfc_sli_prep_xmit_seq64(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11102                          struct lpfc_dmabuf *bmp, u16 rpi, u16 ox_id,
11103                          u32 num_entry, u8 rctl, u8 last_seq, u8 cr_cx_cmd)
11104 {
11105         phba->__lpfc_sli_prep_xmit_seq64(cmdiocbq, bmp, rpi, ox_id, num_entry,
11106                                          rctl, last_seq, cr_cx_cmd);
11107 }
11108
11109 static void
11110 __lpfc_sli_prep_abort_xri_s3(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11111                              u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11112                              bool wqec)
11113 {
11114         IOCB_t *icmd = NULL;
11115
11116         icmd = &cmdiocbq->iocb;
11117         memset(icmd, 0, sizeof(*icmd));
11118
11119         /* Word 5 */
11120         icmd->un.acxri.abortContextTag = ulp_context;
11121         icmd->un.acxri.abortIoTag = iotag;
11122
11123         if (ia) {
11124                 /* Word 7 */
11125                 icmd->ulpCommand = CMD_CLOSE_XRI_CN;
11126         } else {
11127                 /* Word 3 */
11128                 icmd->un.acxri.abortType = ABORT_TYPE_ABTS;
11129
11130                 /* Word 7 */
11131                 icmd->ulpClass = ulp_class;
11132                 icmd->ulpCommand = CMD_ABORT_XRI_CN;
11133         }
11134
11135         /* Word 7 */
11136         icmd->ulpLe = 1;
11137 }
11138
11139 static void
11140 __lpfc_sli_prep_abort_xri_s4(struct lpfc_iocbq *cmdiocbq, u16 ulp_context,
11141                              u16 iotag, u8 ulp_class, u16 cqid, bool ia,
11142                              bool wqec)
11143 {
11144         union lpfc_wqe128 *wqe;
11145
11146         wqe = &cmdiocbq->wqe;
11147         memset(wqe, 0, sizeof(*wqe));
11148
11149         /* Word 3 */
11150         bf_set(abort_cmd_criteria, &wqe->abort_cmd, T_XRI_TAG);
11151         if (ia)
11152                 bf_set(abort_cmd_ia, &wqe->abort_cmd, 1);
11153         else
11154                 bf_set(abort_cmd_ia, &wqe->abort_cmd, 0);
11155
11156         /* Word 7 */
11157         bf_set(wqe_cmnd, &wqe->abort_cmd.wqe_com, CMD_ABORT_XRI_WQE);
11158
11159         /* Word 8 */
11160         wqe->abort_cmd.wqe_com.abort_tag = ulp_context;
11161
11162         /* Word 9 */
11163         bf_set(wqe_reqtag, &wqe->abort_cmd.wqe_com, iotag);
11164
11165         /* Word 10 */
11166         bf_set(wqe_qosd, &wqe->abort_cmd.wqe_com, 1);
11167
11168         /* Word 11 */
11169         if (wqec)
11170                 bf_set(wqe_wqec, &wqe->abort_cmd.wqe_com, 1);
11171         bf_set(wqe_cqid, &wqe->abort_cmd.wqe_com, cqid);
11172         bf_set(wqe_cmd_type, &wqe->abort_cmd.wqe_com, OTHER_COMMAND);
11173 }
11174
11175 void
11176 lpfc_sli_prep_abort_xri(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocbq,
11177                         u16 ulp_context, u16 iotag, u8 ulp_class, u16 cqid,
11178                         bool ia, bool wqec)
11179 {
11180         phba->__lpfc_sli_prep_abort_xri(cmdiocbq, ulp_context, iotag, ulp_class,
11181                                         cqid, ia, wqec);
11182 }
11183
11184 /**
11185  * lpfc_sli_api_table_setup - Set up sli api function jump table
11186  * @phba: The hba struct for which this call is being executed.
11187  * @dev_grp: The HBA PCI-Device group number.
11188  *
11189  * This routine sets up the SLI interface API function jump table in @phba
11190  * struct.
11191  * Returns: 0 - success, -ENODEV - failure.
11192  **/
11193 int
11194 lpfc_sli_api_table_setup(struct lpfc_hba *phba, uint8_t dev_grp)
11195 {
11196
11197         switch (dev_grp) {
11198         case LPFC_PCI_DEV_LP:
11199                 phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s3;
11200                 phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s3;
11201                 phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s3;
11202                 phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s3;
11203                 phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s3;
11204                 phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s3;
11205                 phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s3;
11206                 break;
11207         case LPFC_PCI_DEV_OC:
11208                 phba->__lpfc_sli_issue_iocb = __lpfc_sli_issue_iocb_s4;
11209                 phba->__lpfc_sli_release_iocbq = __lpfc_sli_release_iocbq_s4;
11210                 phba->__lpfc_sli_issue_fcp_io = __lpfc_sli_issue_fcp_io_s4;
11211                 phba->__lpfc_sli_prep_els_req_rsp = __lpfc_sli_prep_els_req_rsp_s4;
11212                 phba->__lpfc_sli_prep_gen_req = __lpfc_sli_prep_gen_req_s4;
11213                 phba->__lpfc_sli_prep_xmit_seq64 = __lpfc_sli_prep_xmit_seq64_s4;
11214                 phba->__lpfc_sli_prep_abort_xri = __lpfc_sli_prep_abort_xri_s4;
11215                 break;
11216         default:
11217                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
11218                                 "1419 Invalid HBA PCI-device group: 0x%x\n",
11219                                 dev_grp);
11220                 return -ENODEV;
11221         }
11222         return 0;
11223 }
11224
11225 /**
11226  * lpfc_sli4_calc_ring - Calculates which ring to use
11227  * @phba: Pointer to HBA context object.
11228  * @piocb: Pointer to command iocb.
11229  *
11230  * For SLI4 only, FCP IO can deferred to one fo many WQs, based on
11231  * hba_wqidx, thus we need to calculate the corresponding ring.
11232  * Since ABORTS must go on the same WQ of the command they are
11233  * aborting, we use command's hba_wqidx.
11234  */
11235 struct lpfc_sli_ring *
11236 lpfc_sli4_calc_ring(struct lpfc_hba *phba, struct lpfc_iocbq *piocb)
11237 {
11238         struct lpfc_io_buf *lpfc_cmd;
11239
11240         if (piocb->cmd_flag & (LPFC_IO_FCP | LPFC_USE_FCPWQIDX)) {
11241                 if (unlikely(!phba->sli4_hba.hdwq))
11242                         return NULL;
11243                 /*
11244                  * for abort iocb hba_wqidx should already
11245                  * be setup based on what work queue we used.
11246                  */
11247                 if (!(piocb->cmd_flag & LPFC_USE_FCPWQIDX)) {
11248                         lpfc_cmd = piocb->io_buf;
11249                         piocb->hba_wqidx = lpfc_cmd->hdwq_no;
11250                 }
11251                 return phba->sli4_hba.hdwq[piocb->hba_wqidx].io_wq->pring;
11252         } else {
11253                 if (unlikely(!phba->sli4_hba.els_wq))
11254                         return NULL;
11255                 piocb->hba_wqidx = 0;
11256                 return phba->sli4_hba.els_wq->pring;
11257         }
11258 }
11259
11260 inline void lpfc_sli4_poll_eq(struct lpfc_queue *eq)
11261 {
11262         struct lpfc_hba *phba = eq->phba;
11263
11264         /*
11265          * Unlocking an irq is one of the entry point to check
11266          * for re-schedule, but we are good for io submission
11267          * path as midlayer does a get_cpu to glue us in. Flush
11268          * out the invalidate queue so we can see the updated
11269          * value for flag.
11270          */
11271         smp_rmb();
11272
11273         if (READ_ONCE(eq->mode) == LPFC_EQ_POLL)
11274                 /* We will not likely get the completion for the caller
11275                  * during this iteration but i guess that's fine.
11276                  * Future io's coming on this eq should be able to
11277                  * pick it up.  As for the case of single io's, they
11278                  * will be handled through a sched from polling timer
11279                  * function which is currently triggered every 1msec.
11280                  */
11281                 lpfc_sli4_process_eq(phba, eq, LPFC_QUEUE_NOARM,
11282                                      LPFC_QUEUE_WORK);
11283 }
11284
11285 /**
11286  * lpfc_sli_issue_iocb - Wrapper function for __lpfc_sli_issue_iocb
11287  * @phba: Pointer to HBA context object.
11288  * @ring_number: Ring number
11289  * @piocb: Pointer to command iocb.
11290  * @flag: Flag indicating if this command can be put into txq.
11291  *
11292  * lpfc_sli_issue_iocb is a wrapper around __lpfc_sli_issue_iocb
11293  * function. This function gets the hbalock and calls
11294  * __lpfc_sli_issue_iocb function and will return the error returned
11295  * by __lpfc_sli_issue_iocb function. This wrapper is used by
11296  * functions which do not hold hbalock.
11297  **/
11298 int
11299 lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number,
11300                     struct lpfc_iocbq *piocb, uint32_t flag)
11301 {
11302         struct lpfc_sli_ring *pring;
11303         struct lpfc_queue *eq;
11304         unsigned long iflags;
11305         int rc;
11306
11307         /* If the PCI channel is in offline state, do not post iocbs. */
11308         if (unlikely(pci_channel_offline(phba->pcidev)))
11309                 return IOCB_ERROR;
11310
11311         if (phba->sli_rev == LPFC_SLI_REV4) {
11312                 lpfc_sli_prep_wqe(phba, piocb);
11313
11314                 eq = phba->sli4_hba.hdwq[piocb->hba_wqidx].hba_eq;
11315
11316                 pring = lpfc_sli4_calc_ring(phba, piocb);
11317                 if (unlikely(pring == NULL))
11318                         return IOCB_ERROR;
11319
11320                 spin_lock_irqsave(&pring->ring_lock, iflags);
11321                 rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11322                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
11323
11324                 lpfc_sli4_poll_eq(eq);
11325         } else {
11326                 /* For now, SLI2/3 will still use hbalock */
11327                 spin_lock_irqsave(&phba->hbalock, iflags);
11328                 rc = __lpfc_sli_issue_iocb(phba, ring_number, piocb, flag);
11329                 spin_unlock_irqrestore(&phba->hbalock, iflags);
11330         }
11331         return rc;
11332 }
11333
11334 /**
11335  * lpfc_extra_ring_setup - Extra ring setup function
11336  * @phba: Pointer to HBA context object.
11337  *
11338  * This function is called while driver attaches with the
11339  * HBA to setup the extra ring. The extra ring is used
11340  * only when driver needs to support target mode functionality
11341  * or IP over FC functionalities.
11342  *
11343  * This function is called with no lock held. SLI3 only.
11344  **/
11345 static int
11346 lpfc_extra_ring_setup( struct lpfc_hba *phba)
11347 {
11348         struct lpfc_sli *psli;
11349         struct lpfc_sli_ring *pring;
11350
11351         psli = &phba->sli;
11352
11353         /* Adjust cmd/rsp ring iocb entries more evenly */
11354
11355         /* Take some away from the FCP ring */
11356         pring = &psli->sli3_ring[LPFC_FCP_RING];
11357         pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11358         pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11359         pring->sli.sli3.numCiocb -= SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11360         pring->sli.sli3.numRiocb -= SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11361
11362         /* and give them to the extra ring */
11363         pring = &psli->sli3_ring[LPFC_EXTRA_RING];
11364
11365         pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11366         pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11367         pring->sli.sli3.numCiocb += SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11368         pring->sli.sli3.numRiocb += SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11369
11370         /* Setup default profile for this ring */
11371         pring->iotag_max = 4096;
11372         pring->num_mask = 1;
11373         pring->prt[0].profile = 0;      /* Mask 0 */
11374         pring->prt[0].rctl = phba->cfg_multi_ring_rctl;
11375         pring->prt[0].type = phba->cfg_multi_ring_type;
11376         pring->prt[0].lpfc_sli_rcv_unsol_event = NULL;
11377         return 0;
11378 }
11379
11380 static void
11381 lpfc_sli_post_recovery_event(struct lpfc_hba *phba,
11382                              struct lpfc_nodelist *ndlp)
11383 {
11384         unsigned long iflags;
11385         struct lpfc_work_evt  *evtp = &ndlp->recovery_evt;
11386
11387         /* Hold a node reference for outstanding queued work */
11388         if (!lpfc_nlp_get(ndlp))
11389                 return;
11390
11391         spin_lock_irqsave(&phba->hbalock, iflags);
11392         if (!list_empty(&evtp->evt_listp)) {
11393                 spin_unlock_irqrestore(&phba->hbalock, iflags);
11394                 lpfc_nlp_put(ndlp);
11395                 return;
11396         }
11397
11398         evtp->evt_arg1 = ndlp;
11399         evtp->evt = LPFC_EVT_RECOVER_PORT;
11400         list_add_tail(&evtp->evt_listp, &phba->work_list);
11401         spin_unlock_irqrestore(&phba->hbalock, iflags);
11402
11403         lpfc_worker_wake_up(phba);
11404 }
11405
11406 /* lpfc_sli_abts_err_handler - handle a failed ABTS request from an SLI3 port.
11407  * @phba: Pointer to HBA context object.
11408  * @iocbq: Pointer to iocb object.
11409  *
11410  * The async_event handler calls this routine when it receives
11411  * an ASYNC_STATUS_CN event from the port.  The port generates
11412  * this event when an Abort Sequence request to an rport fails
11413  * twice in succession.  The abort could be originated by the
11414  * driver or by the port.  The ABTS could have been for an ELS
11415  * or FCP IO.  The port only generates this event when an ABTS
11416  * fails to complete after one retry.
11417  */
11418 static void
11419 lpfc_sli_abts_err_handler(struct lpfc_hba *phba,
11420                           struct lpfc_iocbq *iocbq)
11421 {
11422         struct lpfc_nodelist *ndlp = NULL;
11423         uint16_t rpi = 0, vpi = 0;
11424         struct lpfc_vport *vport = NULL;
11425
11426         /* The rpi in the ulpContext is vport-sensitive. */
11427         vpi = iocbq->iocb.un.asyncstat.sub_ctxt_tag;
11428         rpi = iocbq->iocb.ulpContext;
11429
11430         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11431                         "3092 Port generated ABTS async event "
11432                         "on vpi %d rpi %d status 0x%x\n",
11433                         vpi, rpi, iocbq->iocb.ulpStatus);
11434
11435         vport = lpfc_find_vport_by_vpid(phba, vpi);
11436         if (!vport)
11437                 goto err_exit;
11438         ndlp = lpfc_findnode_rpi(vport, rpi);
11439         if (!ndlp)
11440                 goto err_exit;
11441
11442         if (iocbq->iocb.ulpStatus == IOSTAT_LOCAL_REJECT)
11443                 lpfc_sli_abts_recover_port(vport, ndlp);
11444         return;
11445
11446  err_exit:
11447         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11448                         "3095 Event Context not found, no "
11449                         "action on vpi %d rpi %d status 0x%x, reason 0x%x\n",
11450                         vpi, rpi, iocbq->iocb.ulpStatus,
11451                         iocbq->iocb.ulpContext);
11452 }
11453
11454 /* lpfc_sli4_abts_err_handler - handle a failed ABTS request from an SLI4 port.
11455  * @phba: pointer to HBA context object.
11456  * @ndlp: nodelist pointer for the impacted rport.
11457  * @axri: pointer to the wcqe containing the failed exchange.
11458  *
11459  * The driver calls this routine when it receives an ABORT_XRI_FCP CQE from the
11460  * port.  The port generates this event when an abort exchange request to an
11461  * rport fails twice in succession with no reply.  The abort could be originated
11462  * by the driver or by the port.  The ABTS could have been for an ELS or FCP IO.
11463  */
11464 void
11465 lpfc_sli4_abts_err_handler(struct lpfc_hba *phba,
11466                            struct lpfc_nodelist *ndlp,
11467                            struct sli4_wcqe_xri_aborted *axri)
11468 {
11469         uint32_t ext_status = 0;
11470
11471         if (!ndlp) {
11472                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
11473                                 "3115 Node Context not found, driver "
11474                                 "ignoring abts err event\n");
11475                 return;
11476         }
11477
11478         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
11479                         "3116 Port generated FCP XRI ABORT event on "
11480                         "vpi %d rpi %d xri x%x status 0x%x parameter x%x\n",
11481                         ndlp->vport->vpi, phba->sli4_hba.rpi_ids[ndlp->nlp_rpi],
11482                         bf_get(lpfc_wcqe_xa_xri, axri),
11483                         bf_get(lpfc_wcqe_xa_status, axri),
11484                         axri->parameter);
11485
11486         /*
11487          * Catch the ABTS protocol failure case.  Older OCe FW releases returned
11488          * LOCAL_REJECT and 0 for a failed ABTS exchange and later OCe and
11489          * LPe FW releases returned LOCAL_REJECT and SEQUENCE_TIMEOUT.
11490          */
11491         ext_status = axri->parameter & IOERR_PARAM_MASK;
11492         if ((bf_get(lpfc_wcqe_xa_status, axri) == IOSTAT_LOCAL_REJECT) &&
11493             ((ext_status == IOERR_SEQUENCE_TIMEOUT) || (ext_status == 0)))
11494                 lpfc_sli_post_recovery_event(phba, ndlp);
11495 }
11496
11497 /**
11498  * lpfc_sli_async_event_handler - ASYNC iocb handler function
11499  * @phba: Pointer to HBA context object.
11500  * @pring: Pointer to driver SLI ring object.
11501  * @iocbq: Pointer to iocb object.
11502  *
11503  * This function is called by the slow ring event handler
11504  * function when there is an ASYNC event iocb in the ring.
11505  * This function is called with no lock held.
11506  * Currently this function handles only temperature related
11507  * ASYNC events. The function decodes the temperature sensor
11508  * event message and posts events for the management applications.
11509  **/
11510 static void
11511 lpfc_sli_async_event_handler(struct lpfc_hba * phba,
11512         struct lpfc_sli_ring * pring, struct lpfc_iocbq * iocbq)
11513 {
11514         IOCB_t *icmd;
11515         uint16_t evt_code;
11516         struct temp_event temp_event_data;
11517         struct Scsi_Host *shost;
11518         uint32_t *iocb_w;
11519
11520         icmd = &iocbq->iocb;
11521         evt_code = icmd->un.asyncstat.evt_code;
11522
11523         switch (evt_code) {
11524         case ASYNC_TEMP_WARN:
11525         case ASYNC_TEMP_SAFE:
11526                 temp_event_data.data = (uint32_t) icmd->ulpContext;
11527                 temp_event_data.event_type = FC_REG_TEMPERATURE_EVENT;
11528                 if (evt_code == ASYNC_TEMP_WARN) {
11529                         temp_event_data.event_code = LPFC_THRESHOLD_TEMP;
11530                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11531                                 "0347 Adapter is very hot, please take "
11532                                 "corrective action. temperature : %d Celsius\n",
11533                                 (uint32_t) icmd->ulpContext);
11534                 } else {
11535                         temp_event_data.event_code = LPFC_NORMAL_TEMP;
11536                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11537                                 "0340 Adapter temperature is OK now. "
11538                                 "temperature : %d Celsius\n",
11539                                 (uint32_t) icmd->ulpContext);
11540                 }
11541
11542                 /* Send temperature change event to applications */
11543                 shost = lpfc_shost_from_vport(phba->pport);
11544                 fc_host_post_vendor_event(shost, fc_get_event_number(),
11545                         sizeof(temp_event_data), (char *) &temp_event_data,
11546                         LPFC_NL_VENDOR_ID);
11547                 break;
11548         case ASYNC_STATUS_CN:
11549                 lpfc_sli_abts_err_handler(phba, iocbq);
11550                 break;
11551         default:
11552                 iocb_w = (uint32_t *) icmd;
11553                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
11554                         "0346 Ring %d handler: unexpected ASYNC_STATUS"
11555                         " evt_code 0x%x\n"
11556                         "W0  0x%08x W1  0x%08x W2  0x%08x W3  0x%08x\n"
11557                         "W4  0x%08x W5  0x%08x W6  0x%08x W7  0x%08x\n"
11558                         "W8  0x%08x W9  0x%08x W10 0x%08x W11 0x%08x\n"
11559                         "W12 0x%08x W13 0x%08x W14 0x%08x W15 0x%08x\n",
11560                         pring->ringno, icmd->un.asyncstat.evt_code,
11561                         iocb_w[0], iocb_w[1], iocb_w[2], iocb_w[3],
11562                         iocb_w[4], iocb_w[5], iocb_w[6], iocb_w[7],
11563                         iocb_w[8], iocb_w[9], iocb_w[10], iocb_w[11],
11564                         iocb_w[12], iocb_w[13], iocb_w[14], iocb_w[15]);
11565
11566                 break;
11567         }
11568 }
11569
11570
11571 /**
11572  * lpfc_sli4_setup - SLI ring setup function
11573  * @phba: Pointer to HBA context object.
11574  *
11575  * lpfc_sli_setup sets up rings of the SLI interface with
11576  * number of iocbs per ring and iotags. This function is
11577  * called while driver attach to the HBA and before the
11578  * interrupts are enabled. So there is no need for locking.
11579  *
11580  * This function always returns 0.
11581  **/
11582 int
11583 lpfc_sli4_setup(struct lpfc_hba *phba)
11584 {
11585         struct lpfc_sli_ring *pring;
11586
11587         pring = phba->sli4_hba.els_wq->pring;
11588         pring->num_mask = LPFC_MAX_RING_MASK;
11589         pring->prt[0].profile = 0;      /* Mask 0 */
11590         pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11591         pring->prt[0].type = FC_TYPE_ELS;
11592         pring->prt[0].lpfc_sli_rcv_unsol_event =
11593             lpfc_els_unsol_event;
11594         pring->prt[1].profile = 0;      /* Mask 1 */
11595         pring->prt[1].rctl = FC_RCTL_ELS_REP;
11596         pring->prt[1].type = FC_TYPE_ELS;
11597         pring->prt[1].lpfc_sli_rcv_unsol_event =
11598             lpfc_els_unsol_event;
11599         pring->prt[2].profile = 0;      /* Mask 2 */
11600         /* NameServer Inquiry */
11601         pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11602         /* NameServer */
11603         pring->prt[2].type = FC_TYPE_CT;
11604         pring->prt[2].lpfc_sli_rcv_unsol_event =
11605             lpfc_ct_unsol_event;
11606         pring->prt[3].profile = 0;      /* Mask 3 */
11607         /* NameServer response */
11608         pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11609         /* NameServer */
11610         pring->prt[3].type = FC_TYPE_CT;
11611         pring->prt[3].lpfc_sli_rcv_unsol_event =
11612             lpfc_ct_unsol_event;
11613         return 0;
11614 }
11615
11616 /**
11617  * lpfc_sli_setup - SLI ring setup function
11618  * @phba: Pointer to HBA context object.
11619  *
11620  * lpfc_sli_setup sets up rings of the SLI interface with
11621  * number of iocbs per ring and iotags. This function is
11622  * called while driver attach to the HBA and before the
11623  * interrupts are enabled. So there is no need for locking.
11624  *
11625  * This function always returns 0. SLI3 only.
11626  **/
11627 int
11628 lpfc_sli_setup(struct lpfc_hba *phba)
11629 {
11630         int i, totiocbsize = 0;
11631         struct lpfc_sli *psli = &phba->sli;
11632         struct lpfc_sli_ring *pring;
11633
11634         psli->num_rings = MAX_SLI3_CONFIGURED_RINGS;
11635         psli->sli_flag = 0;
11636
11637         psli->iocbq_lookup = NULL;
11638         psli->iocbq_lookup_len = 0;
11639         psli->last_iotag = 0;
11640
11641         for (i = 0; i < psli->num_rings; i++) {
11642                 pring = &psli->sli3_ring[i];
11643                 switch (i) {
11644                 case LPFC_FCP_RING:     /* ring 0 - FCP */
11645                         /* numCiocb and numRiocb are used in config_port */
11646                         pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R0_ENTRIES;
11647                         pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R0_ENTRIES;
11648                         pring->sli.sli3.numCiocb +=
11649                                 SLI2_IOCB_CMD_R1XTRA_ENTRIES;
11650                         pring->sli.sli3.numRiocb +=
11651                                 SLI2_IOCB_RSP_R1XTRA_ENTRIES;
11652                         pring->sli.sli3.numCiocb +=
11653                                 SLI2_IOCB_CMD_R3XTRA_ENTRIES;
11654                         pring->sli.sli3.numRiocb +=
11655                                 SLI2_IOCB_RSP_R3XTRA_ENTRIES;
11656                         pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11657                                                         SLI3_IOCB_CMD_SIZE :
11658                                                         SLI2_IOCB_CMD_SIZE;
11659                         pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11660                                                         SLI3_IOCB_RSP_SIZE :
11661                                                         SLI2_IOCB_RSP_SIZE;
11662                         pring->iotag_ctr = 0;
11663                         pring->iotag_max =
11664                             (phba->cfg_hba_queue_depth * 2);
11665                         pring->fast_iotag = pring->iotag_max;
11666                         pring->num_mask = 0;
11667                         break;
11668                 case LPFC_EXTRA_RING:   /* ring 1 - EXTRA */
11669                         /* numCiocb and numRiocb are used in config_port */
11670                         pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R1_ENTRIES;
11671                         pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R1_ENTRIES;
11672                         pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11673                                                         SLI3_IOCB_CMD_SIZE :
11674                                                         SLI2_IOCB_CMD_SIZE;
11675                         pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11676                                                         SLI3_IOCB_RSP_SIZE :
11677                                                         SLI2_IOCB_RSP_SIZE;
11678                         pring->iotag_max = phba->cfg_hba_queue_depth;
11679                         pring->num_mask = 0;
11680                         break;
11681                 case LPFC_ELS_RING:     /* ring 2 - ELS / CT */
11682                         /* numCiocb and numRiocb are used in config_port */
11683                         pring->sli.sli3.numCiocb = SLI2_IOCB_CMD_R2_ENTRIES;
11684                         pring->sli.sli3.numRiocb = SLI2_IOCB_RSP_R2_ENTRIES;
11685                         pring->sli.sli3.sizeCiocb = (phba->sli_rev == 3) ?
11686                                                         SLI3_IOCB_CMD_SIZE :
11687                                                         SLI2_IOCB_CMD_SIZE;
11688                         pring->sli.sli3.sizeRiocb = (phba->sli_rev == 3) ?
11689                                                         SLI3_IOCB_RSP_SIZE :
11690                                                         SLI2_IOCB_RSP_SIZE;
11691                         pring->fast_iotag = 0;
11692                         pring->iotag_ctr = 0;
11693                         pring->iotag_max = 4096;
11694                         pring->lpfc_sli_rcv_async_status =
11695                                 lpfc_sli_async_event_handler;
11696                         pring->num_mask = LPFC_MAX_RING_MASK;
11697                         pring->prt[0].profile = 0;      /* Mask 0 */
11698                         pring->prt[0].rctl = FC_RCTL_ELS_REQ;
11699                         pring->prt[0].type = FC_TYPE_ELS;
11700                         pring->prt[0].lpfc_sli_rcv_unsol_event =
11701                             lpfc_els_unsol_event;
11702                         pring->prt[1].profile = 0;      /* Mask 1 */
11703                         pring->prt[1].rctl = FC_RCTL_ELS_REP;
11704                         pring->prt[1].type = FC_TYPE_ELS;
11705                         pring->prt[1].lpfc_sli_rcv_unsol_event =
11706                             lpfc_els_unsol_event;
11707                         pring->prt[2].profile = 0;      /* Mask 2 */
11708                         /* NameServer Inquiry */
11709                         pring->prt[2].rctl = FC_RCTL_DD_UNSOL_CTL;
11710                         /* NameServer */
11711                         pring->prt[2].type = FC_TYPE_CT;
11712                         pring->prt[2].lpfc_sli_rcv_unsol_event =
11713                             lpfc_ct_unsol_event;
11714                         pring->prt[3].profile = 0;      /* Mask 3 */
11715                         /* NameServer response */
11716                         pring->prt[3].rctl = FC_RCTL_DD_SOL_CTL;
11717                         /* NameServer */
11718                         pring->prt[3].type = FC_TYPE_CT;
11719                         pring->prt[3].lpfc_sli_rcv_unsol_event =
11720                             lpfc_ct_unsol_event;
11721                         break;
11722                 }
11723                 totiocbsize += (pring->sli.sli3.numCiocb *
11724                         pring->sli.sli3.sizeCiocb) +
11725                         (pring->sli.sli3.numRiocb * pring->sli.sli3.sizeRiocb);
11726         }
11727         if (totiocbsize > MAX_SLIM_IOCB_SIZE) {
11728                 /* Too many cmd / rsp ring entries in SLI2 SLIM */
11729                 printk(KERN_ERR "%d:0462 Too many cmd / rsp ring entries in "
11730                        "SLI2 SLIM Data: x%x x%lx\n",
11731                        phba->brd_no, totiocbsize,
11732                        (unsigned long) MAX_SLIM_IOCB_SIZE);
11733         }
11734         if (phba->cfg_multi_ring_support == 2)
11735                 lpfc_extra_ring_setup(phba);
11736
11737         return 0;
11738 }
11739
11740 /**
11741  * lpfc_sli4_queue_init - Queue initialization function
11742  * @phba: Pointer to HBA context object.
11743  *
11744  * lpfc_sli4_queue_init sets up mailbox queues and iocb queues for each
11745  * ring. This function also initializes ring indices of each ring.
11746  * This function is called during the initialization of the SLI
11747  * interface of an HBA.
11748  * This function is called with no lock held and always returns
11749  * 1.
11750  **/
11751 void
11752 lpfc_sli4_queue_init(struct lpfc_hba *phba)
11753 {
11754         struct lpfc_sli *psli;
11755         struct lpfc_sli_ring *pring;
11756         int i;
11757
11758         psli = &phba->sli;
11759         spin_lock_irq(&phba->hbalock);
11760         INIT_LIST_HEAD(&psli->mboxq);
11761         INIT_LIST_HEAD(&psli->mboxq_cmpl);
11762         /* Initialize list headers for txq and txcmplq as double linked lists */
11763         for (i = 0; i < phba->cfg_hdw_queue; i++) {
11764                 pring = phba->sli4_hba.hdwq[i].io_wq->pring;
11765                 pring->flag = 0;
11766                 pring->ringno = LPFC_FCP_RING;
11767                 pring->txcmplq_cnt = 0;
11768                 INIT_LIST_HEAD(&pring->txq);
11769                 INIT_LIST_HEAD(&pring->txcmplq);
11770                 INIT_LIST_HEAD(&pring->iocb_continueq);
11771                 spin_lock_init(&pring->ring_lock);
11772         }
11773         pring = phba->sli4_hba.els_wq->pring;
11774         pring->flag = 0;
11775         pring->ringno = LPFC_ELS_RING;
11776         pring->txcmplq_cnt = 0;
11777         INIT_LIST_HEAD(&pring->txq);
11778         INIT_LIST_HEAD(&pring->txcmplq);
11779         INIT_LIST_HEAD(&pring->iocb_continueq);
11780         spin_lock_init(&pring->ring_lock);
11781
11782         if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
11783                 pring = phba->sli4_hba.nvmels_wq->pring;
11784                 pring->flag = 0;
11785                 pring->ringno = LPFC_ELS_RING;
11786                 pring->txcmplq_cnt = 0;
11787                 INIT_LIST_HEAD(&pring->txq);
11788                 INIT_LIST_HEAD(&pring->txcmplq);
11789                 INIT_LIST_HEAD(&pring->iocb_continueq);
11790                 spin_lock_init(&pring->ring_lock);
11791         }
11792
11793         spin_unlock_irq(&phba->hbalock);
11794 }
11795
11796 /**
11797  * lpfc_sli_queue_init - Queue initialization function
11798  * @phba: Pointer to HBA context object.
11799  *
11800  * lpfc_sli_queue_init sets up mailbox queues and iocb queues for each
11801  * ring. This function also initializes ring indices of each ring.
11802  * This function is called during the initialization of the SLI
11803  * interface of an HBA.
11804  * This function is called with no lock held and always returns
11805  * 1.
11806  **/
11807 void
11808 lpfc_sli_queue_init(struct lpfc_hba *phba)
11809 {
11810         struct lpfc_sli *psli;
11811         struct lpfc_sli_ring *pring;
11812         int i;
11813
11814         psli = &phba->sli;
11815         spin_lock_irq(&phba->hbalock);
11816         INIT_LIST_HEAD(&psli->mboxq);
11817         INIT_LIST_HEAD(&psli->mboxq_cmpl);
11818         /* Initialize list headers for txq and txcmplq as double linked lists */
11819         for (i = 0; i < psli->num_rings; i++) {
11820                 pring = &psli->sli3_ring[i];
11821                 pring->ringno = i;
11822                 pring->sli.sli3.next_cmdidx  = 0;
11823                 pring->sli.sli3.local_getidx = 0;
11824                 pring->sli.sli3.cmdidx = 0;
11825                 INIT_LIST_HEAD(&pring->iocb_continueq);
11826                 INIT_LIST_HEAD(&pring->iocb_continue_saveq);
11827                 INIT_LIST_HEAD(&pring->postbufq);
11828                 pring->flag = 0;
11829                 INIT_LIST_HEAD(&pring->txq);
11830                 INIT_LIST_HEAD(&pring->txcmplq);
11831                 spin_lock_init(&pring->ring_lock);
11832         }
11833         spin_unlock_irq(&phba->hbalock);
11834 }
11835
11836 /**
11837  * lpfc_sli_mbox_sys_flush - Flush mailbox command sub-system
11838  * @phba: Pointer to HBA context object.
11839  *
11840  * This routine flushes the mailbox command subsystem. It will unconditionally
11841  * flush all the mailbox commands in the three possible stages in the mailbox
11842  * command sub-system: pending mailbox command queue; the outstanding mailbox
11843  * command; and completed mailbox command queue. It is caller's responsibility
11844  * to make sure that the driver is in the proper state to flush the mailbox
11845  * command sub-system. Namely, the posting of mailbox commands into the
11846  * pending mailbox command queue from the various clients must be stopped;
11847  * either the HBA is in a state that it will never works on the outstanding
11848  * mailbox command (such as in EEH or ERATT conditions) or the outstanding
11849  * mailbox command has been completed.
11850  **/
11851 static void
11852 lpfc_sli_mbox_sys_flush(struct lpfc_hba *phba)
11853 {
11854         LIST_HEAD(completions);
11855         struct lpfc_sli *psli = &phba->sli;
11856         LPFC_MBOXQ_t *pmb;
11857         unsigned long iflag;
11858
11859         /* Disable softirqs, including timers from obtaining phba->hbalock */
11860         local_bh_disable();
11861
11862         /* Flush all the mailbox commands in the mbox system */
11863         spin_lock_irqsave(&phba->hbalock, iflag);
11864
11865         /* The pending mailbox command queue */
11866         list_splice_init(&phba->sli.mboxq, &completions);
11867         /* The outstanding active mailbox command */
11868         if (psli->mbox_active) {
11869                 list_add_tail(&psli->mbox_active->list, &completions);
11870                 psli->mbox_active = NULL;
11871                 psli->sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
11872         }
11873         /* The completed mailbox command queue */
11874         list_splice_init(&phba->sli.mboxq_cmpl, &completions);
11875         spin_unlock_irqrestore(&phba->hbalock, iflag);
11876
11877         /* Enable softirqs again, done with phba->hbalock */
11878         local_bh_enable();
11879
11880         /* Return all flushed mailbox commands with MBX_NOT_FINISHED status */
11881         while (!list_empty(&completions)) {
11882                 list_remove_head(&completions, pmb, LPFC_MBOXQ_t, list);
11883                 pmb->u.mb.mbxStatus = MBX_NOT_FINISHED;
11884                 if (pmb->mbox_cmpl)
11885                         pmb->mbox_cmpl(phba, pmb);
11886         }
11887 }
11888
11889 /**
11890  * lpfc_sli_host_down - Vport cleanup function
11891  * @vport: Pointer to virtual port object.
11892  *
11893  * lpfc_sli_host_down is called to clean up the resources
11894  * associated with a vport before destroying virtual
11895  * port data structures.
11896  * This function does following operations:
11897  * - Free discovery resources associated with this virtual
11898  *   port.
11899  * - Free iocbs associated with this virtual port in
11900  *   the txq.
11901  * - Send abort for all iocb commands associated with this
11902  *   vport in txcmplq.
11903  *
11904  * This function is called with no lock held and always returns 1.
11905  **/
11906 int
11907 lpfc_sli_host_down(struct lpfc_vport *vport)
11908 {
11909         LIST_HEAD(completions);
11910         struct lpfc_hba *phba = vport->phba;
11911         struct lpfc_sli *psli = &phba->sli;
11912         struct lpfc_queue *qp = NULL;
11913         struct lpfc_sli_ring *pring;
11914         struct lpfc_iocbq *iocb, *next_iocb;
11915         int i;
11916         unsigned long flags = 0;
11917         uint16_t prev_pring_flag;
11918
11919         lpfc_cleanup_discovery_resources(vport);
11920
11921         spin_lock_irqsave(&phba->hbalock, flags);
11922
11923         /*
11924          * Error everything on the txq since these iocbs
11925          * have not been given to the FW yet.
11926          * Also issue ABTS for everything on the txcmplq
11927          */
11928         if (phba->sli_rev != LPFC_SLI_REV4) {
11929                 for (i = 0; i < psli->num_rings; i++) {
11930                         pring = &psli->sli3_ring[i];
11931                         prev_pring_flag = pring->flag;
11932                         /* Only slow rings */
11933                         if (pring->ringno == LPFC_ELS_RING) {
11934                                 pring->flag |= LPFC_DEFERRED_RING_EVENT;
11935                                 /* Set the lpfc data pending flag */
11936                                 set_bit(LPFC_DATA_READY, &phba->data_flags);
11937                         }
11938                         list_for_each_entry_safe(iocb, next_iocb,
11939                                                  &pring->txq, list) {
11940                                 if (iocb->vport != vport)
11941                                         continue;
11942                                 list_move_tail(&iocb->list, &completions);
11943                         }
11944                         list_for_each_entry_safe(iocb, next_iocb,
11945                                                  &pring->txcmplq, list) {
11946                                 if (iocb->vport != vport)
11947                                         continue;
11948                                 lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11949                                                            NULL);
11950                         }
11951                         pring->flag = prev_pring_flag;
11952                 }
11953         } else {
11954                 list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
11955                         pring = qp->pring;
11956                         if (!pring)
11957                                 continue;
11958                         if (pring == phba->sli4_hba.els_wq->pring) {
11959                                 pring->flag |= LPFC_DEFERRED_RING_EVENT;
11960                                 /* Set the lpfc data pending flag */
11961                                 set_bit(LPFC_DATA_READY, &phba->data_flags);
11962                         }
11963                         prev_pring_flag = pring->flag;
11964                         spin_lock(&pring->ring_lock);
11965                         list_for_each_entry_safe(iocb, next_iocb,
11966                                                  &pring->txq, list) {
11967                                 if (iocb->vport != vport)
11968                                         continue;
11969                                 list_move_tail(&iocb->list, &completions);
11970                         }
11971                         spin_unlock(&pring->ring_lock);
11972                         list_for_each_entry_safe(iocb, next_iocb,
11973                                                  &pring->txcmplq, list) {
11974                                 if (iocb->vport != vport)
11975                                         continue;
11976                                 lpfc_sli_issue_abort_iotag(phba, pring, iocb,
11977                                                            NULL);
11978                         }
11979                         pring->flag = prev_pring_flag;
11980                 }
11981         }
11982         spin_unlock_irqrestore(&phba->hbalock, flags);
11983
11984         /* Make sure HBA is alive */
11985         lpfc_issue_hb_tmo(phba);
11986
11987         /* Cancel all the IOCBs from the completions list */
11988         lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
11989                               IOERR_SLI_DOWN);
11990         return 1;
11991 }
11992
11993 /**
11994  * lpfc_sli_hba_down - Resource cleanup function for the HBA
11995  * @phba: Pointer to HBA context object.
11996  *
11997  * This function cleans up all iocb, buffers, mailbox commands
11998  * while shutting down the HBA. This function is called with no
11999  * lock held and always returns 1.
12000  * This function does the following to cleanup driver resources:
12001  * - Free discovery resources for each virtual port
12002  * - Cleanup any pending fabric iocbs
12003  * - Iterate through the iocb txq and free each entry
12004  *   in the list.
12005  * - Free up any buffer posted to the HBA
12006  * - Free mailbox commands in the mailbox queue.
12007  **/
12008 int
12009 lpfc_sli_hba_down(struct lpfc_hba *phba)
12010 {
12011         LIST_HEAD(completions);
12012         struct lpfc_sli *psli = &phba->sli;
12013         struct lpfc_queue *qp = NULL;
12014         struct lpfc_sli_ring *pring;
12015         struct lpfc_dmabuf *buf_ptr;
12016         unsigned long flags = 0;
12017         int i;
12018
12019         /* Shutdown the mailbox command sub-system */
12020         lpfc_sli_mbox_sys_shutdown(phba, LPFC_MBX_WAIT);
12021
12022         lpfc_hba_down_prep(phba);
12023
12024         /* Disable softirqs, including timers from obtaining phba->hbalock */
12025         local_bh_disable();
12026
12027         lpfc_fabric_abort_hba(phba);
12028
12029         spin_lock_irqsave(&phba->hbalock, flags);
12030
12031         /*
12032          * Error everything on the txq since these iocbs
12033          * have not been given to the FW yet.
12034          */
12035         if (phba->sli_rev != LPFC_SLI_REV4) {
12036                 for (i = 0; i < psli->num_rings; i++) {
12037                         pring = &psli->sli3_ring[i];
12038                         /* Only slow rings */
12039                         if (pring->ringno == LPFC_ELS_RING) {
12040                                 pring->flag |= LPFC_DEFERRED_RING_EVENT;
12041                                 /* Set the lpfc data pending flag */
12042                                 set_bit(LPFC_DATA_READY, &phba->data_flags);
12043                         }
12044                         list_splice_init(&pring->txq, &completions);
12045                 }
12046         } else {
12047                 list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12048                         pring = qp->pring;
12049                         if (!pring)
12050                                 continue;
12051                         spin_lock(&pring->ring_lock);
12052                         list_splice_init(&pring->txq, &completions);
12053                         spin_unlock(&pring->ring_lock);
12054                         if (pring == phba->sli4_hba.els_wq->pring) {
12055                                 pring->flag |= LPFC_DEFERRED_RING_EVENT;
12056                                 /* Set the lpfc data pending flag */
12057                                 set_bit(LPFC_DATA_READY, &phba->data_flags);
12058                         }
12059                 }
12060         }
12061         spin_unlock_irqrestore(&phba->hbalock, flags);
12062
12063         /* Cancel all the IOCBs from the completions list */
12064         lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
12065                               IOERR_SLI_DOWN);
12066
12067         spin_lock_irqsave(&phba->hbalock, flags);
12068         list_splice_init(&phba->elsbuf, &completions);
12069         phba->elsbuf_cnt = 0;
12070         phba->elsbuf_prev_cnt = 0;
12071         spin_unlock_irqrestore(&phba->hbalock, flags);
12072
12073         while (!list_empty(&completions)) {
12074                 list_remove_head(&completions, buf_ptr,
12075                         struct lpfc_dmabuf, list);
12076                 lpfc_mbuf_free(phba, buf_ptr->virt, buf_ptr->phys);
12077                 kfree(buf_ptr);
12078         }
12079
12080         /* Enable softirqs again, done with phba->hbalock */
12081         local_bh_enable();
12082
12083         /* Return any active mbox cmds */
12084         del_timer_sync(&psli->mbox_tmo);
12085
12086         spin_lock_irqsave(&phba->pport->work_port_lock, flags);
12087         phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
12088         spin_unlock_irqrestore(&phba->pport->work_port_lock, flags);
12089
12090         return 1;
12091 }
12092
12093 /**
12094  * lpfc_sli_pcimem_bcopy - SLI memory copy function
12095  * @srcp: Source memory pointer.
12096  * @destp: Destination memory pointer.
12097  * @cnt: Number of words required to be copied.
12098  *
12099  * This function is used for copying data between driver memory
12100  * and the SLI memory. This function also changes the endianness
12101  * of each word if native endianness is different from SLI
12102  * endianness. This function can be called with or without
12103  * lock.
12104  **/
12105 void
12106 lpfc_sli_pcimem_bcopy(void *srcp, void *destp, uint32_t cnt)
12107 {
12108         uint32_t *src = srcp;
12109         uint32_t *dest = destp;
12110         uint32_t ldata;
12111         int i;
12112
12113         for (i = 0; i < (int)cnt; i += sizeof (uint32_t)) {
12114                 ldata = *src;
12115                 ldata = le32_to_cpu(ldata);
12116                 *dest = ldata;
12117                 src++;
12118                 dest++;
12119         }
12120 }
12121
12122
12123 /**
12124  * lpfc_sli_bemem_bcopy - SLI memory copy function
12125  * @srcp: Source memory pointer.
12126  * @destp: Destination memory pointer.
12127  * @cnt: Number of words required to be copied.
12128  *
12129  * This function is used for copying data between a data structure
12130  * with big endian representation to local endianness.
12131  * This function can be called with or without lock.
12132  **/
12133 void
12134 lpfc_sli_bemem_bcopy(void *srcp, void *destp, uint32_t cnt)
12135 {
12136         uint32_t *src = srcp;
12137         uint32_t *dest = destp;
12138         uint32_t ldata;
12139         int i;
12140
12141         for (i = 0; i < (int)cnt; i += sizeof(uint32_t)) {
12142                 ldata = *src;
12143                 ldata = be32_to_cpu(ldata);
12144                 *dest = ldata;
12145                 src++;
12146                 dest++;
12147         }
12148 }
12149
12150 /**
12151  * lpfc_sli_ringpostbuf_put - Function to add a buffer to postbufq
12152  * @phba: Pointer to HBA context object.
12153  * @pring: Pointer to driver SLI ring object.
12154  * @mp: Pointer to driver buffer object.
12155  *
12156  * This function is called with no lock held.
12157  * It always return zero after adding the buffer to the postbufq
12158  * buffer list.
12159  **/
12160 int
12161 lpfc_sli_ringpostbuf_put(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12162                          struct lpfc_dmabuf *mp)
12163 {
12164         /* Stick struct lpfc_dmabuf at end of postbufq so driver can look it up
12165            later */
12166         spin_lock_irq(&phba->hbalock);
12167         list_add_tail(&mp->list, &pring->postbufq);
12168         pring->postbufq_cnt++;
12169         spin_unlock_irq(&phba->hbalock);
12170         return 0;
12171 }
12172
12173 /**
12174  * lpfc_sli_get_buffer_tag - allocates a tag for a CMD_QUE_XRI64_CX buffer
12175  * @phba: Pointer to HBA context object.
12176  *
12177  * When HBQ is enabled, buffers are searched based on tags. This function
12178  * allocates a tag for buffer posted using CMD_QUE_XRI64_CX iocb. The
12179  * tag is bit wise or-ed with QUE_BUFTAG_BIT to make sure that the tag
12180  * does not conflict with tags of buffer posted for unsolicited events.
12181  * The function returns the allocated tag. The function is called with
12182  * no locks held.
12183  **/
12184 uint32_t
12185 lpfc_sli_get_buffer_tag(struct lpfc_hba *phba)
12186 {
12187         spin_lock_irq(&phba->hbalock);
12188         phba->buffer_tag_count++;
12189         /*
12190          * Always set the QUE_BUFTAG_BIT to distiguish between
12191          * a tag assigned by HBQ.
12192          */
12193         phba->buffer_tag_count |= QUE_BUFTAG_BIT;
12194         spin_unlock_irq(&phba->hbalock);
12195         return phba->buffer_tag_count;
12196 }
12197
12198 /**
12199  * lpfc_sli_ring_taggedbuf_get - find HBQ buffer associated with given tag
12200  * @phba: Pointer to HBA context object.
12201  * @pring: Pointer to driver SLI ring object.
12202  * @tag: Buffer tag.
12203  *
12204  * Buffers posted using CMD_QUE_XRI64_CX iocb are in pring->postbufq
12205  * list. After HBA DMA data to these buffers, CMD_IOCB_RET_XRI64_CX
12206  * iocb is posted to the response ring with the tag of the buffer.
12207  * This function searches the pring->postbufq list using the tag
12208  * to find buffer associated with CMD_IOCB_RET_XRI64_CX
12209  * iocb. If the buffer is found then lpfc_dmabuf object of the
12210  * buffer is returned to the caller else NULL is returned.
12211  * This function is called with no lock held.
12212  **/
12213 struct lpfc_dmabuf *
12214 lpfc_sli_ring_taggedbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12215                         uint32_t tag)
12216 {
12217         struct lpfc_dmabuf *mp, *next_mp;
12218         struct list_head *slp = &pring->postbufq;
12219
12220         /* Search postbufq, from the beginning, looking for a match on tag */
12221         spin_lock_irq(&phba->hbalock);
12222         list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12223                 if (mp->buffer_tag == tag) {
12224                         list_del_init(&mp->list);
12225                         pring->postbufq_cnt--;
12226                         spin_unlock_irq(&phba->hbalock);
12227                         return mp;
12228                 }
12229         }
12230
12231         spin_unlock_irq(&phba->hbalock);
12232         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12233                         "0402 Cannot find virtual addr for buffer tag on "
12234                         "ring %d Data x%lx x%px x%px x%x\n",
12235                         pring->ringno, (unsigned long) tag,
12236                         slp->next, slp->prev, pring->postbufq_cnt);
12237
12238         return NULL;
12239 }
12240
12241 /**
12242  * lpfc_sli_ringpostbuf_get - search buffers for unsolicited CT and ELS events
12243  * @phba: Pointer to HBA context object.
12244  * @pring: Pointer to driver SLI ring object.
12245  * @phys: DMA address of the buffer.
12246  *
12247  * This function searches the buffer list using the dma_address
12248  * of unsolicited event to find the driver's lpfc_dmabuf object
12249  * corresponding to the dma_address. The function returns the
12250  * lpfc_dmabuf object if a buffer is found else it returns NULL.
12251  * This function is called by the ct and els unsolicited event
12252  * handlers to get the buffer associated with the unsolicited
12253  * event.
12254  *
12255  * This function is called with no lock held.
12256  **/
12257 struct lpfc_dmabuf *
12258 lpfc_sli_ringpostbuf_get(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12259                          dma_addr_t phys)
12260 {
12261         struct lpfc_dmabuf *mp, *next_mp;
12262         struct list_head *slp = &pring->postbufq;
12263
12264         /* Search postbufq, from the beginning, looking for a match on phys */
12265         spin_lock_irq(&phba->hbalock);
12266         list_for_each_entry_safe(mp, next_mp, &pring->postbufq, list) {
12267                 if (mp->phys == phys) {
12268                         list_del_init(&mp->list);
12269                         pring->postbufq_cnt--;
12270                         spin_unlock_irq(&phba->hbalock);
12271                         return mp;
12272                 }
12273         }
12274
12275         spin_unlock_irq(&phba->hbalock);
12276         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
12277                         "0410 Cannot find virtual addr for mapped buf on "
12278                         "ring %d Data x%llx x%px x%px x%x\n",
12279                         pring->ringno, (unsigned long long)phys,
12280                         slp->next, slp->prev, pring->postbufq_cnt);
12281         return NULL;
12282 }
12283
12284 /**
12285  * lpfc_sli_abort_els_cmpl - Completion handler for the els abort iocbs
12286  * @phba: Pointer to HBA context object.
12287  * @cmdiocb: Pointer to driver command iocb object.
12288  * @rspiocb: Pointer to driver response iocb object.
12289  *
12290  * This function is the completion handler for the abort iocbs for
12291  * ELS commands. This function is called from the ELS ring event
12292  * handler with no lock held. This function frees memory resources
12293  * associated with the abort iocb.
12294  **/
12295 static void
12296 lpfc_sli_abort_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12297                         struct lpfc_iocbq *rspiocb)
12298 {
12299         u32 ulp_status = get_job_ulpstatus(phba, rspiocb);
12300         u32 ulp_word4 = get_job_word4(phba, rspiocb);
12301         u8 cmnd = get_job_cmnd(phba, cmdiocb);
12302
12303         if (ulp_status) {
12304                 /*
12305                  * Assume that the port already completed and returned, or
12306                  * will return the iocb. Just Log the message.
12307                  */
12308                 if (phba->sli_rev < LPFC_SLI_REV4) {
12309                         if (cmnd == CMD_ABORT_XRI_CX &&
12310                             ulp_status == IOSTAT_LOCAL_REJECT &&
12311                             ulp_word4 == IOERR_ABORT_REQUESTED) {
12312                                 goto release_iocb;
12313                         }
12314                 }
12315         }
12316
12317         lpfc_printf_log(phba, KERN_INFO, LOG_ELS | LOG_SLI,
12318                         "0327 Abort els iocb complete x%px with io cmd xri %x "
12319                         "abort tag x%x abort status %x abort code %x\n",
12320                         cmdiocb, get_job_abtsiotag(phba, cmdiocb),
12321                         (phba->sli_rev == LPFC_SLI_REV4) ?
12322                         get_wqe_reqtag(cmdiocb) :
12323                         cmdiocb->iocb.ulpIoTag,
12324                         ulp_status, ulp_word4);
12325 release_iocb:
12326         lpfc_sli_release_iocbq(phba, cmdiocb);
12327         return;
12328 }
12329
12330 /**
12331  * lpfc_ignore_els_cmpl - Completion handler for aborted ELS command
12332  * @phba: Pointer to HBA context object.
12333  * @cmdiocb: Pointer to driver command iocb object.
12334  * @rspiocb: Pointer to driver response iocb object.
12335  *
12336  * The function is called from SLI ring event handler with no
12337  * lock held. This function is the completion handler for ELS commands
12338  * which are aborted. The function frees memory resources used for
12339  * the aborted ELS commands.
12340  **/
12341 void
12342 lpfc_ignore_els_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12343                      struct lpfc_iocbq *rspiocb)
12344 {
12345         struct lpfc_nodelist *ndlp = cmdiocb->ndlp;
12346         IOCB_t *irsp;
12347         LPFC_MBOXQ_t *mbox;
12348         u32 ulp_command, ulp_status, ulp_word4, iotag;
12349
12350         ulp_command = get_job_cmnd(phba, cmdiocb);
12351         ulp_status = get_job_ulpstatus(phba, rspiocb);
12352         ulp_word4 = get_job_word4(phba, rspiocb);
12353
12354         if (phba->sli_rev == LPFC_SLI_REV4) {
12355                 iotag = get_wqe_reqtag(cmdiocb);
12356         } else {
12357                 irsp = &rspiocb->iocb;
12358                 iotag = irsp->ulpIoTag;
12359
12360                 /* It is possible a PLOGI_RJT for NPIV ports to get aborted.
12361                  * The MBX_REG_LOGIN64 mbox command is freed back to the
12362                  * mbox_mem_pool here.
12363                  */
12364                 if (cmdiocb->context_un.mbox) {
12365                         mbox = cmdiocb->context_un.mbox;
12366                         lpfc_mbox_rsrc_cleanup(phba, mbox, MBOX_THD_UNLOCKED);
12367                         cmdiocb->context_un.mbox = NULL;
12368                 }
12369         }
12370
12371         /* ELS cmd tag <ulpIoTag> completes */
12372         lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
12373                         "0139 Ignoring ELS cmd code x%x ref cnt x%x Data: "
12374                         "x%x x%x x%x x%px\n",
12375                         ulp_command, kref_read(&cmdiocb->ndlp->kref),
12376                         ulp_status, ulp_word4, iotag, cmdiocb->ndlp);
12377         /*
12378          * Deref the ndlp after free_iocb. sli_release_iocb will access the ndlp
12379          * if exchange is busy.
12380          */
12381         if (ulp_command == CMD_GEN_REQUEST64_CR)
12382                 lpfc_ct_free_iocb(phba, cmdiocb);
12383         else
12384                 lpfc_els_free_iocb(phba, cmdiocb);
12385
12386         lpfc_nlp_put(ndlp);
12387 }
12388
12389 /**
12390  * lpfc_sli_issue_abort_iotag - Abort function for a command iocb
12391  * @phba: Pointer to HBA context object.
12392  * @pring: Pointer to driver SLI ring object.
12393  * @cmdiocb: Pointer to driver command iocb object.
12394  * @cmpl: completion function.
12395  *
12396  * This function issues an abort iocb for the provided command iocb. In case
12397  * of unloading, the abort iocb will not be issued to commands on the ELS
12398  * ring. Instead, the callback function shall be changed to those commands
12399  * so that nothing happens when them finishes. This function is called with
12400  * hbalock held andno ring_lock held (SLI4). The function returns IOCB_SUCCESS
12401  * when the command iocb is an abort request.
12402  *
12403  **/
12404 int
12405 lpfc_sli_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_sli_ring *pring,
12406                            struct lpfc_iocbq *cmdiocb, void *cmpl)
12407 {
12408         struct lpfc_vport *vport = cmdiocb->vport;
12409         struct lpfc_iocbq *abtsiocbp;
12410         int retval = IOCB_ERROR;
12411         unsigned long iflags;
12412         struct lpfc_nodelist *ndlp = NULL;
12413         u32 ulp_command = get_job_cmnd(phba, cmdiocb);
12414         u16 ulp_context, iotag;
12415         bool ia;
12416
12417         /*
12418          * There are certain command types we don't want to abort.  And we
12419          * don't want to abort commands that are already in the process of
12420          * being aborted.
12421          */
12422         if (ulp_command == CMD_ABORT_XRI_WQE ||
12423             ulp_command == CMD_ABORT_XRI_CN ||
12424             ulp_command == CMD_CLOSE_XRI_CN ||
12425             cmdiocb->cmd_flag & LPFC_DRIVER_ABORTED)
12426                 return IOCB_ABORTING;
12427
12428         if (!pring) {
12429                 if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12430                         cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12431                 else
12432                         cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12433                 return retval;
12434         }
12435
12436         /*
12437          * If we're unloading, don't abort iocb on the ELS ring, but change
12438          * the callback so that nothing happens when it finishes.
12439          */
12440         if (test_bit(FC_UNLOADING, &vport->load_flag) &&
12441             pring->ringno == LPFC_ELS_RING) {
12442                 if (cmdiocb->cmd_flag & LPFC_IO_FABRIC)
12443                         cmdiocb->fabric_cmd_cmpl = lpfc_ignore_els_cmpl;
12444                 else
12445                         cmdiocb->cmd_cmpl = lpfc_ignore_els_cmpl;
12446                 return retval;
12447         }
12448
12449         /* issue ABTS for this IOCB based on iotag */
12450         abtsiocbp = __lpfc_sli_get_iocbq(phba);
12451         if (abtsiocbp == NULL)
12452                 return IOCB_NORESOURCE;
12453
12454         /* This signals the response to set the correct status
12455          * before calling the completion handler
12456          */
12457         cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
12458
12459         if (phba->sli_rev == LPFC_SLI_REV4) {
12460                 ulp_context = cmdiocb->sli4_xritag;
12461                 iotag = abtsiocbp->iotag;
12462         } else {
12463                 iotag = cmdiocb->iocb.ulpIoTag;
12464                 if (pring->ringno == LPFC_ELS_RING) {
12465                         ndlp = cmdiocb->ndlp;
12466                         ulp_context = ndlp->nlp_rpi;
12467                 } else {
12468                         ulp_context = cmdiocb->iocb.ulpContext;
12469                 }
12470         }
12471
12472         /* Just close the exchange under certain conditions. */
12473         if (test_bit(FC_UNLOADING, &vport->load_flag) ||
12474             phba->link_state < LPFC_LINK_UP ||
12475             (phba->sli_rev == LPFC_SLI_REV4 &&
12476              phba->sli4_hba.link_state.status == LPFC_FC_LA_TYPE_LINK_DOWN) ||
12477             (phba->link_flag & LS_EXTERNAL_LOOPBACK))
12478                 ia = true;
12479         else
12480                 ia = false;
12481
12482         lpfc_sli_prep_abort_xri(phba, abtsiocbp, ulp_context, iotag,
12483                                 cmdiocb->iocb.ulpClass,
12484                                 LPFC_WQE_CQ_ID_DEFAULT, ia, false);
12485
12486         /* ABTS WQE must go to the same WQ as the WQE to be aborted */
12487         abtsiocbp->hba_wqidx = cmdiocb->hba_wqidx;
12488         if (cmdiocb->cmd_flag & LPFC_IO_FCP)
12489                 abtsiocbp->cmd_flag |= (LPFC_IO_FCP | LPFC_USE_FCPWQIDX);
12490
12491         if (cmdiocb->cmd_flag & LPFC_IO_FOF)
12492                 abtsiocbp->cmd_flag |= LPFC_IO_FOF;
12493
12494         if (cmpl)
12495                 abtsiocbp->cmd_cmpl = cmpl;
12496         else
12497                 abtsiocbp->cmd_cmpl = lpfc_sli_abort_els_cmpl;
12498         abtsiocbp->vport = vport;
12499
12500         if (phba->sli_rev == LPFC_SLI_REV4) {
12501                 pring = lpfc_sli4_calc_ring(phba, abtsiocbp);
12502                 if (unlikely(pring == NULL))
12503                         goto abort_iotag_exit;
12504                 /* Note: both hbalock and ring_lock need to be set here */
12505                 spin_lock_irqsave(&pring->ring_lock, iflags);
12506                 retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12507                         abtsiocbp, 0);
12508                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
12509         } else {
12510                 retval = __lpfc_sli_issue_iocb(phba, pring->ringno,
12511                         abtsiocbp, 0);
12512         }
12513
12514 abort_iotag_exit:
12515
12516         lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI,
12517                          "0339 Abort IO XRI x%x, Original iotag x%x, "
12518                          "abort tag x%x Cmdjob : x%px Abortjob : x%px "
12519                          "retval x%x : IA %d cmd_cmpl %ps\n",
12520                          ulp_context, (phba->sli_rev == LPFC_SLI_REV4) ?
12521                          cmdiocb->iotag : iotag, iotag, cmdiocb, abtsiocbp,
12522                          retval, ia, abtsiocbp->cmd_cmpl);
12523         if (retval) {
12524                 cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
12525                 __lpfc_sli_release_iocbq(phba, abtsiocbp);
12526         }
12527
12528         /*
12529          * Caller to this routine should check for IOCB_ERROR
12530          * and handle it properly.  This routine no longer removes
12531          * iocb off txcmplq and call compl in case of IOCB_ERROR.
12532          */
12533         return retval;
12534 }
12535
12536 /**
12537  * lpfc_sli_hba_iocb_abort - Abort all iocbs to an hba.
12538  * @phba: pointer to lpfc HBA data structure.
12539  *
12540  * This routine will abort all pending and outstanding iocbs to an HBA.
12541  **/
12542 void
12543 lpfc_sli_hba_iocb_abort(struct lpfc_hba *phba)
12544 {
12545         struct lpfc_sli *psli = &phba->sli;
12546         struct lpfc_sli_ring *pring;
12547         struct lpfc_queue *qp = NULL;
12548         int i;
12549
12550         if (phba->sli_rev != LPFC_SLI_REV4) {
12551                 for (i = 0; i < psli->num_rings; i++) {
12552                         pring = &psli->sli3_ring[i];
12553                         lpfc_sli_abort_iocb_ring(phba, pring);
12554                 }
12555                 return;
12556         }
12557         list_for_each_entry(qp, &phba->sli4_hba.lpfc_wq_list, wq_list) {
12558                 pring = qp->pring;
12559                 if (!pring)
12560                         continue;
12561                 lpfc_sli_abort_iocb_ring(phba, pring);
12562         }
12563 }
12564
12565 /**
12566  * lpfc_sli_validate_fcp_iocb_for_abort - filter iocbs appropriate for FCP aborts
12567  * @iocbq: Pointer to iocb object.
12568  * @vport: Pointer to driver virtual port object.
12569  *
12570  * This function acts as an iocb filter for functions which abort FCP iocbs.
12571  *
12572  * Return values
12573  * -ENODEV, if a null iocb or vport ptr is encountered
12574  * -EINVAL, if the iocb is not an FCP I/O, not on the TX cmpl queue, premarked as
12575  *          driver already started the abort process, or is an abort iocb itself
12576  * 0, passes criteria for aborting the FCP I/O iocb
12577  **/
12578 static int
12579 lpfc_sli_validate_fcp_iocb_for_abort(struct lpfc_iocbq *iocbq,
12580                                      struct lpfc_vport *vport)
12581 {
12582         u8 ulp_command;
12583
12584         /* No null ptr vports */
12585         if (!iocbq || iocbq->vport != vport)
12586                 return -ENODEV;
12587
12588         /* iocb must be for FCP IO, already exists on the TX cmpl queue,
12589          * can't be premarked as driver aborted, nor be an ABORT iocb itself
12590          */
12591         ulp_command = get_job_cmnd(vport->phba, iocbq);
12592         if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12593             !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ) ||
12594             (iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12595             (ulp_command == CMD_ABORT_XRI_CN ||
12596              ulp_command == CMD_CLOSE_XRI_CN ||
12597              ulp_command == CMD_ABORT_XRI_WQE))
12598                 return -EINVAL;
12599
12600         return 0;
12601 }
12602
12603 /**
12604  * lpfc_sli_validate_fcp_iocb - validate commands associated with a SCSI target
12605  * @iocbq: Pointer to driver iocb object.
12606  * @vport: Pointer to driver virtual port object.
12607  * @tgt_id: SCSI ID of the target.
12608  * @lun_id: LUN ID of the scsi device.
12609  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST
12610  *
12611  * This function acts as an iocb filter for validating a lun/SCSI target/SCSI
12612  * host.
12613  *
12614  * It will return
12615  * 0 if the filtering criteria is met for the given iocb and will return
12616  * 1 if the filtering criteria is not met.
12617  * If ctx_cmd == LPFC_CTX_LUN, the function returns 0 only if the
12618  * given iocb is for the SCSI device specified by vport, tgt_id and
12619  * lun_id parameter.
12620  * If ctx_cmd == LPFC_CTX_TGT,  the function returns 0 only if the
12621  * given iocb is for the SCSI target specified by vport and tgt_id
12622  * parameters.
12623  * If ctx_cmd == LPFC_CTX_HOST, the function returns 0 only if the
12624  * given iocb is for the SCSI host associated with the given vport.
12625  * This function is called with no locks held.
12626  **/
12627 static int
12628 lpfc_sli_validate_fcp_iocb(struct lpfc_iocbq *iocbq, struct lpfc_vport *vport,
12629                            uint16_t tgt_id, uint64_t lun_id,
12630                            lpfc_ctx_cmd ctx_cmd)
12631 {
12632         struct lpfc_io_buf *lpfc_cmd;
12633         int rc = 1;
12634
12635         lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12636
12637         if (lpfc_cmd->pCmd == NULL)
12638                 return rc;
12639
12640         switch (ctx_cmd) {
12641         case LPFC_CTX_LUN:
12642                 if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12643                     (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id) &&
12644                     (scsilun_to_int(&lpfc_cmd->fcp_cmnd->fcp_lun) == lun_id))
12645                         rc = 0;
12646                 break;
12647         case LPFC_CTX_TGT:
12648                 if ((lpfc_cmd->rdata) && (lpfc_cmd->rdata->pnode) &&
12649                     (lpfc_cmd->rdata->pnode->nlp_sid == tgt_id))
12650                         rc = 0;
12651                 break;
12652         case LPFC_CTX_HOST:
12653                 rc = 0;
12654                 break;
12655         default:
12656                 printk(KERN_ERR "%s: Unknown context cmd type, value %d\n",
12657                         __func__, ctx_cmd);
12658                 break;
12659         }
12660
12661         return rc;
12662 }
12663
12664 /**
12665  * lpfc_sli_sum_iocb - Function to count the number of FCP iocbs pending
12666  * @vport: Pointer to virtual port.
12667  * @tgt_id: SCSI ID of the target.
12668  * @lun_id: LUN ID of the scsi device.
12669  * @ctx_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12670  *
12671  * This function returns number of FCP commands pending for the vport.
12672  * When ctx_cmd == LPFC_CTX_LUN, the function returns number of FCP
12673  * commands pending on the vport associated with SCSI device specified
12674  * by tgt_id and lun_id parameters.
12675  * When ctx_cmd == LPFC_CTX_TGT, the function returns number of FCP
12676  * commands pending on the vport associated with SCSI target specified
12677  * by tgt_id parameter.
12678  * When ctx_cmd == LPFC_CTX_HOST, the function returns number of FCP
12679  * commands pending on the vport.
12680  * This function returns the number of iocbs which satisfy the filter.
12681  * This function is called without any lock held.
12682  **/
12683 int
12684 lpfc_sli_sum_iocb(struct lpfc_vport *vport, uint16_t tgt_id, uint64_t lun_id,
12685                   lpfc_ctx_cmd ctx_cmd)
12686 {
12687         struct lpfc_hba *phba = vport->phba;
12688         struct lpfc_iocbq *iocbq;
12689         int sum, i;
12690         unsigned long iflags;
12691         u8 ulp_command;
12692
12693         spin_lock_irqsave(&phba->hbalock, iflags);
12694         for (i = 1, sum = 0; i <= phba->sli.last_iotag; i++) {
12695                 iocbq = phba->sli.iocbq_lookup[i];
12696
12697                 if (!iocbq || iocbq->vport != vport)
12698                         continue;
12699                 if (!(iocbq->cmd_flag & LPFC_IO_FCP) ||
12700                     !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ))
12701                         continue;
12702
12703                 /* Include counting outstanding aborts */
12704                 ulp_command = get_job_cmnd(phba, iocbq);
12705                 if (ulp_command == CMD_ABORT_XRI_CN ||
12706                     ulp_command == CMD_CLOSE_XRI_CN ||
12707                     ulp_command == CMD_ABORT_XRI_WQE) {
12708                         sum++;
12709                         continue;
12710                 }
12711
12712                 if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12713                                                ctx_cmd) == 0)
12714                         sum++;
12715         }
12716         spin_unlock_irqrestore(&phba->hbalock, iflags);
12717
12718         return sum;
12719 }
12720
12721 /**
12722  * lpfc_sli_abort_fcp_cmpl - Completion handler function for aborted FCP IOCBs
12723  * @phba: Pointer to HBA context object
12724  * @cmdiocb: Pointer to command iocb object.
12725  * @rspiocb: Pointer to response iocb object.
12726  *
12727  * This function is called when an aborted FCP iocb completes. This
12728  * function is called by the ring event handler with no lock held.
12729  * This function frees the iocb.
12730  **/
12731 void
12732 lpfc_sli_abort_fcp_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
12733                         struct lpfc_iocbq *rspiocb)
12734 {
12735         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
12736                         "3096 ABORT_XRI_CX completing on rpi x%x "
12737                         "original iotag x%x, abort cmd iotag x%x "
12738                         "status 0x%x, reason 0x%x\n",
12739                         (phba->sli_rev == LPFC_SLI_REV4) ?
12740                         cmdiocb->sli4_xritag :
12741                         cmdiocb->iocb.un.acxri.abortContextTag,
12742                         get_job_abtsiotag(phba, cmdiocb),
12743                         cmdiocb->iotag, get_job_ulpstatus(phba, rspiocb),
12744                         get_job_word4(phba, rspiocb));
12745         lpfc_sli_release_iocbq(phba, cmdiocb);
12746         return;
12747 }
12748
12749 /**
12750  * lpfc_sli_abort_iocb - issue abort for all commands on a host/target/LUN
12751  * @vport: Pointer to virtual port.
12752  * @tgt_id: SCSI ID of the target.
12753  * @lun_id: LUN ID of the scsi device.
12754  * @abort_cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12755  *
12756  * This function sends an abort command for every SCSI command
12757  * associated with the given virtual port pending on the ring
12758  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12759  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12760  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12761  * followed by lpfc_sli_validate_fcp_iocb.
12762  *
12763  * When abort_cmd == LPFC_CTX_LUN, the function sends abort only to the
12764  * FCP iocbs associated with lun specified by tgt_id and lun_id
12765  * parameters
12766  * When abort_cmd == LPFC_CTX_TGT, the function sends abort only to the
12767  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12768  * When abort_cmd == LPFC_CTX_HOST, the function sends abort to all
12769  * FCP iocbs associated with virtual port.
12770  * The pring used for SLI3 is sli3_ring[LPFC_FCP_RING], for SLI4
12771  * lpfc_sli4_calc_ring is used.
12772  * This function returns number of iocbs it failed to abort.
12773  * This function is called with no locks held.
12774  **/
12775 int
12776 lpfc_sli_abort_iocb(struct lpfc_vport *vport, u16 tgt_id, u64 lun_id,
12777                     lpfc_ctx_cmd abort_cmd)
12778 {
12779         struct lpfc_hba *phba = vport->phba;
12780         struct lpfc_sli_ring *pring = NULL;
12781         struct lpfc_iocbq *iocbq;
12782         int errcnt = 0, ret_val = 0;
12783         unsigned long iflags;
12784         int i;
12785
12786         /* all I/Os are in process of being flushed */
12787         if (test_bit(HBA_IOQ_FLUSH, &phba->hba_flag))
12788                 return errcnt;
12789
12790         for (i = 1; i <= phba->sli.last_iotag; i++) {
12791                 iocbq = phba->sli.iocbq_lookup[i];
12792
12793                 if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12794                         continue;
12795
12796                 if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12797                                                abort_cmd) != 0)
12798                         continue;
12799
12800                 spin_lock_irqsave(&phba->hbalock, iflags);
12801                 if (phba->sli_rev == LPFC_SLI_REV3) {
12802                         pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
12803                 } else if (phba->sli_rev == LPFC_SLI_REV4) {
12804                         pring = lpfc_sli4_calc_ring(phba, iocbq);
12805                 }
12806                 ret_val = lpfc_sli_issue_abort_iotag(phba, pring, iocbq,
12807                                                      lpfc_sli_abort_fcp_cmpl);
12808                 spin_unlock_irqrestore(&phba->hbalock, iflags);
12809                 if (ret_val != IOCB_SUCCESS)
12810                         errcnt++;
12811         }
12812
12813         return errcnt;
12814 }
12815
12816 /**
12817  * lpfc_sli_abort_taskmgmt - issue abort for all commands on a host/target/LUN
12818  * @vport: Pointer to virtual port.
12819  * @pring: Pointer to driver SLI ring object.
12820  * @tgt_id: SCSI ID of the target.
12821  * @lun_id: LUN ID of the scsi device.
12822  * @cmd: LPFC_CTX_LUN/LPFC_CTX_TGT/LPFC_CTX_HOST.
12823  *
12824  * This function sends an abort command for every SCSI command
12825  * associated with the given virtual port pending on the ring
12826  * filtered by lpfc_sli_validate_fcp_iocb_for_abort and then
12827  * lpfc_sli_validate_fcp_iocb function.  The ordering for validation before
12828  * submitting abort iocbs must be lpfc_sli_validate_fcp_iocb_for_abort
12829  * followed by lpfc_sli_validate_fcp_iocb.
12830  *
12831  * When taskmgmt_cmd == LPFC_CTX_LUN, the function sends abort only to the
12832  * FCP iocbs associated with lun specified by tgt_id and lun_id
12833  * parameters
12834  * When taskmgmt_cmd == LPFC_CTX_TGT, the function sends abort only to the
12835  * FCP iocbs associated with SCSI target specified by tgt_id parameter.
12836  * When taskmgmt_cmd == LPFC_CTX_HOST, the function sends abort to all
12837  * FCP iocbs associated with virtual port.
12838  * This function returns number of iocbs it aborted .
12839  * This function is called with no locks held right after a taskmgmt
12840  * command is sent.
12841  **/
12842 int
12843 lpfc_sli_abort_taskmgmt(struct lpfc_vport *vport, struct lpfc_sli_ring *pring,
12844                         uint16_t tgt_id, uint64_t lun_id, lpfc_ctx_cmd cmd)
12845 {
12846         struct lpfc_hba *phba = vport->phba;
12847         struct lpfc_io_buf *lpfc_cmd;
12848         struct lpfc_iocbq *abtsiocbq;
12849         struct lpfc_nodelist *ndlp = NULL;
12850         struct lpfc_iocbq *iocbq;
12851         int sum, i, ret_val;
12852         unsigned long iflags;
12853         struct lpfc_sli_ring *pring_s4 = NULL;
12854         u16 ulp_context, iotag, cqid = LPFC_WQE_CQ_ID_DEFAULT;
12855         bool ia;
12856
12857         /* all I/Os are in process of being flushed */
12858         if (test_bit(HBA_IOQ_FLUSH, &phba->hba_flag))
12859                 return 0;
12860
12861         sum = 0;
12862
12863         spin_lock_irqsave(&phba->hbalock, iflags);
12864         for (i = 1; i <= phba->sli.last_iotag; i++) {
12865                 iocbq = phba->sli.iocbq_lookup[i];
12866
12867                 if (lpfc_sli_validate_fcp_iocb_for_abort(iocbq, vport))
12868                         continue;
12869
12870                 if (lpfc_sli_validate_fcp_iocb(iocbq, vport, tgt_id, lun_id,
12871                                                cmd) != 0)
12872                         continue;
12873
12874                 /* Guard against IO completion being called at same time */
12875                 lpfc_cmd = container_of(iocbq, struct lpfc_io_buf, cur_iocbq);
12876                 spin_lock(&lpfc_cmd->buf_lock);
12877
12878                 if (!lpfc_cmd->pCmd) {
12879                         spin_unlock(&lpfc_cmd->buf_lock);
12880                         continue;
12881                 }
12882
12883                 if (phba->sli_rev == LPFC_SLI_REV4) {
12884                         pring_s4 =
12885                             phba->sli4_hba.hdwq[iocbq->hba_wqidx].io_wq->pring;
12886                         if (!pring_s4) {
12887                                 spin_unlock(&lpfc_cmd->buf_lock);
12888                                 continue;
12889                         }
12890                         /* Note: both hbalock and ring_lock must be set here */
12891                         spin_lock(&pring_s4->ring_lock);
12892                 }
12893
12894                 /*
12895                  * If the iocbq is already being aborted, don't take a second
12896                  * action, but do count it.
12897                  */
12898                 if ((iocbq->cmd_flag & LPFC_DRIVER_ABORTED) ||
12899                     !(iocbq->cmd_flag & LPFC_IO_ON_TXCMPLQ)) {
12900                         if (phba->sli_rev == LPFC_SLI_REV4)
12901                                 spin_unlock(&pring_s4->ring_lock);
12902                         spin_unlock(&lpfc_cmd->buf_lock);
12903                         continue;
12904                 }
12905
12906                 /* issue ABTS for this IOCB based on iotag */
12907                 abtsiocbq = __lpfc_sli_get_iocbq(phba);
12908                 if (!abtsiocbq) {
12909                         if (phba->sli_rev == LPFC_SLI_REV4)
12910                                 spin_unlock(&pring_s4->ring_lock);
12911                         spin_unlock(&lpfc_cmd->buf_lock);
12912                         continue;
12913                 }
12914
12915                 if (phba->sli_rev == LPFC_SLI_REV4) {
12916                         iotag = abtsiocbq->iotag;
12917                         ulp_context = iocbq->sli4_xritag;
12918                         cqid = lpfc_cmd->hdwq->io_cq_map;
12919                 } else {
12920                         iotag = iocbq->iocb.ulpIoTag;
12921                         if (pring->ringno == LPFC_ELS_RING) {
12922                                 ndlp = iocbq->ndlp;
12923                                 ulp_context = ndlp->nlp_rpi;
12924                         } else {
12925                                 ulp_context = iocbq->iocb.ulpContext;
12926                         }
12927                 }
12928
12929                 ndlp = lpfc_cmd->rdata->pnode;
12930
12931                 if (lpfc_is_link_up(phba) &&
12932                     (ndlp && ndlp->nlp_state == NLP_STE_MAPPED_NODE) &&
12933                     !(phba->link_flag & LS_EXTERNAL_LOOPBACK))
12934                         ia = false;
12935                 else
12936                         ia = true;
12937
12938                 lpfc_sli_prep_abort_xri(phba, abtsiocbq, ulp_context, iotag,
12939                                         iocbq->iocb.ulpClass, cqid,
12940                                         ia, false);
12941
12942                 abtsiocbq->vport = vport;
12943
12944                 /* ABTS WQE must go to the same WQ as the WQE to be aborted */
12945                 abtsiocbq->hba_wqidx = iocbq->hba_wqidx;
12946                 if (iocbq->cmd_flag & LPFC_IO_FCP)
12947                         abtsiocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
12948                 if (iocbq->cmd_flag & LPFC_IO_FOF)
12949                         abtsiocbq->cmd_flag |= LPFC_IO_FOF;
12950
12951                 /* Setup callback routine and issue the command. */
12952                 abtsiocbq->cmd_cmpl = lpfc_sli_abort_fcp_cmpl;
12953
12954                 /*
12955                  * Indicate the IO is being aborted by the driver and set
12956                  * the caller's flag into the aborted IO.
12957                  */
12958                 iocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
12959
12960                 if (phba->sli_rev == LPFC_SLI_REV4) {
12961                         ret_val = __lpfc_sli_issue_iocb(phba, pring_s4->ringno,
12962                                                         abtsiocbq, 0);
12963                         spin_unlock(&pring_s4->ring_lock);
12964                 } else {
12965                         ret_val = __lpfc_sli_issue_iocb(phba, pring->ringno,
12966                                                         abtsiocbq, 0);
12967                 }
12968
12969                 spin_unlock(&lpfc_cmd->buf_lock);
12970
12971                 if (ret_val == IOCB_ERROR)
12972                         __lpfc_sli_release_iocbq(phba, abtsiocbq);
12973                 else
12974                         sum++;
12975         }
12976         spin_unlock_irqrestore(&phba->hbalock, iflags);
12977         return sum;
12978 }
12979
12980 /**
12981  * lpfc_sli_wake_iocb_wait - lpfc_sli_issue_iocb_wait's completion handler
12982  * @phba: Pointer to HBA context object.
12983  * @cmdiocbq: Pointer to command iocb.
12984  * @rspiocbq: Pointer to response iocb.
12985  *
12986  * This function is the completion handler for iocbs issued using
12987  * lpfc_sli_issue_iocb_wait function. This function is called by the
12988  * ring event handler function without any lock held. This function
12989  * can be called from both worker thread context and interrupt
12990  * context. This function also can be called from other thread which
12991  * cleans up the SLI layer objects.
12992  * This function copy the contents of the response iocb to the
12993  * response iocb memory object provided by the caller of
12994  * lpfc_sli_issue_iocb_wait and then wakes up the thread which
12995  * sleeps for the iocb completion.
12996  **/
12997 static void
12998 lpfc_sli_wake_iocb_wait(struct lpfc_hba *phba,
12999                         struct lpfc_iocbq *cmdiocbq,
13000                         struct lpfc_iocbq *rspiocbq)
13001 {
13002         wait_queue_head_t *pdone_q;
13003         unsigned long iflags;
13004         struct lpfc_io_buf *lpfc_cmd;
13005         size_t offset = offsetof(struct lpfc_iocbq, wqe);
13006
13007         spin_lock_irqsave(&phba->hbalock, iflags);
13008         if (cmdiocbq->cmd_flag & LPFC_IO_WAKE_TMO) {
13009
13010                 /*
13011                  * A time out has occurred for the iocb.  If a time out
13012                  * completion handler has been supplied, call it.  Otherwise,
13013                  * just free the iocbq.
13014                  */
13015
13016                 spin_unlock_irqrestore(&phba->hbalock, iflags);
13017                 cmdiocbq->cmd_cmpl = cmdiocbq->wait_cmd_cmpl;
13018                 cmdiocbq->wait_cmd_cmpl = NULL;
13019                 if (cmdiocbq->cmd_cmpl)
13020                         cmdiocbq->cmd_cmpl(phba, cmdiocbq, NULL);
13021                 else
13022                         lpfc_sli_release_iocbq(phba, cmdiocbq);
13023                 return;
13024         }
13025
13026         /* Copy the contents of the local rspiocb into the caller's buffer. */
13027         cmdiocbq->cmd_flag |= LPFC_IO_WAKE;
13028         if (cmdiocbq->rsp_iocb && rspiocbq)
13029                 memcpy((char *)cmdiocbq->rsp_iocb + offset,
13030                        (char *)rspiocbq + offset, sizeof(*rspiocbq) - offset);
13031
13032         /* Set the exchange busy flag for task management commands */
13033         if ((cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
13034             !(cmdiocbq->cmd_flag & LPFC_IO_LIBDFC)) {
13035                 lpfc_cmd = container_of(cmdiocbq, struct lpfc_io_buf,
13036                                         cur_iocbq);
13037                 if (rspiocbq && (rspiocbq->cmd_flag & LPFC_EXCHANGE_BUSY))
13038                         lpfc_cmd->flags |= LPFC_SBUF_XBUSY;
13039                 else
13040                         lpfc_cmd->flags &= ~LPFC_SBUF_XBUSY;
13041         }
13042
13043         pdone_q = cmdiocbq->context_un.wait_queue;
13044         if (pdone_q)
13045                 wake_up(pdone_q);
13046         spin_unlock_irqrestore(&phba->hbalock, iflags);
13047         return;
13048 }
13049
13050 /**
13051  * lpfc_chk_iocb_flg - Test IOCB flag with lock held.
13052  * @phba: Pointer to HBA context object..
13053  * @piocbq: Pointer to command iocb.
13054  * @flag: Flag to test.
13055  *
13056  * This routine grabs the hbalock and then test the cmd_flag to
13057  * see if the passed in flag is set.
13058  * Returns:
13059  * 1 if flag is set.
13060  * 0 if flag is not set.
13061  **/
13062 static int
13063 lpfc_chk_iocb_flg(struct lpfc_hba *phba,
13064                  struct lpfc_iocbq *piocbq, uint32_t flag)
13065 {
13066         unsigned long iflags;
13067         int ret;
13068
13069         spin_lock_irqsave(&phba->hbalock, iflags);
13070         ret = piocbq->cmd_flag & flag;
13071         spin_unlock_irqrestore(&phba->hbalock, iflags);
13072         return ret;
13073
13074 }
13075
13076 /**
13077  * lpfc_sli_issue_iocb_wait - Synchronous function to issue iocb commands
13078  * @phba: Pointer to HBA context object..
13079  * @ring_number: Ring number
13080  * @piocb: Pointer to command iocb.
13081  * @prspiocbq: Pointer to response iocb.
13082  * @timeout: Timeout in number of seconds.
13083  *
13084  * This function issues the iocb to firmware and waits for the
13085  * iocb to complete. The cmd_cmpl field of the shall be used
13086  * to handle iocbs which time out. If the field is NULL, the
13087  * function shall free the iocbq structure.  If more clean up is
13088  * needed, the caller is expected to provide a completion function
13089  * that will provide the needed clean up.  If the iocb command is
13090  * not completed within timeout seconds, the function will either
13091  * free the iocbq structure (if cmd_cmpl == NULL) or execute the
13092  * completion function set in the cmd_cmpl field and then return
13093  * a status of IOCB_TIMEDOUT.  The caller should not free the iocb
13094  * resources if this function returns IOCB_TIMEDOUT.
13095  * The function waits for the iocb completion using an
13096  * non-interruptible wait.
13097  * This function will sleep while waiting for iocb completion.
13098  * So, this function should not be called from any context which
13099  * does not allow sleeping. Due to the same reason, this function
13100  * cannot be called with interrupt disabled.
13101  * This function assumes that the iocb completions occur while
13102  * this function sleep. So, this function cannot be called from
13103  * the thread which process iocb completion for this ring.
13104  * This function clears the cmd_flag of the iocb object before
13105  * issuing the iocb and the iocb completion handler sets this
13106  * flag and wakes this thread when the iocb completes.
13107  * The contents of the response iocb will be copied to prspiocbq
13108  * by the completion handler when the command completes.
13109  * This function returns IOCB_SUCCESS when success.
13110  * This function is called with no lock held.
13111  **/
13112 int
13113 lpfc_sli_issue_iocb_wait(struct lpfc_hba *phba,
13114                          uint32_t ring_number,
13115                          struct lpfc_iocbq *piocb,
13116                          struct lpfc_iocbq *prspiocbq,
13117                          uint32_t timeout)
13118 {
13119         DECLARE_WAIT_QUEUE_HEAD_ONSTACK(done_q);
13120         long timeleft, timeout_req = 0;
13121         int retval = IOCB_SUCCESS;
13122         uint32_t creg_val;
13123         struct lpfc_iocbq *iocb;
13124         int txq_cnt = 0;
13125         int txcmplq_cnt = 0;
13126         struct lpfc_sli_ring *pring;
13127         unsigned long iflags;
13128         bool iocb_completed = true;
13129
13130         if (phba->sli_rev >= LPFC_SLI_REV4) {
13131                 lpfc_sli_prep_wqe(phba, piocb);
13132
13133                 pring = lpfc_sli4_calc_ring(phba, piocb);
13134         } else
13135                 pring = &phba->sli.sli3_ring[ring_number];
13136         /*
13137          * If the caller has provided a response iocbq buffer, then rsp_iocb
13138          * is NULL or its an error.
13139          */
13140         if (prspiocbq) {
13141                 if (piocb->rsp_iocb)
13142                         return IOCB_ERROR;
13143                 piocb->rsp_iocb = prspiocbq;
13144         }
13145
13146         piocb->wait_cmd_cmpl = piocb->cmd_cmpl;
13147         piocb->cmd_cmpl = lpfc_sli_wake_iocb_wait;
13148         piocb->context_un.wait_queue = &done_q;
13149         piocb->cmd_flag &= ~(LPFC_IO_WAKE | LPFC_IO_WAKE_TMO);
13150
13151         if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13152                 if (lpfc_readl(phba->HCregaddr, &creg_val))
13153                         return IOCB_ERROR;
13154                 creg_val |= (HC_R0INT_ENA << LPFC_FCP_RING);
13155                 writel(creg_val, phba->HCregaddr);
13156                 readl(phba->HCregaddr); /* flush */
13157         }
13158
13159         retval = lpfc_sli_issue_iocb(phba, ring_number, piocb,
13160                                      SLI_IOCB_RET_IOCB);
13161         if (retval == IOCB_SUCCESS) {
13162                 timeout_req = msecs_to_jiffies(timeout * 1000);
13163                 timeleft = wait_event_timeout(done_q,
13164                                 lpfc_chk_iocb_flg(phba, piocb, LPFC_IO_WAKE),
13165                                 timeout_req);
13166                 spin_lock_irqsave(&phba->hbalock, iflags);
13167                 if (!(piocb->cmd_flag & LPFC_IO_WAKE)) {
13168
13169                         /*
13170                          * IOCB timed out.  Inform the wake iocb wait
13171                          * completion function and set local status
13172                          */
13173
13174                         iocb_completed = false;
13175                         piocb->cmd_flag |= LPFC_IO_WAKE_TMO;
13176                 }
13177                 spin_unlock_irqrestore(&phba->hbalock, iflags);
13178                 if (iocb_completed) {
13179                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13180                                         "0331 IOCB wake signaled\n");
13181                         /* Note: we are not indicating if the IOCB has a success
13182                          * status or not - that's for the caller to check.
13183                          * IOCB_SUCCESS means just that the command was sent and
13184                          * completed. Not that it completed successfully.
13185                          * */
13186                 } else if (timeleft == 0) {
13187                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13188                                         "0338 IOCB wait timeout error - no "
13189                                         "wake response Data x%x\n", timeout);
13190                         retval = IOCB_TIMEDOUT;
13191                 } else {
13192                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13193                                         "0330 IOCB wake NOT set, "
13194                                         "Data x%x x%lx\n",
13195                                         timeout, (timeleft / jiffies));
13196                         retval = IOCB_TIMEDOUT;
13197                 }
13198         } else if (retval == IOCB_BUSY) {
13199                 if (phba->cfg_log_verbose & LOG_SLI) {
13200                         list_for_each_entry(iocb, &pring->txq, list) {
13201                                 txq_cnt++;
13202                         }
13203                         list_for_each_entry(iocb, &pring->txcmplq, list) {
13204                                 txcmplq_cnt++;
13205                         }
13206                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13207                                 "2818 Max IOCBs %d txq cnt %d txcmplq cnt %d\n",
13208                                 phba->iocb_cnt, txq_cnt, txcmplq_cnt);
13209                 }
13210                 return retval;
13211         } else {
13212                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
13213                                 "0332 IOCB wait issue failed, Data x%x\n",
13214                                 retval);
13215                 retval = IOCB_ERROR;
13216         }
13217
13218         if (phba->cfg_poll & DISABLE_FCP_RING_INT) {
13219                 if (lpfc_readl(phba->HCregaddr, &creg_val))
13220                         return IOCB_ERROR;
13221                 creg_val &= ~(HC_R0INT_ENA << LPFC_FCP_RING);
13222                 writel(creg_val, phba->HCregaddr);
13223                 readl(phba->HCregaddr); /* flush */
13224         }
13225
13226         if (prspiocbq)
13227                 piocb->rsp_iocb = NULL;
13228
13229         piocb->context_un.wait_queue = NULL;
13230         piocb->cmd_cmpl = NULL;
13231         return retval;
13232 }
13233
13234 /**
13235  * lpfc_sli_issue_mbox_wait - Synchronous function to issue mailbox
13236  * @phba: Pointer to HBA context object.
13237  * @pmboxq: Pointer to driver mailbox object.
13238  * @timeout: Timeout in number of seconds.
13239  *
13240  * This function issues the mailbox to firmware and waits for the
13241  * mailbox command to complete. If the mailbox command is not
13242  * completed within timeout seconds, it returns MBX_TIMEOUT.
13243  * The function waits for the mailbox completion using an
13244  * interruptible wait. If the thread is woken up due to a
13245  * signal, MBX_TIMEOUT error is returned to the caller. Caller
13246  * should not free the mailbox resources, if this function returns
13247  * MBX_TIMEOUT.
13248  * This function will sleep while waiting for mailbox completion.
13249  * So, this function should not be called from any context which
13250  * does not allow sleeping. Due to the same reason, this function
13251  * cannot be called with interrupt disabled.
13252  * This function assumes that the mailbox completion occurs while
13253  * this function sleep. So, this function cannot be called from
13254  * the worker thread which processes mailbox completion.
13255  * This function is called in the context of HBA management
13256  * applications.
13257  * This function returns MBX_SUCCESS when successful.
13258  * This function is called with no lock held.
13259  **/
13260 int
13261 lpfc_sli_issue_mbox_wait(struct lpfc_hba *phba, LPFC_MBOXQ_t *pmboxq,
13262                          uint32_t timeout)
13263 {
13264         struct completion mbox_done;
13265         int retval;
13266         unsigned long flag;
13267
13268         pmboxq->mbox_flag &= ~LPFC_MBX_WAKE;
13269         /* setup wake call as IOCB callback */
13270         pmboxq->mbox_cmpl = lpfc_sli_wake_mbox_wait;
13271
13272         /* setup ctx_u field to pass wait_queue pointer to wake function  */
13273         init_completion(&mbox_done);
13274         pmboxq->ctx_u.mbox_wait = &mbox_done;
13275         /* now issue the command */
13276         retval = lpfc_sli_issue_mbox(phba, pmboxq, MBX_NOWAIT);
13277         if (retval == MBX_BUSY || retval == MBX_SUCCESS) {
13278                 wait_for_completion_timeout(&mbox_done,
13279                                             msecs_to_jiffies(timeout * 1000));
13280
13281                 spin_lock_irqsave(&phba->hbalock, flag);
13282                 pmboxq->ctx_u.mbox_wait = NULL;
13283                 /*
13284                  * if LPFC_MBX_WAKE flag is set the mailbox is completed
13285                  * else do not free the resources.
13286                  */
13287                 if (pmboxq->mbox_flag & LPFC_MBX_WAKE) {
13288                         retval = MBX_SUCCESS;
13289                 } else {
13290                         retval = MBX_TIMEOUT;
13291                         pmboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
13292                 }
13293                 spin_unlock_irqrestore(&phba->hbalock, flag);
13294         }
13295         return retval;
13296 }
13297
13298 /**
13299  * lpfc_sli_mbox_sys_shutdown - shutdown mailbox command sub-system
13300  * @phba: Pointer to HBA context.
13301  * @mbx_action: Mailbox shutdown options.
13302  *
13303  * This function is called to shutdown the driver's mailbox sub-system.
13304  * It first marks the mailbox sub-system is in a block state to prevent
13305  * the asynchronous mailbox command from issued off the pending mailbox
13306  * command queue. If the mailbox command sub-system shutdown is due to
13307  * HBA error conditions such as EEH or ERATT, this routine shall invoke
13308  * the mailbox sub-system flush routine to forcefully bring down the
13309  * mailbox sub-system. Otherwise, if it is due to normal condition (such
13310  * as with offline or HBA function reset), this routine will wait for the
13311  * outstanding mailbox command to complete before invoking the mailbox
13312  * sub-system flush routine to gracefully bring down mailbox sub-system.
13313  **/
13314 void
13315 lpfc_sli_mbox_sys_shutdown(struct lpfc_hba *phba, int mbx_action)
13316 {
13317         struct lpfc_sli *psli = &phba->sli;
13318         unsigned long timeout;
13319
13320         if (mbx_action == LPFC_MBX_NO_WAIT) {
13321                 /* delay 100ms for port state */
13322                 msleep(100);
13323                 lpfc_sli_mbox_sys_flush(phba);
13324                 return;
13325         }
13326         timeout = msecs_to_jiffies(LPFC_MBOX_TMO * 1000) + jiffies;
13327
13328         /* Disable softirqs, including timers from obtaining phba->hbalock */
13329         local_bh_disable();
13330
13331         spin_lock_irq(&phba->hbalock);
13332         psli->sli_flag |= LPFC_SLI_ASYNC_MBX_BLK;
13333
13334         if (psli->sli_flag & LPFC_SLI_ACTIVE) {
13335                 /* Determine how long we might wait for the active mailbox
13336                  * command to be gracefully completed by firmware.
13337                  */
13338                 if (phba->sli.mbox_active)
13339                         timeout = msecs_to_jiffies(lpfc_mbox_tmo_val(phba,
13340                                                 phba->sli.mbox_active) *
13341                                                 1000) + jiffies;
13342                 spin_unlock_irq(&phba->hbalock);
13343
13344                 /* Enable softirqs again, done with phba->hbalock */
13345                 local_bh_enable();
13346
13347                 while (phba->sli.mbox_active) {
13348                         /* Check active mailbox complete status every 2ms */
13349                         msleep(2);
13350                         if (time_after(jiffies, timeout))
13351                                 /* Timeout, let the mailbox flush routine to
13352                                  * forcefully release active mailbox command
13353                                  */
13354                                 break;
13355                 }
13356         } else {
13357                 spin_unlock_irq(&phba->hbalock);
13358
13359                 /* Enable softirqs again, done with phba->hbalock */
13360                 local_bh_enable();
13361         }
13362
13363         lpfc_sli_mbox_sys_flush(phba);
13364 }
13365
13366 /**
13367  * lpfc_sli_eratt_read - read sli-3 error attention events
13368  * @phba: Pointer to HBA context.
13369  *
13370  * This function is called to read the SLI3 device error attention registers
13371  * for possible error attention events. The caller must hold the hostlock
13372  * with spin_lock_irq().
13373  *
13374  * This function returns 1 when there is Error Attention in the Host Attention
13375  * Register and returns 0 otherwise.
13376  **/
13377 static int
13378 lpfc_sli_eratt_read(struct lpfc_hba *phba)
13379 {
13380         uint32_t ha_copy;
13381
13382         /* Read chip Host Attention (HA) register */
13383         if (lpfc_readl(phba->HAregaddr, &ha_copy))
13384                 goto unplug_err;
13385
13386         if (ha_copy & HA_ERATT) {
13387                 /* Read host status register to retrieve error event */
13388                 if (lpfc_sli_read_hs(phba))
13389                         goto unplug_err;
13390
13391                 /* Check if there is a deferred error condition is active */
13392                 if ((HS_FFER1 & phba->work_hs) &&
13393                     ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13394                       HS_FFER6 | HS_FFER7 | HS_FFER8) & phba->work_hs)) {
13395                         set_bit(DEFER_ERATT, &phba->hba_flag);
13396                         /* Clear all interrupt enable conditions */
13397                         writel(0, phba->HCregaddr);
13398                         readl(phba->HCregaddr);
13399                 }
13400
13401                 /* Set the driver HA work bitmap */
13402                 phba->work_ha |= HA_ERATT;
13403                 /* Indicate polling handles this ERATT */
13404                 set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13405                 return 1;
13406         }
13407         return 0;
13408
13409 unplug_err:
13410         /* Set the driver HS work bitmap */
13411         phba->work_hs |= UNPLUG_ERR;
13412         /* Set the driver HA work bitmap */
13413         phba->work_ha |= HA_ERATT;
13414         /* Indicate polling handles this ERATT */
13415         set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13416         return 1;
13417 }
13418
13419 /**
13420  * lpfc_sli4_eratt_read - read sli-4 error attention events
13421  * @phba: Pointer to HBA context.
13422  *
13423  * This function is called to read the SLI4 device error attention registers
13424  * for possible error attention events. The caller must hold the hostlock
13425  * with spin_lock_irq().
13426  *
13427  * This function returns 1 when there is Error Attention in the Host Attention
13428  * Register and returns 0 otherwise.
13429  **/
13430 static int
13431 lpfc_sli4_eratt_read(struct lpfc_hba *phba)
13432 {
13433         uint32_t uerr_sta_hi, uerr_sta_lo;
13434         uint32_t if_type, portsmphr;
13435         struct lpfc_register portstat_reg;
13436         u32 logmask;
13437
13438         /*
13439          * For now, use the SLI4 device internal unrecoverable error
13440          * registers for error attention. This can be changed later.
13441          */
13442         if_type = bf_get(lpfc_sli_intf_if_type, &phba->sli4_hba.sli_intf);
13443         switch (if_type) {
13444         case LPFC_SLI_INTF_IF_TYPE_0:
13445                 if (lpfc_readl(phba->sli4_hba.u.if_type0.UERRLOregaddr,
13446                         &uerr_sta_lo) ||
13447                         lpfc_readl(phba->sli4_hba.u.if_type0.UERRHIregaddr,
13448                         &uerr_sta_hi)) {
13449                         phba->work_hs |= UNPLUG_ERR;
13450                         phba->work_ha |= HA_ERATT;
13451                         set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13452                         return 1;
13453                 }
13454                 if ((~phba->sli4_hba.ue_mask_lo & uerr_sta_lo) ||
13455                     (~phba->sli4_hba.ue_mask_hi & uerr_sta_hi)) {
13456                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13457                                         "1423 HBA Unrecoverable error: "
13458                                         "uerr_lo_reg=0x%x, uerr_hi_reg=0x%x, "
13459                                         "ue_mask_lo_reg=0x%x, "
13460                                         "ue_mask_hi_reg=0x%x\n",
13461                                         uerr_sta_lo, uerr_sta_hi,
13462                                         phba->sli4_hba.ue_mask_lo,
13463                                         phba->sli4_hba.ue_mask_hi);
13464                         phba->work_status[0] = uerr_sta_lo;
13465                         phba->work_status[1] = uerr_sta_hi;
13466                         phba->work_ha |= HA_ERATT;
13467                         set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13468                         return 1;
13469                 }
13470                 break;
13471         case LPFC_SLI_INTF_IF_TYPE_2:
13472         case LPFC_SLI_INTF_IF_TYPE_6:
13473                 if (lpfc_readl(phba->sli4_hba.u.if_type2.STATUSregaddr,
13474                         &portstat_reg.word0) ||
13475                         lpfc_readl(phba->sli4_hba.PSMPHRregaddr,
13476                         &portsmphr)){
13477                         phba->work_hs |= UNPLUG_ERR;
13478                         phba->work_ha |= HA_ERATT;
13479                         set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13480                         return 1;
13481                 }
13482                 if (bf_get(lpfc_sliport_status_err, &portstat_reg)) {
13483                         phba->work_status[0] =
13484                                 readl(phba->sli4_hba.u.if_type2.ERR1regaddr);
13485                         phba->work_status[1] =
13486                                 readl(phba->sli4_hba.u.if_type2.ERR2regaddr);
13487                         logmask = LOG_TRACE_EVENT;
13488                         if (phba->work_status[0] ==
13489                                 SLIPORT_ERR1_REG_ERR_CODE_2 &&
13490                             phba->work_status[1] == SLIPORT_ERR2_REG_FW_RESTART)
13491                                 logmask = LOG_SLI;
13492                         lpfc_printf_log(phba, KERN_ERR, logmask,
13493                                         "2885 Port Status Event: "
13494                                         "port status reg 0x%x, "
13495                                         "port smphr reg 0x%x, "
13496                                         "error 1=0x%x, error 2=0x%x\n",
13497                                         portstat_reg.word0,
13498                                         portsmphr,
13499                                         phba->work_status[0],
13500                                         phba->work_status[1]);
13501                         phba->work_ha |= HA_ERATT;
13502                         set_bit(HBA_ERATT_HANDLED, &phba->hba_flag);
13503                         return 1;
13504                 }
13505                 break;
13506         case LPFC_SLI_INTF_IF_TYPE_1:
13507         default:
13508                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13509                                 "2886 HBA Error Attention on unsupported "
13510                                 "if type %d.", if_type);
13511                 return 1;
13512         }
13513
13514         return 0;
13515 }
13516
13517 /**
13518  * lpfc_sli_check_eratt - check error attention events
13519  * @phba: Pointer to HBA context.
13520  *
13521  * This function is called from timer soft interrupt context to check HBA's
13522  * error attention register bit for error attention events.
13523  *
13524  * This function returns 1 when there is Error Attention in the Host Attention
13525  * Register and returns 0 otherwise.
13526  **/
13527 int
13528 lpfc_sli_check_eratt(struct lpfc_hba *phba)
13529 {
13530         uint32_t ha_copy;
13531
13532         /* If somebody is waiting to handle an eratt, don't process it
13533          * here. The brdkill function will do this.
13534          */
13535         if (phba->link_flag & LS_IGNORE_ERATT)
13536                 return 0;
13537
13538         /* Check if interrupt handler handles this ERATT */
13539         if (test_bit(HBA_ERATT_HANDLED, &phba->hba_flag))
13540                 /* Interrupt handler has handled ERATT */
13541                 return 0;
13542
13543         /*
13544          * If there is deferred error attention, do not check for error
13545          * attention
13546          */
13547         if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag)))
13548                 return 0;
13549
13550         spin_lock_irq(&phba->hbalock);
13551         /* If PCI channel is offline, don't process it */
13552         if (unlikely(pci_channel_offline(phba->pcidev))) {
13553                 spin_unlock_irq(&phba->hbalock);
13554                 return 0;
13555         }
13556
13557         switch (phba->sli_rev) {
13558         case LPFC_SLI_REV2:
13559         case LPFC_SLI_REV3:
13560                 /* Read chip Host Attention (HA) register */
13561                 ha_copy = lpfc_sli_eratt_read(phba);
13562                 break;
13563         case LPFC_SLI_REV4:
13564                 /* Read device Uncoverable Error (UERR) registers */
13565                 ha_copy = lpfc_sli4_eratt_read(phba);
13566                 break;
13567         default:
13568                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13569                                 "0299 Invalid SLI revision (%d)\n",
13570                                 phba->sli_rev);
13571                 ha_copy = 0;
13572                 break;
13573         }
13574         spin_unlock_irq(&phba->hbalock);
13575
13576         return ha_copy;
13577 }
13578
13579 /**
13580  * lpfc_intr_state_check - Check device state for interrupt handling
13581  * @phba: Pointer to HBA context.
13582  *
13583  * This inline routine checks whether a device or its PCI slot is in a state
13584  * that the interrupt should be handled.
13585  *
13586  * This function returns 0 if the device or the PCI slot is in a state that
13587  * interrupt should be handled, otherwise -EIO.
13588  */
13589 static inline int
13590 lpfc_intr_state_check(struct lpfc_hba *phba)
13591 {
13592         /* If the pci channel is offline, ignore all the interrupts */
13593         if (unlikely(pci_channel_offline(phba->pcidev)))
13594                 return -EIO;
13595
13596         /* Update device level interrupt statistics */
13597         phba->sli.slistat.sli_intr++;
13598
13599         /* Ignore all interrupts during initialization. */
13600         if (unlikely(phba->link_state < LPFC_LINK_DOWN))
13601                 return -EIO;
13602
13603         return 0;
13604 }
13605
13606 /**
13607  * lpfc_sli_sp_intr_handler - Slow-path interrupt handler to SLI-3 device
13608  * @irq: Interrupt number.
13609  * @dev_id: The device context pointer.
13610  *
13611  * This function is directly called from the PCI layer as an interrupt
13612  * service routine when device with SLI-3 interface spec is enabled with
13613  * MSI-X multi-message interrupt mode and there are slow-path events in
13614  * the HBA. However, when the device is enabled with either MSI or Pin-IRQ
13615  * interrupt mode, this function is called as part of the device-level
13616  * interrupt handler. When the PCI slot is in error recovery or the HBA
13617  * is undergoing initialization, the interrupt handler will not process
13618  * the interrupt. The link attention and ELS ring attention events are
13619  * handled by the worker thread. The interrupt handler signals the worker
13620  * thread and returns for these events. This function is called without
13621  * any lock held. It gets the hbalock to access and update SLI data
13622  * structures.
13623  *
13624  * This function returns IRQ_HANDLED when interrupt is handled else it
13625  * returns IRQ_NONE.
13626  **/
13627 irqreturn_t
13628 lpfc_sli_sp_intr_handler(int irq, void *dev_id)
13629 {
13630         struct lpfc_hba  *phba;
13631         uint32_t ha_copy, hc_copy;
13632         uint32_t work_ha_copy;
13633         unsigned long status;
13634         unsigned long iflag;
13635         uint32_t control;
13636
13637         MAILBOX_t *mbox, *pmbox;
13638         struct lpfc_vport *vport;
13639         struct lpfc_nodelist *ndlp;
13640         struct lpfc_dmabuf *mp;
13641         LPFC_MBOXQ_t *pmb;
13642         int rc;
13643
13644         /*
13645          * Get the driver's phba structure from the dev_id and
13646          * assume the HBA is not interrupting.
13647          */
13648         phba = (struct lpfc_hba *)dev_id;
13649
13650         if (unlikely(!phba))
13651                 return IRQ_NONE;
13652
13653         /*
13654          * Stuff needs to be attented to when this function is invoked as an
13655          * individual interrupt handler in MSI-X multi-message interrupt mode
13656          */
13657         if (phba->intr_type == MSIX) {
13658                 /* Check device state for handling interrupt */
13659                 if (lpfc_intr_state_check(phba))
13660                         return IRQ_NONE;
13661                 /* Need to read HA REG for slow-path events */
13662                 spin_lock_irqsave(&phba->hbalock, iflag);
13663                 if (lpfc_readl(phba->HAregaddr, &ha_copy))
13664                         goto unplug_error;
13665                 /* If somebody is waiting to handle an eratt don't process it
13666                  * here. The brdkill function will do this.
13667                  */
13668                 if (phba->link_flag & LS_IGNORE_ERATT)
13669                         ha_copy &= ~HA_ERATT;
13670                 /* Check the need for handling ERATT in interrupt handler */
13671                 if (ha_copy & HA_ERATT) {
13672                         if (test_and_set_bit(HBA_ERATT_HANDLED,
13673                                              &phba->hba_flag))
13674                                 /* ERATT polling has handled ERATT */
13675                                 ha_copy &= ~HA_ERATT;
13676                 }
13677
13678                 /*
13679                  * If there is deferred error attention, do not check for any
13680                  * interrupt.
13681                  */
13682                 if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag))) {
13683                         spin_unlock_irqrestore(&phba->hbalock, iflag);
13684                         return IRQ_NONE;
13685                 }
13686
13687                 /* Clear up only attention source related to slow-path */
13688                 if (lpfc_readl(phba->HCregaddr, &hc_copy))
13689                         goto unplug_error;
13690
13691                 writel(hc_copy & ~(HC_MBINT_ENA | HC_R2INT_ENA |
13692                         HC_LAINT_ENA | HC_ERINT_ENA),
13693                         phba->HCregaddr);
13694                 writel((ha_copy & (HA_MBATT | HA_R2_CLR_MSK)),
13695                         phba->HAregaddr);
13696                 writel(hc_copy, phba->HCregaddr);
13697                 readl(phba->HAregaddr); /* flush */
13698                 spin_unlock_irqrestore(&phba->hbalock, iflag);
13699         } else
13700                 ha_copy = phba->ha_copy;
13701
13702         work_ha_copy = ha_copy & phba->work_ha_mask;
13703
13704         if (work_ha_copy) {
13705                 if (work_ha_copy & HA_LATT) {
13706                         if (phba->sli.sli_flag & LPFC_PROCESS_LA) {
13707                                 /*
13708                                  * Turn off Link Attention interrupts
13709                                  * until CLEAR_LA done
13710                                  */
13711                                 spin_lock_irqsave(&phba->hbalock, iflag);
13712                                 phba->sli.sli_flag &= ~LPFC_PROCESS_LA;
13713                                 if (lpfc_readl(phba->HCregaddr, &control))
13714                                         goto unplug_error;
13715                                 control &= ~HC_LAINT_ENA;
13716                                 writel(control, phba->HCregaddr);
13717                                 readl(phba->HCregaddr); /* flush */
13718                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
13719                         }
13720                         else
13721                                 work_ha_copy &= ~HA_LATT;
13722                 }
13723
13724                 if (work_ha_copy & ~(HA_ERATT | HA_MBATT | HA_LATT)) {
13725                         /*
13726                          * Turn off Slow Rings interrupts, LPFC_ELS_RING is
13727                          * the only slow ring.
13728                          */
13729                         status = (work_ha_copy &
13730                                 (HA_RXMASK  << (4*LPFC_ELS_RING)));
13731                         status >>= (4*LPFC_ELS_RING);
13732                         if (status & HA_RXMASK) {
13733                                 spin_lock_irqsave(&phba->hbalock, iflag);
13734                                 if (lpfc_readl(phba->HCregaddr, &control))
13735                                         goto unplug_error;
13736
13737                                 lpfc_debugfs_slow_ring_trc(phba,
13738                                 "ISR slow ring:   ctl:x%x stat:x%x isrcnt:x%x",
13739                                 control, status,
13740                                 (uint32_t)phba->sli.slistat.sli_intr);
13741
13742                                 if (control & (HC_R0INT_ENA << LPFC_ELS_RING)) {
13743                                         lpfc_debugfs_slow_ring_trc(phba,
13744                                                 "ISR Disable ring:"
13745                                                 "pwork:x%x hawork:x%x wait:x%x",
13746                                                 phba->work_ha, work_ha_copy,
13747                                                 (uint32_t)((unsigned long)
13748                                                 &phba->work_waitq));
13749
13750                                         control &=
13751                                             ~(HC_R0INT_ENA << LPFC_ELS_RING);
13752                                         writel(control, phba->HCregaddr);
13753                                         readl(phba->HCregaddr); /* flush */
13754                                 }
13755                                 else {
13756                                         lpfc_debugfs_slow_ring_trc(phba,
13757                                                 "ISR slow ring:   pwork:"
13758                                                 "x%x hawork:x%x wait:x%x",
13759                                                 phba->work_ha, work_ha_copy,
13760                                                 (uint32_t)((unsigned long)
13761                                                 &phba->work_waitq));
13762                                 }
13763                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
13764                         }
13765                 }
13766                 spin_lock_irqsave(&phba->hbalock, iflag);
13767                 if (work_ha_copy & HA_ERATT) {
13768                         if (lpfc_sli_read_hs(phba))
13769                                 goto unplug_error;
13770                         /*
13771                          * Check if there is a deferred error condition
13772                          * is active
13773                          */
13774                         if ((HS_FFER1 & phba->work_hs) &&
13775                                 ((HS_FFER2 | HS_FFER3 | HS_FFER4 | HS_FFER5 |
13776                                   HS_FFER6 | HS_FFER7 | HS_FFER8) &
13777                                   phba->work_hs)) {
13778                                 set_bit(DEFER_ERATT, &phba->hba_flag);
13779                                 /* Clear all interrupt enable conditions */
13780                                 writel(0, phba->HCregaddr);
13781                                 readl(phba->HCregaddr);
13782                         }
13783                 }
13784
13785                 if ((work_ha_copy & HA_MBATT) && (phba->sli.mbox_active)) {
13786                         pmb = phba->sli.mbox_active;
13787                         pmbox = &pmb->u.mb;
13788                         mbox = phba->mbox;
13789                         vport = pmb->vport;
13790
13791                         /* First check out the status word */
13792                         lpfc_sli_pcimem_bcopy(mbox, pmbox, sizeof(uint32_t));
13793                         if (pmbox->mbxOwner != OWN_HOST) {
13794                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
13795                                 /*
13796                                  * Stray Mailbox Interrupt, mbxCommand <cmd>
13797                                  * mbxStatus <status>
13798                                  */
13799                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
13800                                                 "(%d):0304 Stray Mailbox "
13801                                                 "Interrupt mbxCommand x%x "
13802                                                 "mbxStatus x%x\n",
13803                                                 (vport ? vport->vpi : 0),
13804                                                 pmbox->mbxCommand,
13805                                                 pmbox->mbxStatus);
13806                                 /* clear mailbox attention bit */
13807                                 work_ha_copy &= ~HA_MBATT;
13808                         } else {
13809                                 phba->sli.mbox_active = NULL;
13810                                 spin_unlock_irqrestore(&phba->hbalock, iflag);
13811                                 phba->last_completion_time = jiffies;
13812                                 del_timer(&phba->sli.mbox_tmo);
13813                                 if (pmb->mbox_cmpl) {
13814                                         lpfc_sli_pcimem_bcopy(mbox, pmbox,
13815                                                         MAILBOX_CMD_SIZE);
13816                                         if (pmb->out_ext_byte_len &&
13817                                                 pmb->ext_buf)
13818                                                 lpfc_sli_pcimem_bcopy(
13819                                                 phba->mbox_ext,
13820                                                 pmb->ext_buf,
13821                                                 pmb->out_ext_byte_len);
13822                                 }
13823                                 if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
13824                                         pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
13825
13826                                         lpfc_debugfs_disc_trc(vport,
13827                                                 LPFC_DISC_TRC_MBOX_VPORT,
13828                                                 "MBOX dflt rpi: : "
13829                                                 "status:x%x rpi:x%x",
13830                                                 (uint32_t)pmbox->mbxStatus,
13831                                                 pmbox->un.varWords[0], 0);
13832
13833                                         if (!pmbox->mbxStatus) {
13834                                                 mp = pmb->ctx_buf;
13835                                                 ndlp = pmb->ctx_ndlp;
13836
13837                                                 /* Reg_LOGIN of dflt RPI was
13838                                                  * successful. new lets get
13839                                                  * rid of the RPI using the
13840                                                  * same mbox buffer.
13841                                                  */
13842                                                 lpfc_unreg_login(phba,
13843                                                         vport->vpi,
13844                                                         pmbox->un.varWords[0],
13845                                                         pmb);
13846                                                 pmb->mbox_cmpl =
13847                                                         lpfc_mbx_cmpl_dflt_rpi;
13848                                                 pmb->ctx_buf = mp;
13849                                                 pmb->ctx_ndlp = ndlp;
13850                                                 pmb->vport = vport;
13851                                                 rc = lpfc_sli_issue_mbox(phba,
13852                                                                 pmb,
13853                                                                 MBX_NOWAIT);
13854                                                 if (rc != MBX_BUSY)
13855                                                         lpfc_printf_log(phba,
13856                                                         KERN_ERR,
13857                                                         LOG_TRACE_EVENT,
13858                                                         "0350 rc should have"
13859                                                         "been MBX_BUSY\n");
13860                                                 if (rc != MBX_NOT_FINISHED)
13861                                                         goto send_current_mbox;
13862                                         }
13863                                 }
13864                                 spin_lock_irqsave(
13865                                                 &phba->pport->work_port_lock,
13866                                                 iflag);
13867                                 phba->pport->work_port_events &=
13868                                         ~WORKER_MBOX_TMO;
13869                                 spin_unlock_irqrestore(
13870                                                 &phba->pport->work_port_lock,
13871                                                 iflag);
13872
13873                                 /* Do NOT queue MBX_HEARTBEAT to the worker
13874                                  * thread for processing.
13875                                  */
13876                                 if (pmbox->mbxCommand == MBX_HEARTBEAT) {
13877                                         /* Process mbox now */
13878                                         phba->sli.mbox_active = NULL;
13879                                         phba->sli.sli_flag &=
13880                                                 ~LPFC_SLI_MBOX_ACTIVE;
13881                                         if (pmb->mbox_cmpl)
13882                                                 pmb->mbox_cmpl(phba, pmb);
13883                                 } else {
13884                                         /* Queue to worker thread to process */
13885                                         lpfc_mbox_cmpl_put(phba, pmb);
13886                                 }
13887                         }
13888                 } else
13889                         spin_unlock_irqrestore(&phba->hbalock, iflag);
13890
13891                 if ((work_ha_copy & HA_MBATT) &&
13892                     (phba->sli.mbox_active == NULL)) {
13893 send_current_mbox:
13894                         /* Process next mailbox command if there is one */
13895                         do {
13896                                 rc = lpfc_sli_issue_mbox(phba, NULL,
13897                                                          MBX_NOWAIT);
13898                         } while (rc == MBX_NOT_FINISHED);
13899                         if (rc != MBX_SUCCESS)
13900                                 lpfc_printf_log(phba, KERN_ERR,
13901                                                 LOG_TRACE_EVENT,
13902                                                 "0349 rc should be "
13903                                                 "MBX_SUCCESS\n");
13904                 }
13905
13906                 spin_lock_irqsave(&phba->hbalock, iflag);
13907                 phba->work_ha |= work_ha_copy;
13908                 spin_unlock_irqrestore(&phba->hbalock, iflag);
13909                 lpfc_worker_wake_up(phba);
13910         }
13911         return IRQ_HANDLED;
13912 unplug_error:
13913         spin_unlock_irqrestore(&phba->hbalock, iflag);
13914         return IRQ_HANDLED;
13915
13916 } /* lpfc_sli_sp_intr_handler */
13917
13918 /**
13919  * lpfc_sli_fp_intr_handler - Fast-path interrupt handler to SLI-3 device.
13920  * @irq: Interrupt number.
13921  * @dev_id: The device context pointer.
13922  *
13923  * This function is directly called from the PCI layer as an interrupt
13924  * service routine when device with SLI-3 interface spec is enabled with
13925  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
13926  * ring event in the HBA. However, when the device is enabled with either
13927  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
13928  * device-level interrupt handler. When the PCI slot is in error recovery
13929  * or the HBA is undergoing initialization, the interrupt handler will not
13930  * process the interrupt. The SCSI FCP fast-path ring event are handled in
13931  * the intrrupt context. This function is called without any lock held.
13932  * It gets the hbalock to access and update SLI data structures.
13933  *
13934  * This function returns IRQ_HANDLED when interrupt is handled else it
13935  * returns IRQ_NONE.
13936  **/
13937 irqreturn_t
13938 lpfc_sli_fp_intr_handler(int irq, void *dev_id)
13939 {
13940         struct lpfc_hba  *phba;
13941         uint32_t ha_copy;
13942         unsigned long status;
13943         unsigned long iflag;
13944         struct lpfc_sli_ring *pring;
13945
13946         /* Get the driver's phba structure from the dev_id and
13947          * assume the HBA is not interrupting.
13948          */
13949         phba = (struct lpfc_hba *) dev_id;
13950
13951         if (unlikely(!phba))
13952                 return IRQ_NONE;
13953
13954         /*
13955          * Stuff needs to be attented to when this function is invoked as an
13956          * individual interrupt handler in MSI-X multi-message interrupt mode
13957          */
13958         if (phba->intr_type == MSIX) {
13959                 /* Check device state for handling interrupt */
13960                 if (lpfc_intr_state_check(phba))
13961                         return IRQ_NONE;
13962                 /* Need to read HA REG for FCP ring and other ring events */
13963                 if (lpfc_readl(phba->HAregaddr, &ha_copy))
13964                         return IRQ_HANDLED;
13965
13966                 /*
13967                  * If there is deferred error attention, do not check for
13968                  * any interrupt.
13969                  */
13970                 if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag)))
13971                         return IRQ_NONE;
13972
13973                 /* Clear up only attention source related to fast-path */
13974                 spin_lock_irqsave(&phba->hbalock, iflag);
13975                 writel((ha_copy & (HA_R0_CLR_MSK | HA_R1_CLR_MSK)),
13976                         phba->HAregaddr);
13977                 readl(phba->HAregaddr); /* flush */
13978                 spin_unlock_irqrestore(&phba->hbalock, iflag);
13979         } else
13980                 ha_copy = phba->ha_copy;
13981
13982         /*
13983          * Process all events on FCP ring. Take the optimized path for FCP IO.
13984          */
13985         ha_copy &= ~(phba->work_ha_mask);
13986
13987         status = (ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
13988         status >>= (4*LPFC_FCP_RING);
13989         pring = &phba->sli.sli3_ring[LPFC_FCP_RING];
13990         if (status & HA_RXMASK)
13991                 lpfc_sli_handle_fast_ring_event(phba, pring, status);
13992
13993         if (phba->cfg_multi_ring_support == 2) {
13994                 /*
13995                  * Process all events on extra ring. Take the optimized path
13996                  * for extra ring IO.
13997                  */
13998                 status = (ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
13999                 status >>= (4*LPFC_EXTRA_RING);
14000                 if (status & HA_RXMASK) {
14001                         lpfc_sli_handle_fast_ring_event(phba,
14002                                         &phba->sli.sli3_ring[LPFC_EXTRA_RING],
14003                                         status);
14004                 }
14005         }
14006         return IRQ_HANDLED;
14007 }  /* lpfc_sli_fp_intr_handler */
14008
14009 /**
14010  * lpfc_sli_intr_handler - Device-level interrupt handler to SLI-3 device
14011  * @irq: Interrupt number.
14012  * @dev_id: The device context pointer.
14013  *
14014  * This function is the HBA device-level interrupt handler to device with
14015  * SLI-3 interface spec, called from the PCI layer when either MSI or
14016  * Pin-IRQ interrupt mode is enabled and there is an event in the HBA which
14017  * requires driver attention. This function invokes the slow-path interrupt
14018  * attention handling function and fast-path interrupt attention handling
14019  * function in turn to process the relevant HBA attention events. This
14020  * function is called without any lock held. It gets the hbalock to access
14021  * and update SLI data structures.
14022  *
14023  * This function returns IRQ_HANDLED when interrupt is handled, else it
14024  * returns IRQ_NONE.
14025  **/
14026 irqreturn_t
14027 lpfc_sli_intr_handler(int irq, void *dev_id)
14028 {
14029         struct lpfc_hba  *phba;
14030         irqreturn_t sp_irq_rc, fp_irq_rc;
14031         unsigned long status1, status2;
14032         uint32_t hc_copy;
14033
14034         /*
14035          * Get the driver's phba structure from the dev_id and
14036          * assume the HBA is not interrupting.
14037          */
14038         phba = (struct lpfc_hba *) dev_id;
14039
14040         if (unlikely(!phba))
14041                 return IRQ_NONE;
14042
14043         /* Check device state for handling interrupt */
14044         if (lpfc_intr_state_check(phba))
14045                 return IRQ_NONE;
14046
14047         spin_lock(&phba->hbalock);
14048         if (lpfc_readl(phba->HAregaddr, &phba->ha_copy)) {
14049                 spin_unlock(&phba->hbalock);
14050                 return IRQ_HANDLED;
14051         }
14052
14053         if (unlikely(!phba->ha_copy)) {
14054                 spin_unlock(&phba->hbalock);
14055                 return IRQ_NONE;
14056         } else if (phba->ha_copy & HA_ERATT) {
14057                 if (test_and_set_bit(HBA_ERATT_HANDLED, &phba->hba_flag))
14058                         /* ERATT polling has handled ERATT */
14059                         phba->ha_copy &= ~HA_ERATT;
14060         }
14061
14062         /*
14063          * If there is deferred error attention, do not check for any interrupt.
14064          */
14065         if (unlikely(test_bit(DEFER_ERATT, &phba->hba_flag))) {
14066                 spin_unlock(&phba->hbalock);
14067                 return IRQ_NONE;
14068         }
14069
14070         /* Clear attention sources except link and error attentions */
14071         if (lpfc_readl(phba->HCregaddr, &hc_copy)) {
14072                 spin_unlock(&phba->hbalock);
14073                 return IRQ_HANDLED;
14074         }
14075         writel(hc_copy & ~(HC_MBINT_ENA | HC_R0INT_ENA | HC_R1INT_ENA
14076                 | HC_R2INT_ENA | HC_LAINT_ENA | HC_ERINT_ENA),
14077                 phba->HCregaddr);
14078         writel((phba->ha_copy & ~(HA_LATT | HA_ERATT)), phba->HAregaddr);
14079         writel(hc_copy, phba->HCregaddr);
14080         readl(phba->HAregaddr); /* flush */
14081         spin_unlock(&phba->hbalock);
14082
14083         /*
14084          * Invokes slow-path host attention interrupt handling as appropriate.
14085          */
14086
14087         /* status of events with mailbox and link attention */
14088         status1 = phba->ha_copy & (HA_MBATT | HA_LATT | HA_ERATT);
14089
14090         /* status of events with ELS ring */
14091         status2 = (phba->ha_copy & (HA_RXMASK  << (4*LPFC_ELS_RING)));
14092         status2 >>= (4*LPFC_ELS_RING);
14093
14094         if (status1 || (status2 & HA_RXMASK))
14095                 sp_irq_rc = lpfc_sli_sp_intr_handler(irq, dev_id);
14096         else
14097                 sp_irq_rc = IRQ_NONE;
14098
14099         /*
14100          * Invoke fast-path host attention interrupt handling as appropriate.
14101          */
14102
14103         /* status of events with FCP ring */
14104         status1 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_FCP_RING)));
14105         status1 >>= (4*LPFC_FCP_RING);
14106
14107         /* status of events with extra ring */
14108         if (phba->cfg_multi_ring_support == 2) {
14109                 status2 = (phba->ha_copy & (HA_RXMASK << (4*LPFC_EXTRA_RING)));
14110                 status2 >>= (4*LPFC_EXTRA_RING);
14111         } else
14112                 status2 = 0;
14113
14114         if ((status1 & HA_RXMASK) || (status2 & HA_RXMASK))
14115                 fp_irq_rc = lpfc_sli_fp_intr_handler(irq, dev_id);
14116         else
14117                 fp_irq_rc = IRQ_NONE;
14118
14119         /* Return device-level interrupt handling status */
14120         return (sp_irq_rc == IRQ_HANDLED) ? sp_irq_rc : fp_irq_rc;
14121 }  /* lpfc_sli_intr_handler */
14122
14123 /**
14124  * lpfc_sli4_els_xri_abort_event_proc - Process els xri abort event
14125  * @phba: pointer to lpfc hba data structure.
14126  *
14127  * This routine is invoked by the worker thread to process all the pending
14128  * SLI4 els abort xri events.
14129  **/
14130 void lpfc_sli4_els_xri_abort_event_proc(struct lpfc_hba *phba)
14131 {
14132         struct lpfc_cq_event *cq_event;
14133         unsigned long iflags;
14134
14135         /* First, declare the els xri abort event has been handled */
14136         clear_bit(ELS_XRI_ABORT_EVENT, &phba->hba_flag);
14137
14138         /* Now, handle all the els xri abort events */
14139         spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14140         while (!list_empty(&phba->sli4_hba.sp_els_xri_aborted_work_queue)) {
14141                 /* Get the first event from the head of the event queue */
14142                 list_remove_head(&phba->sli4_hba.sp_els_xri_aborted_work_queue,
14143                                  cq_event, struct lpfc_cq_event, list);
14144                 spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14145                                        iflags);
14146                 /* Notify aborted XRI for ELS work queue */
14147                 lpfc_sli4_els_xri_aborted(phba, &cq_event->cqe.wcqe_axri);
14148
14149                 /* Free the event processed back to the free pool */
14150                 lpfc_sli4_cq_event_release(phba, cq_event);
14151                 spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14152                                   iflags);
14153         }
14154         spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock, iflags);
14155 }
14156
14157 /**
14158  * lpfc_sli4_els_preprocess_rspiocbq - Get response iocbq from els wcqe
14159  * @phba: Pointer to HBA context object.
14160  * @irspiocbq: Pointer to work-queue completion queue entry.
14161  *
14162  * This routine handles an ELS work-queue completion event and construct
14163  * a pseudo response ELS IOCBQ from the SLI4 ELS WCQE for the common
14164  * discovery engine to handle.
14165  *
14166  * Return: Pointer to the receive IOCBQ, NULL otherwise.
14167  **/
14168 static struct lpfc_iocbq *
14169 lpfc_sli4_els_preprocess_rspiocbq(struct lpfc_hba *phba,
14170                                   struct lpfc_iocbq *irspiocbq)
14171 {
14172         struct lpfc_sli_ring *pring;
14173         struct lpfc_iocbq *cmdiocbq;
14174         struct lpfc_wcqe_complete *wcqe;
14175         unsigned long iflags;
14176
14177         pring = lpfc_phba_elsring(phba);
14178         if (unlikely(!pring))
14179                 return NULL;
14180
14181         wcqe = &irspiocbq->cq_event.cqe.wcqe_cmpl;
14182         spin_lock_irqsave(&pring->ring_lock, iflags);
14183         pring->stats.iocb_event++;
14184         /* Look up the ELS command IOCB and create pseudo response IOCB */
14185         cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
14186                                 bf_get(lpfc_wcqe_c_request_tag, wcqe));
14187         if (unlikely(!cmdiocbq)) {
14188                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
14189                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14190                                 "0386 ELS complete with no corresponding "
14191                                 "cmdiocb: 0x%x 0x%x 0x%x 0x%x\n",
14192                                 wcqe->word0, wcqe->total_data_placed,
14193                                 wcqe->parameter, wcqe->word3);
14194                 lpfc_sli_release_iocbq(phba, irspiocbq);
14195                 return NULL;
14196         }
14197
14198         memcpy(&irspiocbq->wqe, &cmdiocbq->wqe, sizeof(union lpfc_wqe128));
14199         memcpy(&irspiocbq->wcqe_cmpl, wcqe, sizeof(*wcqe));
14200
14201         /* Put the iocb back on the txcmplq */
14202         lpfc_sli_ringtxcmpl_put(phba, pring, cmdiocbq);
14203         spin_unlock_irqrestore(&pring->ring_lock, iflags);
14204
14205         if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
14206                 spin_lock_irqsave(&phba->hbalock, iflags);
14207                 irspiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
14208                 spin_unlock_irqrestore(&phba->hbalock, iflags);
14209         }
14210
14211         return irspiocbq;
14212 }
14213
14214 inline struct lpfc_cq_event *
14215 lpfc_cq_event_setup(struct lpfc_hba *phba, void *entry, int size)
14216 {
14217         struct lpfc_cq_event *cq_event;
14218
14219         /* Allocate a new internal CQ_EVENT entry */
14220         cq_event = lpfc_sli4_cq_event_alloc(phba);
14221         if (!cq_event) {
14222                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14223                                 "0602 Failed to alloc CQ_EVENT entry\n");
14224                 return NULL;
14225         }
14226
14227         /* Move the CQE into the event */
14228         memcpy(&cq_event->cqe, entry, size);
14229         return cq_event;
14230 }
14231
14232 /**
14233  * lpfc_sli4_sp_handle_async_event - Handle an asynchronous event
14234  * @phba: Pointer to HBA context object.
14235  * @mcqe: Pointer to mailbox completion queue entry.
14236  *
14237  * This routine process a mailbox completion queue entry with asynchronous
14238  * event.
14239  *
14240  * Return: true if work posted to worker thread, otherwise false.
14241  **/
14242 static bool
14243 lpfc_sli4_sp_handle_async_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14244 {
14245         struct lpfc_cq_event *cq_event;
14246         unsigned long iflags;
14247
14248         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14249                         "0392 Async Event: word0:x%x, word1:x%x, "
14250                         "word2:x%x, word3:x%x\n", mcqe->word0,
14251                         mcqe->mcqe_tag0, mcqe->mcqe_tag1, mcqe->trailer);
14252
14253         cq_event = lpfc_cq_event_setup(phba, mcqe, sizeof(struct lpfc_mcqe));
14254         if (!cq_event)
14255                 return false;
14256
14257         spin_lock_irqsave(&phba->sli4_hba.asynce_list_lock, iflags);
14258         list_add_tail(&cq_event->list, &phba->sli4_hba.sp_asynce_work_queue);
14259         spin_unlock_irqrestore(&phba->sli4_hba.asynce_list_lock, iflags);
14260
14261         /* Set the async event flag */
14262         set_bit(ASYNC_EVENT, &phba->hba_flag);
14263
14264         return true;
14265 }
14266
14267 /**
14268  * lpfc_sli4_sp_handle_mbox_event - Handle a mailbox completion event
14269  * @phba: Pointer to HBA context object.
14270  * @mcqe: Pointer to mailbox completion queue entry.
14271  *
14272  * This routine process a mailbox completion queue entry with mailbox
14273  * completion event.
14274  *
14275  * Return: true if work posted to worker thread, otherwise false.
14276  **/
14277 static bool
14278 lpfc_sli4_sp_handle_mbox_event(struct lpfc_hba *phba, struct lpfc_mcqe *mcqe)
14279 {
14280         uint32_t mcqe_status;
14281         MAILBOX_t *mbox, *pmbox;
14282         struct lpfc_mqe *mqe;
14283         struct lpfc_vport *vport;
14284         struct lpfc_nodelist *ndlp;
14285         struct lpfc_dmabuf *mp;
14286         unsigned long iflags;
14287         LPFC_MBOXQ_t *pmb;
14288         bool workposted = false;
14289         int rc;
14290
14291         /* If not a mailbox complete MCQE, out by checking mailbox consume */
14292         if (!bf_get(lpfc_trailer_completed, mcqe))
14293                 goto out_no_mqe_complete;
14294
14295         /* Get the reference to the active mbox command */
14296         spin_lock_irqsave(&phba->hbalock, iflags);
14297         pmb = phba->sli.mbox_active;
14298         if (unlikely(!pmb)) {
14299                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14300                                 "1832 No pending MBOX command to handle\n");
14301                 spin_unlock_irqrestore(&phba->hbalock, iflags);
14302                 goto out_no_mqe_complete;
14303         }
14304         spin_unlock_irqrestore(&phba->hbalock, iflags);
14305         mqe = &pmb->u.mqe;
14306         pmbox = (MAILBOX_t *)&pmb->u.mqe;
14307         mbox = phba->mbox;
14308         vport = pmb->vport;
14309
14310         /* Reset heartbeat timer */
14311         phba->last_completion_time = jiffies;
14312         del_timer(&phba->sli.mbox_tmo);
14313
14314         /* Move mbox data to caller's mailbox region, do endian swapping */
14315         if (pmb->mbox_cmpl && mbox)
14316                 lpfc_sli4_pcimem_bcopy(mbox, mqe, sizeof(struct lpfc_mqe));
14317
14318         /*
14319          * For mcqe errors, conditionally move a modified error code to
14320          * the mbox so that the error will not be missed.
14321          */
14322         mcqe_status = bf_get(lpfc_mcqe_status, mcqe);
14323         if (mcqe_status != MB_CQE_STATUS_SUCCESS) {
14324                 if (bf_get(lpfc_mqe_status, mqe) == MBX_SUCCESS)
14325                         bf_set(lpfc_mqe_status, mqe,
14326                                (LPFC_MBX_ERROR_RANGE | mcqe_status));
14327         }
14328         if (pmb->mbox_flag & LPFC_MBX_IMED_UNREG) {
14329                 pmb->mbox_flag &= ~LPFC_MBX_IMED_UNREG;
14330                 lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_MBOX_VPORT,
14331                                       "MBOX dflt rpi: status:x%x rpi:x%x",
14332                                       mcqe_status,
14333                                       pmbox->un.varWords[0], 0);
14334                 if (mcqe_status == MB_CQE_STATUS_SUCCESS) {
14335                         mp = pmb->ctx_buf;
14336                         ndlp = pmb->ctx_ndlp;
14337
14338                         /* Reg_LOGIN of dflt RPI was successful. Mark the
14339                          * node as having an UNREG_LOGIN in progress to stop
14340                          * an unsolicited PLOGI from the same NPortId from
14341                          * starting another mailbox transaction.
14342                          */
14343                         set_bit(NLP_UNREG_INP, &ndlp->nlp_flag);
14344                         lpfc_unreg_login(phba, vport->vpi,
14345                                          pmbox->un.varWords[0], pmb);
14346                         pmb->mbox_cmpl = lpfc_mbx_cmpl_dflt_rpi;
14347                         pmb->ctx_buf = mp;
14348
14349                         /* No reference taken here.  This is a default
14350                          * RPI reg/immediate unreg cycle. The reference was
14351                          * taken in the reg rpi path and is released when
14352                          * this mailbox completes.
14353                          */
14354                         pmb->ctx_ndlp = ndlp;
14355                         pmb->vport = vport;
14356                         rc = lpfc_sli_issue_mbox(phba, pmb, MBX_NOWAIT);
14357                         if (rc != MBX_BUSY)
14358                                 lpfc_printf_log(phba, KERN_ERR,
14359                                                 LOG_TRACE_EVENT,
14360                                                 "0385 rc should "
14361                                                 "have been MBX_BUSY\n");
14362                         if (rc != MBX_NOT_FINISHED)
14363                                 goto send_current_mbox;
14364                 }
14365         }
14366         spin_lock_irqsave(&phba->pport->work_port_lock, iflags);
14367         phba->pport->work_port_events &= ~WORKER_MBOX_TMO;
14368         spin_unlock_irqrestore(&phba->pport->work_port_lock, iflags);
14369
14370         /* Do NOT queue MBX_HEARTBEAT to the worker thread for processing. */
14371         if (pmbox->mbxCommand == MBX_HEARTBEAT) {
14372                 spin_lock_irqsave(&phba->hbalock, iflags);
14373                 /* Release the mailbox command posting token */
14374                 phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14375                 phba->sli.mbox_active = NULL;
14376                 if (bf_get(lpfc_trailer_consumed, mcqe))
14377                         lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14378                 spin_unlock_irqrestore(&phba->hbalock, iflags);
14379
14380                 /* Post the next mbox command, if there is one */
14381                 lpfc_sli4_post_async_mbox(phba);
14382
14383                 /* Process cmpl now */
14384                 if (pmb->mbox_cmpl)
14385                         pmb->mbox_cmpl(phba, pmb);
14386                 return false;
14387         }
14388
14389         /* There is mailbox completion work to queue to the worker thread */
14390         spin_lock_irqsave(&phba->hbalock, iflags);
14391         __lpfc_mbox_cmpl_put(phba, pmb);
14392         phba->work_ha |= HA_MBATT;
14393         spin_unlock_irqrestore(&phba->hbalock, iflags);
14394         workposted = true;
14395
14396 send_current_mbox:
14397         spin_lock_irqsave(&phba->hbalock, iflags);
14398         /* Release the mailbox command posting token */
14399         phba->sli.sli_flag &= ~LPFC_SLI_MBOX_ACTIVE;
14400         /* Setting active mailbox pointer need to be in sync to flag clear */
14401         phba->sli.mbox_active = NULL;
14402         if (bf_get(lpfc_trailer_consumed, mcqe))
14403                 lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14404         spin_unlock_irqrestore(&phba->hbalock, iflags);
14405         /* Wake up worker thread to post the next pending mailbox command */
14406         lpfc_worker_wake_up(phba);
14407         return workposted;
14408
14409 out_no_mqe_complete:
14410         spin_lock_irqsave(&phba->hbalock, iflags);
14411         if (bf_get(lpfc_trailer_consumed, mcqe))
14412                 lpfc_sli4_mq_release(phba->sli4_hba.mbx_wq);
14413         spin_unlock_irqrestore(&phba->hbalock, iflags);
14414         return false;
14415 }
14416
14417 /**
14418  * lpfc_sli4_sp_handle_mcqe - Process a mailbox completion queue entry
14419  * @phba: Pointer to HBA context object.
14420  * @cq: Pointer to associated CQ
14421  * @cqe: Pointer to mailbox completion queue entry.
14422  *
14423  * This routine process a mailbox completion queue entry, it invokes the
14424  * proper mailbox complete handling or asynchronous event handling routine
14425  * according to the MCQE's async bit.
14426  *
14427  * Return: true if work posted to worker thread, otherwise false.
14428  **/
14429 static bool
14430 lpfc_sli4_sp_handle_mcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14431                          struct lpfc_cqe *cqe)
14432 {
14433         struct lpfc_mcqe mcqe;
14434         bool workposted;
14435
14436         cq->CQ_mbox++;
14437
14438         /* Copy the mailbox MCQE and convert endian order as needed */
14439         lpfc_sli4_pcimem_bcopy(cqe, &mcqe, sizeof(struct lpfc_mcqe));
14440
14441         /* Invoke the proper event handling routine */
14442         if (!bf_get(lpfc_trailer_async, &mcqe))
14443                 workposted = lpfc_sli4_sp_handle_mbox_event(phba, &mcqe);
14444         else
14445                 workposted = lpfc_sli4_sp_handle_async_event(phba, &mcqe);
14446         return workposted;
14447 }
14448
14449 /**
14450  * lpfc_sli4_sp_handle_els_wcqe - Handle els work-queue completion event
14451  * @phba: Pointer to HBA context object.
14452  * @cq: Pointer to associated CQ
14453  * @wcqe: Pointer to work-queue completion queue entry.
14454  *
14455  * This routine handles an ELS work-queue completion event.
14456  *
14457  * Return: true if work posted to worker thread, otherwise false.
14458  **/
14459 static bool
14460 lpfc_sli4_sp_handle_els_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14461                              struct lpfc_wcqe_complete *wcqe)
14462 {
14463         struct lpfc_iocbq *irspiocbq;
14464         unsigned long iflags;
14465         struct lpfc_sli_ring *pring = cq->pring;
14466         int txq_cnt = 0;
14467         int txcmplq_cnt = 0;
14468
14469         /* Check for response status */
14470         if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
14471                 /* Log the error status */
14472                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14473                                 "0357 ELS CQE error: status=x%x: "
14474                                 "CQE: %08x %08x %08x %08x\n",
14475                                 bf_get(lpfc_wcqe_c_status, wcqe),
14476                                 wcqe->word0, wcqe->total_data_placed,
14477                                 wcqe->parameter, wcqe->word3);
14478         }
14479
14480         /* Get an irspiocbq for later ELS response processing use */
14481         irspiocbq = lpfc_sli_get_iocbq(phba);
14482         if (!irspiocbq) {
14483                 if (!list_empty(&pring->txq))
14484                         txq_cnt++;
14485                 if (!list_empty(&pring->txcmplq))
14486                         txcmplq_cnt++;
14487                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14488                         "0387 NO IOCBQ data: txq_cnt=%d iocb_cnt=%d "
14489                         "els_txcmplq_cnt=%d\n",
14490                         txq_cnt, phba->iocb_cnt,
14491                         txcmplq_cnt);
14492                 return false;
14493         }
14494
14495         /* Save off the slow-path queue event for work thread to process */
14496         memcpy(&irspiocbq->cq_event.cqe.wcqe_cmpl, wcqe, sizeof(*wcqe));
14497         spin_lock_irqsave(&phba->hbalock, iflags);
14498         list_add_tail(&irspiocbq->cq_event.list,
14499                       &phba->sli4_hba.sp_queue_event);
14500         spin_unlock_irqrestore(&phba->hbalock, iflags);
14501         set_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
14502
14503         return true;
14504 }
14505
14506 /**
14507  * lpfc_sli4_sp_handle_rel_wcqe - Handle slow-path WQ entry consumed event
14508  * @phba: Pointer to HBA context object.
14509  * @wcqe: Pointer to work-queue completion queue entry.
14510  *
14511  * This routine handles slow-path WQ entry consumed event by invoking the
14512  * proper WQ release routine to the slow-path WQ.
14513  **/
14514 static void
14515 lpfc_sli4_sp_handle_rel_wcqe(struct lpfc_hba *phba,
14516                              struct lpfc_wcqe_release *wcqe)
14517 {
14518         /* sanity check on queue memory */
14519         if (unlikely(!phba->sli4_hba.els_wq))
14520                 return;
14521         /* Check for the slow-path ELS work queue */
14522         if (bf_get(lpfc_wcqe_r_wq_id, wcqe) == phba->sli4_hba.els_wq->queue_id)
14523                 lpfc_sli4_wq_release(phba->sli4_hba.els_wq,
14524                                      bf_get(lpfc_wcqe_r_wqe_index, wcqe));
14525         else
14526                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
14527                                 "2579 Slow-path wqe consume event carries "
14528                                 "miss-matched qid: wcqe-qid=x%x, sp-qid=x%x\n",
14529                                 bf_get(lpfc_wcqe_r_wqe_index, wcqe),
14530                                 phba->sli4_hba.els_wq->queue_id);
14531 }
14532
14533 /**
14534  * lpfc_sli4_sp_handle_abort_xri_wcqe - Handle a xri abort event
14535  * @phba: Pointer to HBA context object.
14536  * @cq: Pointer to a WQ completion queue.
14537  * @wcqe: Pointer to work-queue completion queue entry.
14538  *
14539  * This routine handles an XRI abort event.
14540  *
14541  * Return: true if work posted to worker thread, otherwise false.
14542  **/
14543 static bool
14544 lpfc_sli4_sp_handle_abort_xri_wcqe(struct lpfc_hba *phba,
14545                                    struct lpfc_queue *cq,
14546                                    struct sli4_wcqe_xri_aborted *wcqe)
14547 {
14548         bool workposted = false;
14549         struct lpfc_cq_event *cq_event;
14550         unsigned long iflags;
14551
14552         switch (cq->subtype) {
14553         case LPFC_IO:
14554                 lpfc_sli4_io_xri_aborted(phba, wcqe, cq->hdwq);
14555                 if (phba->cfg_enable_fc4_type & LPFC_ENABLE_NVME) {
14556                         /* Notify aborted XRI for NVME work queue */
14557                         if (phba->nvmet_support)
14558                                 lpfc_sli4_nvmet_xri_aborted(phba, wcqe);
14559                 }
14560                 workposted = false;
14561                 break;
14562         case LPFC_NVME_LS: /* NVME LS uses ELS resources */
14563         case LPFC_ELS:
14564                 cq_event = lpfc_cq_event_setup(phba, wcqe, sizeof(*wcqe));
14565                 if (!cq_event) {
14566                         workposted = false;
14567                         break;
14568                 }
14569                 cq_event->hdwq = cq->hdwq;
14570                 spin_lock_irqsave(&phba->sli4_hba.els_xri_abrt_list_lock,
14571                                   iflags);
14572                 list_add_tail(&cq_event->list,
14573                               &phba->sli4_hba.sp_els_xri_aborted_work_queue);
14574                 /* Set the els xri abort event flag */
14575                 set_bit(ELS_XRI_ABORT_EVENT, &phba->hba_flag);
14576                 spin_unlock_irqrestore(&phba->sli4_hba.els_xri_abrt_list_lock,
14577                                        iflags);
14578                 workposted = true;
14579                 break;
14580         default:
14581                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14582                                 "0603 Invalid CQ subtype %d: "
14583                                 "%08x %08x %08x %08x\n",
14584                                 cq->subtype, wcqe->word0, wcqe->parameter,
14585                                 wcqe->word2, wcqe->word3);
14586                 workposted = false;
14587                 break;
14588         }
14589         return workposted;
14590 }
14591
14592 #define FC_RCTL_MDS_DIAGS       0xF4
14593
14594 /**
14595  * lpfc_sli4_sp_handle_rcqe - Process a receive-queue completion queue entry
14596  * @phba: Pointer to HBA context object.
14597  * @rcqe: Pointer to receive-queue completion queue entry.
14598  *
14599  * This routine process a receive-queue completion queue entry.
14600  *
14601  * Return: true if work posted to worker thread, otherwise false.
14602  **/
14603 static bool
14604 lpfc_sli4_sp_handle_rcqe(struct lpfc_hba *phba, struct lpfc_rcqe *rcqe)
14605 {
14606         bool workposted = false;
14607         struct fc_frame_header *fc_hdr;
14608         struct lpfc_queue *hrq = phba->sli4_hba.hdr_rq;
14609         struct lpfc_queue *drq = phba->sli4_hba.dat_rq;
14610         struct lpfc_nvmet_tgtport *tgtp;
14611         struct hbq_dmabuf *dma_buf;
14612         uint32_t status, rq_id;
14613         unsigned long iflags;
14614
14615         /* sanity check on queue memory */
14616         if (unlikely(!hrq) || unlikely(!drq))
14617                 return workposted;
14618
14619         if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
14620                 rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
14621         else
14622                 rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
14623         if (rq_id != hrq->queue_id)
14624                 goto out;
14625
14626         status = bf_get(lpfc_rcqe_status, rcqe);
14627         switch (status) {
14628         case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
14629                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14630                                 "2537 Receive Frame Truncated!!\n");
14631                 fallthrough;
14632         case FC_STATUS_RQ_SUCCESS:
14633                 spin_lock_irqsave(&phba->hbalock, iflags);
14634                 lpfc_sli4_rq_release(hrq, drq);
14635                 dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14636                 if (!dma_buf) {
14637                         hrq->RQ_no_buf_found++;
14638                         spin_unlock_irqrestore(&phba->hbalock, iflags);
14639                         goto out;
14640                 }
14641                 hrq->RQ_rcv_buf++;
14642                 hrq->RQ_buf_posted--;
14643                 memcpy(&dma_buf->cq_event.cqe.rcqe_cmpl, rcqe, sizeof(*rcqe));
14644
14645                 fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
14646
14647                 if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
14648                     fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
14649                         spin_unlock_irqrestore(&phba->hbalock, iflags);
14650                         /* Handle MDS Loopback frames */
14651                         if  (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
14652                                 lpfc_sli4_handle_mds_loopback(phba->pport,
14653                                                               dma_buf);
14654                         else
14655                                 lpfc_in_buf_free(phba, &dma_buf->dbuf);
14656                         break;
14657                 }
14658
14659                 /* save off the frame for the work thread to process */
14660                 list_add_tail(&dma_buf->cq_event.list,
14661                               &phba->sli4_hba.sp_queue_event);
14662                 spin_unlock_irqrestore(&phba->hbalock, iflags);
14663                 /* Frame received */
14664                 set_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
14665                 workposted = true;
14666                 break;
14667         case FC_STATUS_INSUFF_BUF_FRM_DISC:
14668                 if (phba->nvmet_support) {
14669                         tgtp = phba->targetport->private;
14670                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14671                                         "6402 RQE Error x%x, posted %d err_cnt "
14672                                         "%d: %x %x %x\n",
14673                                         status, hrq->RQ_buf_posted,
14674                                         hrq->RQ_no_posted_buf,
14675                                         atomic_read(&tgtp->rcv_fcp_cmd_in),
14676                                         atomic_read(&tgtp->rcv_fcp_cmd_out),
14677                                         atomic_read(&tgtp->xmt_fcp_release));
14678                 }
14679                 fallthrough;
14680
14681         case FC_STATUS_INSUFF_BUF_NEED_BUF:
14682                 hrq->RQ_no_posted_buf++;
14683                 /* Post more buffers if possible */
14684                 set_bit(HBA_POST_RECEIVE_BUFFER, &phba->hba_flag);
14685                 workposted = true;
14686                 break;
14687         case FC_STATUS_RQ_DMA_FAILURE:
14688                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14689                                 "2564 RQE DMA Error x%x, x%08x x%08x x%08x "
14690                                 "x%08x\n",
14691                                 status, rcqe->word0, rcqe->word1,
14692                                 rcqe->word2, rcqe->word3);
14693
14694                 /* If IV set, no further recovery */
14695                 if (bf_get(lpfc_rcqe_iv, rcqe))
14696                         break;
14697
14698                 /* recycle consumed resource */
14699                 spin_lock_irqsave(&phba->hbalock, iflags);
14700                 lpfc_sli4_rq_release(hrq, drq);
14701                 dma_buf = lpfc_sli_hbqbuf_get(&phba->hbqs[0].hbq_buffer_list);
14702                 if (!dma_buf) {
14703                         hrq->RQ_no_buf_found++;
14704                         spin_unlock_irqrestore(&phba->hbalock, iflags);
14705                         break;
14706                 }
14707                 hrq->RQ_rcv_buf++;
14708                 hrq->RQ_buf_posted--;
14709                 spin_unlock_irqrestore(&phba->hbalock, iflags);
14710                 lpfc_in_buf_free(phba, &dma_buf->dbuf);
14711                 break;
14712         default:
14713                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14714                                 "2565 Unexpected RQE Status x%x, w0-3 x%08x "
14715                                 "x%08x x%08x x%08x\n",
14716                                 status, rcqe->word0, rcqe->word1,
14717                                 rcqe->word2, rcqe->word3);
14718                 break;
14719         }
14720 out:
14721         return workposted;
14722 }
14723
14724 /**
14725  * lpfc_sli4_sp_handle_cqe - Process a slow path completion queue entry
14726  * @phba: Pointer to HBA context object.
14727  * @cq: Pointer to the completion queue.
14728  * @cqe: Pointer to a completion queue entry.
14729  *
14730  * This routine process a slow-path work-queue or receive queue completion queue
14731  * entry.
14732  *
14733  * Return: true if work posted to worker thread, otherwise false.
14734  **/
14735 static bool
14736 lpfc_sli4_sp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
14737                          struct lpfc_cqe *cqe)
14738 {
14739         struct lpfc_cqe cqevt;
14740         bool workposted = false;
14741
14742         /* Copy the work queue CQE and convert endian order if needed */
14743         lpfc_sli4_pcimem_bcopy(cqe, &cqevt, sizeof(struct lpfc_cqe));
14744
14745         /* Check and process for different type of WCQE and dispatch */
14746         switch (bf_get(lpfc_cqe_code, &cqevt)) {
14747         case CQE_CODE_COMPL_WQE:
14748                 /* Process the WQ/RQ complete event */
14749                 phba->last_completion_time = jiffies;
14750                 workposted = lpfc_sli4_sp_handle_els_wcqe(phba, cq,
14751                                 (struct lpfc_wcqe_complete *)&cqevt);
14752                 break;
14753         case CQE_CODE_RELEASE_WQE:
14754                 /* Process the WQ release event */
14755                 lpfc_sli4_sp_handle_rel_wcqe(phba,
14756                                 (struct lpfc_wcqe_release *)&cqevt);
14757                 break;
14758         case CQE_CODE_XRI_ABORTED:
14759                 /* Process the WQ XRI abort event */
14760                 phba->last_completion_time = jiffies;
14761                 workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
14762                                 (struct sli4_wcqe_xri_aborted *)&cqevt);
14763                 break;
14764         case CQE_CODE_RECEIVE:
14765         case CQE_CODE_RECEIVE_V1:
14766                 /* Process the RQ event */
14767                 phba->last_completion_time = jiffies;
14768                 workposted = lpfc_sli4_sp_handle_rcqe(phba,
14769                                 (struct lpfc_rcqe *)&cqevt);
14770                 break;
14771         default:
14772                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14773                                 "0388 Not a valid WCQE code: x%x\n",
14774                                 bf_get(lpfc_cqe_code, &cqevt));
14775                 break;
14776         }
14777         return workposted;
14778 }
14779
14780 /**
14781  * lpfc_sli4_sp_handle_eqe - Process a slow-path event queue entry
14782  * @phba: Pointer to HBA context object.
14783  * @eqe: Pointer to fast-path event queue entry.
14784  * @speq: Pointer to slow-path event queue.
14785  *
14786  * This routine process a event queue entry from the slow-path event queue.
14787  * It will check the MajorCode and MinorCode to determine this is for a
14788  * completion event on a completion queue, if not, an error shall be logged
14789  * and just return. Otherwise, it will get to the corresponding completion
14790  * queue and process all the entries on that completion queue, rearm the
14791  * completion queue, and then return.
14792  *
14793  **/
14794 static void
14795 lpfc_sli4_sp_handle_eqe(struct lpfc_hba *phba, struct lpfc_eqe *eqe,
14796         struct lpfc_queue *speq)
14797 {
14798         struct lpfc_queue *cq = NULL, *childq;
14799         uint16_t cqid;
14800         int ret = 0;
14801
14802         /* Get the reference to the corresponding CQ */
14803         cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
14804
14805         list_for_each_entry(childq, &speq->child_list, list) {
14806                 if (childq->queue_id == cqid) {
14807                         cq = childq;
14808                         break;
14809                 }
14810         }
14811         if (unlikely(!cq)) {
14812                 if (phba->sli.sli_flag & LPFC_SLI_ACTIVE)
14813                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14814                                         "0365 Slow-path CQ identifier "
14815                                         "(%d) does not exist\n", cqid);
14816                 return;
14817         }
14818
14819         /* Save EQ associated with this CQ */
14820         cq->assoc_qp = speq;
14821
14822         if (is_kdump_kernel())
14823                 ret = queue_work(phba->wq, &cq->spwork);
14824         else
14825                 ret = queue_work_on(cq->chann, phba->wq, &cq->spwork);
14826
14827         if (!ret)
14828                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14829                                 "0390 Cannot schedule queue work "
14830                                 "for CQ eqcqid=%d, cqid=%d on CPU %d\n",
14831                                 cqid, cq->queue_id, raw_smp_processor_id());
14832 }
14833
14834 /**
14835  * __lpfc_sli4_process_cq - Process elements of a CQ
14836  * @phba: Pointer to HBA context object.
14837  * @cq: Pointer to CQ to be processed
14838  * @handler: Routine to process each cqe
14839  * @delay: Pointer to usdelay to set in case of rescheduling of the handler
14840  *
14841  * This routine processes completion queue entries in a CQ. While a valid
14842  * queue element is found, the handler is called. During processing checks
14843  * are made for periodic doorbell writes to let the hardware know of
14844  * element consumption.
14845  *
14846  * If the max limit on cqes to process is hit, or there are no more valid
14847  * entries, the loop stops. If we processed a sufficient number of elements,
14848  * meaning there is sufficient load, rather than rearming and generating
14849  * another interrupt, a cq rescheduling delay will be set. A delay of 0
14850  * indicates no rescheduling.
14851  *
14852  * Returns True if work scheduled, False otherwise.
14853  **/
14854 static bool
14855 __lpfc_sli4_process_cq(struct lpfc_hba *phba, struct lpfc_queue *cq,
14856         bool (*handler)(struct lpfc_hba *, struct lpfc_queue *,
14857                         struct lpfc_cqe *), unsigned long *delay)
14858 {
14859         struct lpfc_cqe *cqe;
14860         bool workposted = false;
14861         int count = 0, consumed = 0;
14862         bool arm = true;
14863
14864         /* default - no reschedule */
14865         *delay = 0;
14866
14867         if (cmpxchg(&cq->queue_claimed, 0, 1) != 0)
14868                 goto rearm_and_exit;
14869
14870         /* Process all the entries to the CQ */
14871         cq->q_flag = 0;
14872         cqe = lpfc_sli4_cq_get(cq);
14873         while (cqe) {
14874                 workposted |= handler(phba, cq, cqe);
14875                 __lpfc_sli4_consume_cqe(phba, cq, cqe);
14876
14877                 consumed++;
14878                 if (!(++count % cq->max_proc_limit))
14879                         break;
14880
14881                 if (!(count % cq->notify_interval)) {
14882                         phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14883                                                 LPFC_QUEUE_NOARM);
14884                         consumed = 0;
14885                         cq->assoc_qp->q_flag |= HBA_EQ_DELAY_CHK;
14886                 }
14887
14888                 if (count == LPFC_NVMET_CQ_NOTIFY)
14889                         cq->q_flag |= HBA_NVMET_CQ_NOTIFY;
14890
14891                 cqe = lpfc_sli4_cq_get(cq);
14892         }
14893         if (count >= phba->cfg_cq_poll_threshold) {
14894                 *delay = 1;
14895                 arm = false;
14896         }
14897
14898         /* Track the max number of CQEs processed in 1 EQ */
14899         if (count > cq->CQ_max_cqe)
14900                 cq->CQ_max_cqe = count;
14901
14902         cq->assoc_qp->EQ_cqe_cnt += count;
14903
14904         /* Catch the no cq entry condition */
14905         if (unlikely(count == 0))
14906                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
14907                                 "0369 No entry from completion queue "
14908                                 "qid=%d\n", cq->queue_id);
14909
14910         xchg(&cq->queue_claimed, 0);
14911
14912 rearm_and_exit:
14913         phba->sli4_hba.sli4_write_cq_db(phba, cq, consumed,
14914                         arm ?  LPFC_QUEUE_REARM : LPFC_QUEUE_NOARM);
14915
14916         return workposted;
14917 }
14918
14919 /**
14920  * __lpfc_sli4_sp_process_cq - Process a slow-path event queue entry
14921  * @cq: pointer to CQ to process
14922  *
14923  * This routine calls the cq processing routine with a handler specific
14924  * to the type of queue bound to it.
14925  *
14926  * The CQ routine returns two values: the first is the calling status,
14927  * which indicates whether work was queued to the  background discovery
14928  * thread. If true, the routine should wakeup the discovery thread;
14929  * the second is the delay parameter. If non-zero, rather than rearming
14930  * the CQ and yet another interrupt, the CQ handler should be queued so
14931  * that it is processed in a subsequent polling action. The value of
14932  * the delay indicates when to reschedule it.
14933  **/
14934 static void
14935 __lpfc_sli4_sp_process_cq(struct lpfc_queue *cq)
14936 {
14937         struct lpfc_hba *phba = cq->phba;
14938         unsigned long delay;
14939         bool workposted = false;
14940         int ret = 0;
14941
14942         /* Process and rearm the CQ */
14943         switch (cq->type) {
14944         case LPFC_MCQ:
14945                 workposted |= __lpfc_sli4_process_cq(phba, cq,
14946                                                 lpfc_sli4_sp_handle_mcqe,
14947                                                 &delay);
14948                 break;
14949         case LPFC_WCQ:
14950                 if (cq->subtype == LPFC_IO)
14951                         workposted |= __lpfc_sli4_process_cq(phba, cq,
14952                                                 lpfc_sli4_fp_handle_cqe,
14953                                                 &delay);
14954                 else
14955                         workposted |= __lpfc_sli4_process_cq(phba, cq,
14956                                                 lpfc_sli4_sp_handle_cqe,
14957                                                 &delay);
14958                 break;
14959         default:
14960                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14961                                 "0370 Invalid completion queue type (%d)\n",
14962                                 cq->type);
14963                 return;
14964         }
14965
14966         if (delay) {
14967                 if (is_kdump_kernel())
14968                         ret = queue_delayed_work(phba->wq, &cq->sched_spwork,
14969                                                 delay);
14970                 else
14971                         ret = queue_delayed_work_on(cq->chann, phba->wq,
14972                                                 &cq->sched_spwork, delay);
14973                 if (!ret)
14974                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
14975                                 "0394 Cannot schedule queue work "
14976                                 "for cqid=%d on CPU %d\n",
14977                                 cq->queue_id, cq->chann);
14978         }
14979
14980         /* wake up worker thread if there are works to be done */
14981         if (workposted)
14982                 lpfc_worker_wake_up(phba);
14983 }
14984
14985 /**
14986  * lpfc_sli4_sp_process_cq - slow-path work handler when started by
14987  *   interrupt
14988  * @work: pointer to work element
14989  *
14990  * translates from the work handler and calls the slow-path handler.
14991  **/
14992 static void
14993 lpfc_sli4_sp_process_cq(struct work_struct *work)
14994 {
14995         struct lpfc_queue *cq = container_of(work, struct lpfc_queue, spwork);
14996
14997         __lpfc_sli4_sp_process_cq(cq);
14998 }
14999
15000 /**
15001  * lpfc_sli4_dly_sp_process_cq - slow-path work handler when started by timer
15002  * @work: pointer to work element
15003  *
15004  * translates from the work handler and calls the slow-path handler.
15005  **/
15006 static void
15007 lpfc_sli4_dly_sp_process_cq(struct work_struct *work)
15008 {
15009         struct lpfc_queue *cq = container_of(to_delayed_work(work),
15010                                         struct lpfc_queue, sched_spwork);
15011
15012         __lpfc_sli4_sp_process_cq(cq);
15013 }
15014
15015 /**
15016  * lpfc_sli4_fp_handle_fcp_wcqe - Process fast-path work queue completion entry
15017  * @phba: Pointer to HBA context object.
15018  * @cq: Pointer to associated CQ
15019  * @wcqe: Pointer to work-queue completion queue entry.
15020  *
15021  * This routine process a fast-path work queue completion entry from fast-path
15022  * event queue for FCP command response completion.
15023  **/
15024 static void
15025 lpfc_sli4_fp_handle_fcp_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15026                              struct lpfc_wcqe_complete *wcqe)
15027 {
15028         struct lpfc_sli_ring *pring = cq->pring;
15029         struct lpfc_iocbq *cmdiocbq;
15030         unsigned long iflags;
15031
15032         /* Check for response status */
15033         if (unlikely(bf_get(lpfc_wcqe_c_status, wcqe))) {
15034                 /* If resource errors reported from HBA, reduce queue
15035                  * depth of the SCSI device.
15036                  */
15037                 if (((bf_get(lpfc_wcqe_c_status, wcqe) ==
15038                      IOSTAT_LOCAL_REJECT)) &&
15039                     ((wcqe->parameter & IOERR_PARAM_MASK) ==
15040                      IOERR_NO_RESOURCES))
15041                         phba->lpfc_rampdown_queue_depth(phba);
15042
15043                 /* Log the cmpl status */
15044                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
15045                                 "0373 FCP CQE cmpl: status=x%x: "
15046                                 "CQE: %08x %08x %08x %08x\n",
15047                                 bf_get(lpfc_wcqe_c_status, wcqe),
15048                                 wcqe->word0, wcqe->total_data_placed,
15049                                 wcqe->parameter, wcqe->word3);
15050         }
15051
15052         /* Look up the FCP command IOCB and create pseudo response IOCB */
15053         spin_lock_irqsave(&pring->ring_lock, iflags);
15054         pring->stats.iocb_event++;
15055         cmdiocbq = lpfc_sli_iocbq_lookup_by_tag(phba, pring,
15056                                 bf_get(lpfc_wcqe_c_request_tag, wcqe));
15057         spin_unlock_irqrestore(&pring->ring_lock, iflags);
15058         if (unlikely(!cmdiocbq)) {
15059                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15060                                 "0374 FCP complete with no corresponding "
15061                                 "cmdiocb: iotag (%d)\n",
15062                                 bf_get(lpfc_wcqe_c_request_tag, wcqe));
15063                 return;
15064         }
15065 #ifdef CONFIG_SCSI_LPFC_DEBUG_FS
15066         cmdiocbq->isr_timestamp = cq->isr_timestamp;
15067 #endif
15068         if (bf_get(lpfc_wcqe_c_xb, wcqe)) {
15069                 spin_lock_irqsave(&phba->hbalock, iflags);
15070                 cmdiocbq->cmd_flag |= LPFC_EXCHANGE_BUSY;
15071                 spin_unlock_irqrestore(&phba->hbalock, iflags);
15072         }
15073
15074         if (cmdiocbq->cmd_cmpl) {
15075                 /* For FCP the flag is cleared in cmd_cmpl */
15076                 if (!(cmdiocbq->cmd_flag & LPFC_IO_FCP) &&
15077                     cmdiocbq->cmd_flag & LPFC_DRIVER_ABORTED) {
15078                         spin_lock_irqsave(&phba->hbalock, iflags);
15079                         cmdiocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
15080                         spin_unlock_irqrestore(&phba->hbalock, iflags);
15081                 }
15082
15083                 /* Pass the cmd_iocb and the wcqe to the upper layer */
15084                 memcpy(&cmdiocbq->wcqe_cmpl, wcqe,
15085                        sizeof(struct lpfc_wcqe_complete));
15086                 cmdiocbq->cmd_cmpl(phba, cmdiocbq, cmdiocbq);
15087         } else {
15088                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15089                                 "0375 FCP cmdiocb not callback function "
15090                                 "iotag: (%d)\n",
15091                                 bf_get(lpfc_wcqe_c_request_tag, wcqe));
15092         }
15093 }
15094
15095 /**
15096  * lpfc_sli4_fp_handle_rel_wcqe - Handle fast-path WQ entry consumed event
15097  * @phba: Pointer to HBA context object.
15098  * @cq: Pointer to completion queue.
15099  * @wcqe: Pointer to work-queue completion queue entry.
15100  *
15101  * This routine handles an fast-path WQ entry consumed event by invoking the
15102  * proper WQ release routine to the slow-path WQ.
15103  **/
15104 static void
15105 lpfc_sli4_fp_handle_rel_wcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15106                              struct lpfc_wcqe_release *wcqe)
15107 {
15108         struct lpfc_queue *childwq;
15109         bool wqid_matched = false;
15110         uint16_t hba_wqid;
15111
15112         /* Check for fast-path FCP work queue release */
15113         hba_wqid = bf_get(lpfc_wcqe_r_wq_id, wcqe);
15114         list_for_each_entry(childwq, &cq->child_list, list) {
15115                 if (childwq->queue_id == hba_wqid) {
15116                         lpfc_sli4_wq_release(childwq,
15117                                         bf_get(lpfc_wcqe_r_wqe_index, wcqe));
15118                         if (childwq->q_flag & HBA_NVMET_WQFULL)
15119                                 lpfc_nvmet_wqfull_process(phba, childwq);
15120                         wqid_matched = true;
15121                         break;
15122                 }
15123         }
15124         /* Report warning log message if no match found */
15125         if (wqid_matched != true)
15126                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15127                                 "2580 Fast-path wqe consume event carries "
15128                                 "miss-matched qid: wcqe-qid=x%x\n", hba_wqid);
15129 }
15130
15131 /**
15132  * lpfc_sli4_nvmet_handle_rcqe - Process a receive-queue completion queue entry
15133  * @phba: Pointer to HBA context object.
15134  * @cq: Pointer to completion queue.
15135  * @rcqe: Pointer to receive-queue completion queue entry.
15136  *
15137  * This routine process a receive-queue completion queue entry.
15138  *
15139  * Return: true if work posted to worker thread, otherwise false.
15140  **/
15141 static bool
15142 lpfc_sli4_nvmet_handle_rcqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15143                             struct lpfc_rcqe *rcqe)
15144 {
15145         bool workposted = false;
15146         struct lpfc_queue *hrq;
15147         struct lpfc_queue *drq;
15148         struct rqb_dmabuf *dma_buf;
15149         struct fc_frame_header *fc_hdr;
15150         struct lpfc_nvmet_tgtport *tgtp;
15151         uint32_t status, rq_id;
15152         unsigned long iflags;
15153         uint32_t fctl, idx;
15154
15155         if ((phba->nvmet_support == 0) ||
15156             (phba->sli4_hba.nvmet_cqset == NULL))
15157                 return workposted;
15158
15159         idx = cq->queue_id - phba->sli4_hba.nvmet_cqset[0]->queue_id;
15160         hrq = phba->sli4_hba.nvmet_mrq_hdr[idx];
15161         drq = phba->sli4_hba.nvmet_mrq_data[idx];
15162
15163         /* sanity check on queue memory */
15164         if (unlikely(!hrq) || unlikely(!drq))
15165                 return workposted;
15166
15167         if (bf_get(lpfc_cqe_code, rcqe) == CQE_CODE_RECEIVE_V1)
15168                 rq_id = bf_get(lpfc_rcqe_rq_id_v1, rcqe);
15169         else
15170                 rq_id = bf_get(lpfc_rcqe_rq_id, rcqe);
15171
15172         if ((phba->nvmet_support == 0) ||
15173             (rq_id != hrq->queue_id))
15174                 return workposted;
15175
15176         status = bf_get(lpfc_rcqe_status, rcqe);
15177         switch (status) {
15178         case FC_STATUS_RQ_BUF_LEN_EXCEEDED:
15179                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15180                                 "6126 Receive Frame Truncated!!\n");
15181                 fallthrough;
15182         case FC_STATUS_RQ_SUCCESS:
15183                 spin_lock_irqsave(&phba->hbalock, iflags);
15184                 lpfc_sli4_rq_release(hrq, drq);
15185                 dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15186                 if (!dma_buf) {
15187                         hrq->RQ_no_buf_found++;
15188                         spin_unlock_irqrestore(&phba->hbalock, iflags);
15189                         goto out;
15190                 }
15191                 spin_unlock_irqrestore(&phba->hbalock, iflags);
15192                 hrq->RQ_rcv_buf++;
15193                 hrq->RQ_buf_posted--;
15194                 fc_hdr = (struct fc_frame_header *)dma_buf->hbuf.virt;
15195
15196                 /* Just some basic sanity checks on FCP Command frame */
15197                 fctl = (fc_hdr->fh_f_ctl[0] << 16 |
15198                         fc_hdr->fh_f_ctl[1] << 8 |
15199                         fc_hdr->fh_f_ctl[2]);
15200                 if (((fctl &
15201                     (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) !=
15202                     (FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT)) ||
15203                     (fc_hdr->fh_seq_cnt != 0)) /* 0 byte swapped is still 0 */
15204                         goto drop;
15205
15206                 if (fc_hdr->fh_type == FC_TYPE_FCP) {
15207                         dma_buf->bytes_recv = bf_get(lpfc_rcqe_length, rcqe);
15208                         lpfc_nvmet_unsol_fcp_event(
15209                                 phba, idx, dma_buf, cq->isr_timestamp,
15210                                 cq->q_flag & HBA_NVMET_CQ_NOTIFY);
15211                         return false;
15212                 }
15213 drop:
15214                 lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15215                 break;
15216         case FC_STATUS_INSUFF_BUF_FRM_DISC:
15217                 if (phba->nvmet_support) {
15218                         tgtp = phba->targetport->private;
15219                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15220                                         "6401 RQE Error x%x, posted %d err_cnt "
15221                                         "%d: %x %x %x\n",
15222                                         status, hrq->RQ_buf_posted,
15223                                         hrq->RQ_no_posted_buf,
15224                                         atomic_read(&tgtp->rcv_fcp_cmd_in),
15225                                         atomic_read(&tgtp->rcv_fcp_cmd_out),
15226                                         atomic_read(&tgtp->xmt_fcp_release));
15227                 }
15228                 fallthrough;
15229
15230         case FC_STATUS_INSUFF_BUF_NEED_BUF:
15231                 hrq->RQ_no_posted_buf++;
15232                 /* Post more buffers if possible */
15233                 break;
15234         case FC_STATUS_RQ_DMA_FAILURE:
15235                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15236                                 "2575 RQE DMA Error x%x, x%08x x%08x x%08x "
15237                                 "x%08x\n",
15238                                 status, rcqe->word0, rcqe->word1,
15239                                 rcqe->word2, rcqe->word3);
15240
15241                 /* If IV set, no further recovery */
15242                 if (bf_get(lpfc_rcqe_iv, rcqe))
15243                         break;
15244
15245                 /* recycle consumed resource */
15246                 spin_lock_irqsave(&phba->hbalock, iflags);
15247                 lpfc_sli4_rq_release(hrq, drq);
15248                 dma_buf = lpfc_sli_rqbuf_get(phba, hrq);
15249                 if (!dma_buf) {
15250                         hrq->RQ_no_buf_found++;
15251                         spin_unlock_irqrestore(&phba->hbalock, iflags);
15252                         break;
15253                 }
15254                 hrq->RQ_rcv_buf++;
15255                 hrq->RQ_buf_posted--;
15256                 spin_unlock_irqrestore(&phba->hbalock, iflags);
15257                 lpfc_rq_buf_free(phba, &dma_buf->hbuf);
15258                 break;
15259         default:
15260                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15261                                 "2576 Unexpected RQE Status x%x, w0-3 x%08x "
15262                                 "x%08x x%08x x%08x\n",
15263                                 status, rcqe->word0, rcqe->word1,
15264                                 rcqe->word2, rcqe->word3);
15265                 break;
15266         }
15267 out:
15268         return workposted;
15269 }
15270
15271 /**
15272  * lpfc_sli4_fp_handle_cqe - Process fast-path work queue completion entry
15273  * @phba: adapter with cq
15274  * @cq: Pointer to the completion queue.
15275  * @cqe: Pointer to fast-path completion queue entry.
15276  *
15277  * This routine process a fast-path work queue completion entry from fast-path
15278  * event queue for FCP command response completion.
15279  *
15280  * Return: true if work posted to worker thread, otherwise false.
15281  **/
15282 static bool
15283 lpfc_sli4_fp_handle_cqe(struct lpfc_hba *phba, struct lpfc_queue *cq,
15284                          struct lpfc_cqe *cqe)
15285 {
15286         struct lpfc_wcqe_release wcqe;
15287         bool workposted = false;
15288
15289         /* Copy the work queue CQE and convert endian order if needed */
15290         lpfc_sli4_pcimem_bcopy(cqe, &wcqe, sizeof(struct lpfc_cqe));
15291
15292         /* Check and process for different type of WCQE and dispatch */
15293         switch (bf_get(lpfc_wcqe_c_code, &wcqe)) {
15294         case CQE_CODE_COMPL_WQE:
15295         case CQE_CODE_NVME_ERSP:
15296                 cq->CQ_wq++;
15297                 /* Process the WQ complete event */
15298                 phba->last_completion_time = jiffies;
15299                 if (cq->subtype == LPFC_IO || cq->subtype == LPFC_NVME_LS)
15300                         lpfc_sli4_fp_handle_fcp_wcqe(phba, cq,
15301                                 (struct lpfc_wcqe_complete *)&wcqe);
15302                 break;
15303         case CQE_CODE_RELEASE_WQE:
15304                 cq->CQ_release_wqe++;
15305                 /* Process the WQ release event */
15306                 lpfc_sli4_fp_handle_rel_wcqe(phba, cq,
15307                                 (struct lpfc_wcqe_release *)&wcqe);
15308                 break;
15309         case CQE_CODE_XRI_ABORTED:
15310                 cq->CQ_xri_aborted++;
15311                 /* Process the WQ XRI abort event */
15312                 phba->last_completion_time = jiffies;
15313                 workposted = lpfc_sli4_sp_handle_abort_xri_wcqe(phba, cq,
15314                                 (struct sli4_wcqe_xri_aborted *)&wcqe);
15315                 break;
15316         case CQE_CODE_RECEIVE_V1:
15317         case CQE_CODE_RECEIVE:
15318                 phba->last_completion_time = jiffies;
15319                 if (cq->subtype == LPFC_NVMET) {
15320                         workposted = lpfc_sli4_nvmet_handle_rcqe(
15321                                 phba, cq, (struct lpfc_rcqe *)&wcqe);
15322                 }
15323                 break;
15324         default:
15325                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15326                                 "0144 Not a valid CQE code: x%x\n",
15327                                 bf_get(lpfc_wcqe_c_code, &wcqe));
15328                 break;
15329         }
15330         return workposted;
15331 }
15332
15333 /**
15334  * __lpfc_sli4_hba_process_cq - Process a fast-path event queue entry
15335  * @cq: Pointer to CQ to be processed
15336  *
15337  * This routine calls the cq processing routine with the handler for
15338  * fast path CQEs.
15339  *
15340  * The CQ routine returns two values: the first is the calling status,
15341  * which indicates whether work was queued to the  background discovery
15342  * thread. If true, the routine should wakeup the discovery thread;
15343  * the second is the delay parameter. If non-zero, rather than rearming
15344  * the CQ and yet another interrupt, the CQ handler should be queued so
15345  * that it is processed in a subsequent polling action. The value of
15346  * the delay indicates when to reschedule it.
15347  **/
15348 static void
15349 __lpfc_sli4_hba_process_cq(struct lpfc_queue *cq)
15350 {
15351         struct lpfc_hba *phba = cq->phba;
15352         unsigned long delay;
15353         bool workposted = false;
15354         int ret;
15355
15356         /* process and rearm the CQ */
15357         workposted |= __lpfc_sli4_process_cq(phba, cq, lpfc_sli4_fp_handle_cqe,
15358                                              &delay);
15359
15360         if (delay) {
15361                 if (is_kdump_kernel())
15362                         ret = queue_delayed_work(phba->wq, &cq->sched_irqwork,
15363                                                 delay);
15364                 else
15365                         ret = queue_delayed_work_on(cq->chann, phba->wq,
15366                                                 &cq->sched_irqwork, delay);
15367                 if (!ret)
15368                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15369                                         "0367 Cannot schedule queue work "
15370                                         "for cqid=%d on CPU %d\n",
15371                                         cq->queue_id, cq->chann);
15372         }
15373
15374         /* wake up worker thread if there are works to be done */
15375         if (workposted)
15376                 lpfc_worker_wake_up(phba);
15377 }
15378
15379 /**
15380  * lpfc_sli4_hba_process_cq - fast-path work handler when started by
15381  *   interrupt
15382  * @work: pointer to work element
15383  *
15384  * translates from the work handler and calls the fast-path handler.
15385  **/
15386 static void
15387 lpfc_sli4_hba_process_cq(struct work_struct *work)
15388 {
15389         struct lpfc_queue *cq = container_of(work, struct lpfc_queue, irqwork);
15390
15391         __lpfc_sli4_hba_process_cq(cq);
15392 }
15393
15394 /**
15395  * lpfc_sli4_hba_handle_eqe - Process a fast-path event queue entry
15396  * @phba: Pointer to HBA context object.
15397  * @eq: Pointer to the queue structure.
15398  * @eqe: Pointer to fast-path event queue entry.
15399  * @poll_mode: poll_mode to execute processing the cq.
15400  *
15401  * This routine process a event queue entry from the fast-path event queue.
15402  * It will check the MajorCode and MinorCode to determine this is for a
15403  * completion event on a completion queue, if not, an error shall be logged
15404  * and just return. Otherwise, it will get to the corresponding completion
15405  * queue and process all the entries on the completion queue, rearm the
15406  * completion queue, and then return.
15407  **/
15408 static void
15409 lpfc_sli4_hba_handle_eqe(struct lpfc_hba *phba, struct lpfc_queue *eq,
15410                          struct lpfc_eqe *eqe, enum lpfc_poll_mode poll_mode)
15411 {
15412         struct lpfc_queue *cq = NULL;
15413         uint32_t qidx = eq->hdwq;
15414         uint16_t cqid, id;
15415         int ret;
15416
15417         if (unlikely(bf_get_le32(lpfc_eqe_major_code, eqe) != 0)) {
15418                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15419                                 "0366 Not a valid completion "
15420                                 "event: majorcode=x%x, minorcode=x%x\n",
15421                                 bf_get_le32(lpfc_eqe_major_code, eqe),
15422                                 bf_get_le32(lpfc_eqe_minor_code, eqe));
15423                 return;
15424         }
15425
15426         /* Get the reference to the corresponding CQ */
15427         cqid = bf_get_le32(lpfc_eqe_resource_id, eqe);
15428
15429         /* Use the fast lookup method first */
15430         if (cqid <= phba->sli4_hba.cq_max) {
15431                 cq = phba->sli4_hba.cq_lookup[cqid];
15432                 if (cq)
15433                         goto  work_cq;
15434         }
15435
15436         /* Next check for NVMET completion */
15437         if (phba->cfg_nvmet_mrq && phba->sli4_hba.nvmet_cqset) {
15438                 id = phba->sli4_hba.nvmet_cqset[0]->queue_id;
15439                 if ((cqid >= id) && (cqid < (id + phba->cfg_nvmet_mrq))) {
15440                         /* Process NVMET unsol rcv */
15441                         cq = phba->sli4_hba.nvmet_cqset[cqid - id];
15442                         goto  process_cq;
15443                 }
15444         }
15445
15446         if (phba->sli4_hba.nvmels_cq &&
15447             (cqid == phba->sli4_hba.nvmels_cq->queue_id)) {
15448                 /* Process NVME unsol rcv */
15449                 cq = phba->sli4_hba.nvmels_cq;
15450         }
15451
15452         /* Otherwise this is a Slow path event */
15453         if (cq == NULL) {
15454                 lpfc_sli4_sp_handle_eqe(phba, eqe,
15455                                         phba->sli4_hba.hdwq[qidx].hba_eq);
15456                 return;
15457         }
15458
15459 process_cq:
15460         if (unlikely(cqid != cq->queue_id)) {
15461                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15462                                 "0368 Miss-matched fast-path completion "
15463                                 "queue identifier: eqcqid=%d, fcpcqid=%d\n",
15464                                 cqid, cq->queue_id);
15465                 return;
15466         }
15467
15468 work_cq:
15469 #if defined(CONFIG_SCSI_LPFC_DEBUG_FS)
15470         if (phba->ktime_on)
15471                 cq->isr_timestamp = ktime_get_ns();
15472         else
15473                 cq->isr_timestamp = 0;
15474 #endif
15475
15476         switch (poll_mode) {
15477         case LPFC_THREADED_IRQ:
15478                 __lpfc_sli4_hba_process_cq(cq);
15479                 break;
15480         case LPFC_QUEUE_WORK:
15481         default:
15482                 if (is_kdump_kernel())
15483                         ret = queue_work(phba->wq, &cq->irqwork);
15484                 else
15485                         ret = queue_work_on(cq->chann, phba->wq, &cq->irqwork);
15486                 if (!ret)
15487                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15488                                         "0383 Cannot schedule queue work "
15489                                         "for CQ eqcqid=%d, cqid=%d on CPU %d\n",
15490                                         cqid, cq->queue_id,
15491                                         raw_smp_processor_id());
15492                 break;
15493         }
15494 }
15495
15496 /**
15497  * lpfc_sli4_dly_hba_process_cq - fast-path work handler when started by timer
15498  * @work: pointer to work element
15499  *
15500  * translates from the work handler and calls the fast-path handler.
15501  **/
15502 static void
15503 lpfc_sli4_dly_hba_process_cq(struct work_struct *work)
15504 {
15505         struct lpfc_queue *cq = container_of(to_delayed_work(work),
15506                                         struct lpfc_queue, sched_irqwork);
15507
15508         __lpfc_sli4_hba_process_cq(cq);
15509 }
15510
15511 /**
15512  * lpfc_sli4_hba_intr_handler - HBA interrupt handler to SLI-4 device
15513  * @irq: Interrupt number.
15514  * @dev_id: The device context pointer.
15515  *
15516  * This function is directly called from the PCI layer as an interrupt
15517  * service routine when device with SLI-4 interface spec is enabled with
15518  * MSI-X multi-message interrupt mode and there is a fast-path FCP IOCB
15519  * ring event in the HBA. However, when the device is enabled with either
15520  * MSI or Pin-IRQ interrupt mode, this function is called as part of the
15521  * device-level interrupt handler. When the PCI slot is in error recovery
15522  * or the HBA is undergoing initialization, the interrupt handler will not
15523  * process the interrupt. The SCSI FCP fast-path ring event are handled in
15524  * the intrrupt context. This function is called without any lock held.
15525  * It gets the hbalock to access and update SLI data structures. Note that,
15526  * the FCP EQ to FCP CQ are one-to-one map such that the FCP EQ index is
15527  * equal to that of FCP CQ index.
15528  *
15529  * The link attention and ELS ring attention events are handled
15530  * by the worker thread. The interrupt handler signals the worker thread
15531  * and returns for these events. This function is called without any lock
15532  * held. It gets the hbalock to access and update SLI data structures.
15533  *
15534  * This function returns IRQ_HANDLED when interrupt is handled, IRQ_WAKE_THREAD
15535  * when interrupt is scheduled to be handled from a threaded irq context, or
15536  * else returns IRQ_NONE.
15537  **/
15538 irqreturn_t
15539 lpfc_sli4_hba_intr_handler(int irq, void *dev_id)
15540 {
15541         struct lpfc_hba *phba;
15542         struct lpfc_hba_eq_hdl *hba_eq_hdl;
15543         struct lpfc_queue *fpeq;
15544         unsigned long iflag;
15545         int hba_eqidx;
15546         int ecount = 0;
15547         struct lpfc_eq_intr_info *eqi;
15548
15549         /* Get the driver's phba structure from the dev_id */
15550         hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
15551         phba = hba_eq_hdl->phba;
15552         hba_eqidx = hba_eq_hdl->idx;
15553
15554         if (unlikely(!phba))
15555                 return IRQ_NONE;
15556         if (unlikely(!phba->sli4_hba.hdwq))
15557                 return IRQ_NONE;
15558
15559         /* Get to the EQ struct associated with this vector */
15560         fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
15561         if (unlikely(!fpeq))
15562                 return IRQ_NONE;
15563
15564         /* Check device state for handling interrupt */
15565         if (unlikely(lpfc_intr_state_check(phba))) {
15566                 /* Check again for link_state with lock held */
15567                 spin_lock_irqsave(&phba->hbalock, iflag);
15568                 if (phba->link_state < LPFC_LINK_DOWN)
15569                         /* Flush, clear interrupt, and rearm the EQ */
15570                         lpfc_sli4_eqcq_flush(phba, fpeq);
15571                 spin_unlock_irqrestore(&phba->hbalock, iflag);
15572                 return IRQ_NONE;
15573         }
15574
15575         switch (fpeq->poll_mode) {
15576         case LPFC_THREADED_IRQ:
15577                 /* CGN mgmt is mutually exclusive from irq processing */
15578                 if (phba->cmf_active_mode == LPFC_CFG_OFF)
15579                         return IRQ_WAKE_THREAD;
15580                 fallthrough;
15581         case LPFC_QUEUE_WORK:
15582         default:
15583                 eqi = this_cpu_ptr(phba->sli4_hba.eq_info);
15584                 eqi->icnt++;
15585
15586                 fpeq->last_cpu = raw_smp_processor_id();
15587
15588                 if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
15589                     fpeq->q_flag & HBA_EQ_DELAY_CHK &&
15590                     phba->cfg_auto_imax &&
15591                     fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
15592                     phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
15593                         lpfc_sli4_mod_hba_eq_delay(phba, fpeq,
15594                                                    LPFC_MAX_AUTO_EQ_DELAY);
15595
15596                 /* process and rearm the EQ */
15597                 ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
15598                                               LPFC_QUEUE_WORK);
15599
15600                 if (unlikely(ecount == 0)) {
15601                         fpeq->EQ_no_entry++;
15602                         if (phba->intr_type == MSIX)
15603                                 /* MSI-X treated interrupt served as no EQ share INT */
15604                                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
15605                                                 "0358 MSI-X interrupt with no EQE\n");
15606                         else
15607                                 /* Non MSI-X treated on interrupt as EQ share INT */
15608                                 return IRQ_NONE;
15609                 }
15610         }
15611
15612         return IRQ_HANDLED;
15613 } /* lpfc_sli4_hba_intr_handler */
15614
15615 /**
15616  * lpfc_sli4_intr_handler - Device-level interrupt handler for SLI-4 device
15617  * @irq: Interrupt number.
15618  * @dev_id: The device context pointer.
15619  *
15620  * This function is the device-level interrupt handler to device with SLI-4
15621  * interface spec, called from the PCI layer when either MSI or Pin-IRQ
15622  * interrupt mode is enabled and there is an event in the HBA which requires
15623  * driver attention. This function invokes the slow-path interrupt attention
15624  * handling function and fast-path interrupt attention handling function in
15625  * turn to process the relevant HBA attention events. This function is called
15626  * without any lock held. It gets the hbalock to access and update SLI data
15627  * structures.
15628  *
15629  * This function returns IRQ_HANDLED when interrupt is handled, else it
15630  * returns IRQ_NONE.
15631  **/
15632 irqreturn_t
15633 lpfc_sli4_intr_handler(int irq, void *dev_id)
15634 {
15635         struct lpfc_hba  *phba;
15636         irqreturn_t hba_irq_rc;
15637         bool hba_handled = false;
15638         int qidx;
15639
15640         /* Get the driver's phba structure from the dev_id */
15641         phba = (struct lpfc_hba *)dev_id;
15642
15643         if (unlikely(!phba))
15644                 return IRQ_NONE;
15645
15646         /*
15647          * Invoke fast-path host attention interrupt handling as appropriate.
15648          */
15649         for (qidx = 0; qidx < phba->cfg_irq_chann; qidx++) {
15650                 hba_irq_rc = lpfc_sli4_hba_intr_handler(irq,
15651                                         &phba->sli4_hba.hba_eq_hdl[qidx]);
15652                 if (hba_irq_rc == IRQ_HANDLED)
15653                         hba_handled |= true;
15654         }
15655
15656         return (hba_handled == true) ? IRQ_HANDLED : IRQ_NONE;
15657 } /* lpfc_sli4_intr_handler */
15658
15659 void lpfc_sli4_poll_hbtimer(struct timer_list *t)
15660 {
15661         struct lpfc_hba *phba = from_timer(phba, t, cpuhp_poll_timer);
15662         struct lpfc_queue *eq;
15663
15664         rcu_read_lock();
15665
15666         list_for_each_entry_rcu(eq, &phba->poll_list, _poll_list)
15667                 lpfc_sli4_poll_eq(eq);
15668         if (!list_empty(&phba->poll_list))
15669                 mod_timer(&phba->cpuhp_poll_timer,
15670                           jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15671
15672         rcu_read_unlock();
15673 }
15674
15675 static inline void lpfc_sli4_add_to_poll_list(struct lpfc_queue *eq)
15676 {
15677         struct lpfc_hba *phba = eq->phba;
15678
15679         /* kickstart slowpath processing if needed */
15680         if (list_empty(&phba->poll_list))
15681                 mod_timer(&phba->cpuhp_poll_timer,
15682                           jiffies + msecs_to_jiffies(LPFC_POLL_HB));
15683
15684         list_add_rcu(&eq->_poll_list, &phba->poll_list);
15685         synchronize_rcu();
15686 }
15687
15688 static inline void lpfc_sli4_remove_from_poll_list(struct lpfc_queue *eq)
15689 {
15690         struct lpfc_hba *phba = eq->phba;
15691
15692         /* Disable slowpath processing for this eq.  Kick start the eq
15693          * by RE-ARMING the eq's ASAP
15694          */
15695         list_del_rcu(&eq->_poll_list);
15696         synchronize_rcu();
15697
15698         if (list_empty(&phba->poll_list))
15699                 del_timer_sync(&phba->cpuhp_poll_timer);
15700 }
15701
15702 void lpfc_sli4_cleanup_poll_list(struct lpfc_hba *phba)
15703 {
15704         struct lpfc_queue *eq, *next;
15705
15706         list_for_each_entry_safe(eq, next, &phba->poll_list, _poll_list)
15707                 list_del(&eq->_poll_list);
15708
15709         INIT_LIST_HEAD(&phba->poll_list);
15710         synchronize_rcu();
15711 }
15712
15713 static inline void
15714 __lpfc_sli4_switch_eqmode(struct lpfc_queue *eq, uint8_t mode)
15715 {
15716         if (mode == eq->mode)
15717                 return;
15718         /*
15719          * currently this function is only called during a hotplug
15720          * event and the cpu on which this function is executing
15721          * is going offline.  By now the hotplug has instructed
15722          * the scheduler to remove this cpu from cpu active mask.
15723          * So we don't need to work about being put aside by the
15724          * scheduler for a high priority process.  Yes, the inte-
15725          * rrupts could come but they are known to retire ASAP.
15726          */
15727
15728         /* Disable polling in the fastpath */
15729         WRITE_ONCE(eq->mode, mode);
15730         /* flush out the store buffer */
15731         smp_wmb();
15732
15733         /*
15734          * Add this eq to the polling list and start polling. For
15735          * a grace period both interrupt handler and poller will
15736          * try to process the eq _but_ that's fine.  We have a
15737          * synchronization mechanism in place (queue_claimed) to
15738          * deal with it.  This is just a draining phase for int-
15739          * errupt handler (not eq's) as we have guranteed through
15740          * barrier that all the CPUs have seen the new CQ_POLLED
15741          * state. which will effectively disable the REARMING of
15742          * the EQ.  The whole idea is eq's die off eventually as
15743          * we are not rearming EQ's anymore.
15744          */
15745         mode ? lpfc_sli4_add_to_poll_list(eq) :
15746                lpfc_sli4_remove_from_poll_list(eq);
15747 }
15748
15749 void lpfc_sli4_start_polling(struct lpfc_queue *eq)
15750 {
15751         __lpfc_sli4_switch_eqmode(eq, LPFC_EQ_POLL);
15752 }
15753
15754 void lpfc_sli4_stop_polling(struct lpfc_queue *eq)
15755 {
15756         struct lpfc_hba *phba = eq->phba;
15757
15758         __lpfc_sli4_switch_eqmode(eq, LPFC_EQ_INTERRUPT);
15759
15760         /* Kick start for the pending io's in h/w.
15761          * Once we switch back to interrupt processing on a eq
15762          * the io path completion will only arm eq's when it
15763          * receives a completion.  But since eq's are in disa-
15764          * rmed state it doesn't receive a completion.  This
15765          * creates a deadlock scenaro.
15766          */
15767         phba->sli4_hba.sli4_write_eq_db(phba, eq, 0, LPFC_QUEUE_REARM);
15768 }
15769
15770 /**
15771  * lpfc_sli4_queue_free - free a queue structure and associated memory
15772  * @queue: The queue structure to free.
15773  *
15774  * This function frees a queue structure and the DMAable memory used for
15775  * the host resident queue. This function must be called after destroying the
15776  * queue on the HBA.
15777  **/
15778 void
15779 lpfc_sli4_queue_free(struct lpfc_queue *queue)
15780 {
15781         struct lpfc_dmabuf *dmabuf;
15782
15783         if (!queue)
15784                 return;
15785
15786         if (!list_empty(&queue->wq_list))
15787                 list_del(&queue->wq_list);
15788
15789         while (!list_empty(&queue->page_list)) {
15790                 list_remove_head(&queue->page_list, dmabuf, struct lpfc_dmabuf,
15791                                  list);
15792                 dma_free_coherent(&queue->phba->pcidev->dev, queue->page_size,
15793                                   dmabuf->virt, dmabuf->phys);
15794                 kfree(dmabuf);
15795         }
15796         if (queue->rqbp) {
15797                 lpfc_free_rq_buffer(queue->phba, queue);
15798                 kfree(queue->rqbp);
15799         }
15800
15801         if (!list_empty(&queue->cpu_list))
15802                 list_del(&queue->cpu_list);
15803
15804         kfree(queue);
15805         return;
15806 }
15807
15808 /**
15809  * lpfc_sli4_queue_alloc - Allocate and initialize a queue structure
15810  * @phba: The HBA that this queue is being created on.
15811  * @page_size: The size of a queue page
15812  * @entry_size: The size of each queue entry for this queue.
15813  * @entry_count: The number of entries that this queue will handle.
15814  * @cpu: The cpu that will primarily utilize this queue.
15815  *
15816  * This function allocates a queue structure and the DMAable memory used for
15817  * the host resident queue. This function must be called before creating the
15818  * queue on the HBA.
15819  **/
15820 struct lpfc_queue *
15821 lpfc_sli4_queue_alloc(struct lpfc_hba *phba, uint32_t page_size,
15822                       uint32_t entry_size, uint32_t entry_count, int cpu)
15823 {
15824         struct lpfc_queue *queue;
15825         struct lpfc_dmabuf *dmabuf;
15826         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
15827         uint16_t x, pgcnt;
15828
15829         if (!phba->sli4_hba.pc_sli4_params.supported)
15830                 hw_page_size = page_size;
15831
15832         pgcnt = ALIGN(entry_size * entry_count, hw_page_size) / hw_page_size;
15833
15834         /* If needed, Adjust page count to match the max the adapter supports */
15835         if (pgcnt > phba->sli4_hba.pc_sli4_params.wqpcnt)
15836                 pgcnt = phba->sli4_hba.pc_sli4_params.wqpcnt;
15837
15838         queue = kzalloc_node(sizeof(*queue) + (sizeof(void *) * pgcnt),
15839                              GFP_KERNEL, cpu_to_node(cpu));
15840         if (!queue)
15841                 return NULL;
15842
15843         INIT_LIST_HEAD(&queue->list);
15844         INIT_LIST_HEAD(&queue->_poll_list);
15845         INIT_LIST_HEAD(&queue->wq_list);
15846         INIT_LIST_HEAD(&queue->wqfull_list);
15847         INIT_LIST_HEAD(&queue->page_list);
15848         INIT_LIST_HEAD(&queue->child_list);
15849         INIT_LIST_HEAD(&queue->cpu_list);
15850
15851         /* Set queue parameters now.  If the system cannot provide memory
15852          * resources, the free routine needs to know what was allocated.
15853          */
15854         queue->page_count = pgcnt;
15855         queue->q_pgs = (void **)&queue[1];
15856         queue->entry_cnt_per_pg = hw_page_size / entry_size;
15857         queue->entry_size = entry_size;
15858         queue->entry_count = entry_count;
15859         queue->page_size = hw_page_size;
15860         queue->phba = phba;
15861
15862         for (x = 0; x < queue->page_count; x++) {
15863                 dmabuf = kzalloc_node(sizeof(*dmabuf), GFP_KERNEL,
15864                                       dev_to_node(&phba->pcidev->dev));
15865                 if (!dmabuf)
15866                         goto out_fail;
15867                 dmabuf->virt = dma_alloc_coherent(&phba->pcidev->dev,
15868                                                   hw_page_size, &dmabuf->phys,
15869                                                   GFP_KERNEL);
15870                 if (!dmabuf->virt) {
15871                         kfree(dmabuf);
15872                         goto out_fail;
15873                 }
15874                 dmabuf->buffer_tag = x;
15875                 list_add_tail(&dmabuf->list, &queue->page_list);
15876                 /* use lpfc_sli4_qe to index a paritcular entry in this page */
15877                 queue->q_pgs[x] = dmabuf->virt;
15878         }
15879         INIT_WORK(&queue->irqwork, lpfc_sli4_hba_process_cq);
15880         INIT_WORK(&queue->spwork, lpfc_sli4_sp_process_cq);
15881         INIT_DELAYED_WORK(&queue->sched_irqwork, lpfc_sli4_dly_hba_process_cq);
15882         INIT_DELAYED_WORK(&queue->sched_spwork, lpfc_sli4_dly_sp_process_cq);
15883
15884         /* notify_interval will be set during q creation */
15885
15886         return queue;
15887 out_fail:
15888         lpfc_sli4_queue_free(queue);
15889         return NULL;
15890 }
15891
15892 /**
15893  * lpfc_dual_chute_pci_bar_map - Map pci base address register to host memory
15894  * @phba: HBA structure that indicates port to create a queue on.
15895  * @pci_barset: PCI BAR set flag.
15896  *
15897  * This function shall perform iomap of the specified PCI BAR address to host
15898  * memory address if not already done so and return it. The returned host
15899  * memory address can be NULL.
15900  */
15901 static void __iomem *
15902 lpfc_dual_chute_pci_bar_map(struct lpfc_hba *phba, uint16_t pci_barset)
15903 {
15904         if (!phba->pcidev)
15905                 return NULL;
15906
15907         switch (pci_barset) {
15908         case WQ_PCI_BAR_0_AND_1:
15909                 return phba->pci_bar0_memmap_p;
15910         case WQ_PCI_BAR_2_AND_3:
15911                 return phba->pci_bar2_memmap_p;
15912         case WQ_PCI_BAR_4_AND_5:
15913                 return phba->pci_bar4_memmap_p;
15914         default:
15915                 break;
15916         }
15917         return NULL;
15918 }
15919
15920 /**
15921  * lpfc_modify_hba_eq_delay - Modify Delay Multiplier on EQs
15922  * @phba: HBA structure that EQs are on.
15923  * @startq: The starting EQ index to modify
15924  * @numq: The number of EQs (consecutive indexes) to modify
15925  * @usdelay: amount of delay
15926  *
15927  * This function revises the EQ delay on 1 or more EQs. The EQ delay
15928  * is set either by writing to a register (if supported by the SLI Port)
15929  * or by mailbox command. The mailbox command allows several EQs to be
15930  * updated at once.
15931  *
15932  * The @phba struct is used to send a mailbox command to HBA. The @startq
15933  * is used to get the starting EQ index to change. The @numq value is
15934  * used to specify how many consecutive EQ indexes, starting at EQ index,
15935  * are to be changed. This function is asynchronous and will wait for any
15936  * mailbox commands to finish before returning.
15937  *
15938  * On success this function will return a zero. If unable to allocate
15939  * enough memory this function will return -ENOMEM. If a mailbox command
15940  * fails this function will return -ENXIO. Note: on ENXIO, some EQs may
15941  * have had their delay multipler changed.
15942  **/
15943 void
15944 lpfc_modify_hba_eq_delay(struct lpfc_hba *phba, uint32_t startq,
15945                          uint32_t numq, uint32_t usdelay)
15946 {
15947         struct lpfc_mbx_modify_eq_delay *eq_delay;
15948         LPFC_MBOXQ_t *mbox;
15949         struct lpfc_queue *eq;
15950         int cnt = 0, rc, length;
15951         uint32_t shdr_status, shdr_add_status;
15952         uint32_t dmult;
15953         int qidx;
15954         union lpfc_sli4_cfg_shdr *shdr;
15955
15956         if (startq >= phba->cfg_irq_chann)
15957                 return;
15958
15959         if (usdelay > 0xFFFF) {
15960                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_FCP | LOG_NVME,
15961                                 "6429 usdelay %d too large. Scaled down to "
15962                                 "0xFFFF.\n", usdelay);
15963                 usdelay = 0xFFFF;
15964         }
15965
15966         /* set values by EQ_DELAY register if supported */
15967         if (phba->sli.sli_flag & LPFC_SLI_USE_EQDR) {
15968                 for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
15969                         eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
15970                         if (!eq)
15971                                 continue;
15972
15973                         lpfc_sli4_mod_hba_eq_delay(phba, eq, usdelay);
15974
15975                         if (++cnt >= numq)
15976                                 break;
15977                 }
15978                 return;
15979         }
15980
15981         /* Otherwise, set values by mailbox cmd */
15982
15983         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
15984         if (!mbox) {
15985                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
15986                                 "6428 Failed allocating mailbox cmd buffer."
15987                                 " EQ delay was not set.\n");
15988                 return;
15989         }
15990         length = (sizeof(struct lpfc_mbx_modify_eq_delay) -
15991                   sizeof(struct lpfc_sli4_cfg_mhdr));
15992         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
15993                          LPFC_MBOX_OPCODE_MODIFY_EQ_DELAY,
15994                          length, LPFC_SLI4_MBX_EMBED);
15995         eq_delay = &mbox->u.mqe.un.eq_delay;
15996
15997         /* Calculate delay multiper from maximum interrupt per second */
15998         dmult = (usdelay * LPFC_DMULT_CONST) / LPFC_SEC_TO_USEC;
15999         if (dmult)
16000                 dmult--;
16001         if (dmult > LPFC_DMULT_MAX)
16002                 dmult = LPFC_DMULT_MAX;
16003
16004         for (qidx = startq; qidx < phba->cfg_irq_chann; qidx++) {
16005                 eq = phba->sli4_hba.hba_eq_hdl[qidx].eq;
16006                 if (!eq)
16007                         continue;
16008                 eq->q_mode = usdelay;
16009                 eq_delay->u.request.eq[cnt].eq_id = eq->queue_id;
16010                 eq_delay->u.request.eq[cnt].phase = 0;
16011                 eq_delay->u.request.eq[cnt].delay_multi = dmult;
16012
16013                 if (++cnt >= numq)
16014                         break;
16015         }
16016         eq_delay->u.request.num_eq = cnt;
16017
16018         mbox->vport = phba->pport;
16019         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16020         mbox->ctx_ndlp = NULL;
16021         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16022         shdr = (union lpfc_sli4_cfg_shdr *) &eq_delay->header.cfg_shdr;
16023         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16024         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16025         if (shdr_status || shdr_add_status || rc) {
16026                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16027                                 "2512 MODIFY_EQ_DELAY mailbox failed with "
16028                                 "status x%x add_status x%x, mbx status x%x\n",
16029                                 shdr_status, shdr_add_status, rc);
16030         }
16031         mempool_free(mbox, phba->mbox_mem_pool);
16032         return;
16033 }
16034
16035 /**
16036  * lpfc_eq_create - Create an Event Queue on the HBA
16037  * @phba: HBA structure that indicates port to create a queue on.
16038  * @eq: The queue structure to use to create the event queue.
16039  * @imax: The maximum interrupt per second limit.
16040  *
16041  * This function creates an event queue, as detailed in @eq, on a port,
16042  * described by @phba by sending an EQ_CREATE mailbox command to the HBA.
16043  *
16044  * The @phba struct is used to send mailbox command to HBA. The @eq struct
16045  * is used to get the entry count and entry size that are necessary to
16046  * determine the number of pages to allocate and use for this queue. This
16047  * function will send the EQ_CREATE mailbox command to the HBA to setup the
16048  * event queue. This function is asynchronous and will wait for the mailbox
16049  * command to finish before continuing.
16050  *
16051  * On success this function will return a zero. If unable to allocate enough
16052  * memory this function will return -ENOMEM. If the queue create mailbox command
16053  * fails this function will return -ENXIO.
16054  **/
16055 int
16056 lpfc_eq_create(struct lpfc_hba *phba, struct lpfc_queue *eq, uint32_t imax)
16057 {
16058         struct lpfc_mbx_eq_create *eq_create;
16059         LPFC_MBOXQ_t *mbox;
16060         int rc, length, status = 0;
16061         struct lpfc_dmabuf *dmabuf;
16062         uint32_t shdr_status, shdr_add_status;
16063         union lpfc_sli4_cfg_shdr *shdr;
16064         uint16_t dmult;
16065         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16066
16067         /* sanity check on queue memory */
16068         if (!eq)
16069                 return -ENODEV;
16070         if (!phba->sli4_hba.pc_sli4_params.supported)
16071                 hw_page_size = SLI4_PAGE_SIZE;
16072
16073         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16074         if (!mbox)
16075                 return -ENOMEM;
16076         length = (sizeof(struct lpfc_mbx_eq_create) -
16077                   sizeof(struct lpfc_sli4_cfg_mhdr));
16078         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16079                          LPFC_MBOX_OPCODE_EQ_CREATE,
16080                          length, LPFC_SLI4_MBX_EMBED);
16081         eq_create = &mbox->u.mqe.un.eq_create;
16082         shdr = (union lpfc_sli4_cfg_shdr *) &eq_create->header.cfg_shdr;
16083         bf_set(lpfc_mbx_eq_create_num_pages, &eq_create->u.request,
16084                eq->page_count);
16085         bf_set(lpfc_eq_context_size, &eq_create->u.request.context,
16086                LPFC_EQE_SIZE);
16087         bf_set(lpfc_eq_context_valid, &eq_create->u.request.context, 1);
16088
16089         /* Use version 2 of CREATE_EQ if eqav is set */
16090         if (phba->sli4_hba.pc_sli4_params.eqav) {
16091                 bf_set(lpfc_mbox_hdr_version, &shdr->request,
16092                        LPFC_Q_CREATE_VERSION_2);
16093                 bf_set(lpfc_eq_context_autovalid, &eq_create->u.request.context,
16094                        phba->sli4_hba.pc_sli4_params.eqav);
16095         }
16096
16097         /* don't setup delay multiplier using EQ_CREATE */
16098         dmult = 0;
16099         bf_set(lpfc_eq_context_delay_multi, &eq_create->u.request.context,
16100                dmult);
16101         switch (eq->entry_count) {
16102         default:
16103                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16104                                 "0360 Unsupported EQ count. (%d)\n",
16105                                 eq->entry_count);
16106                 if (eq->entry_count < 256) {
16107                         status = -EINVAL;
16108                         goto out;
16109                 }
16110                 fallthrough;    /* otherwise default to smallest count */
16111         case 256:
16112                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16113                        LPFC_EQ_CNT_256);
16114                 break;
16115         case 512:
16116                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16117                        LPFC_EQ_CNT_512);
16118                 break;
16119         case 1024:
16120                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16121                        LPFC_EQ_CNT_1024);
16122                 break;
16123         case 2048:
16124                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16125                        LPFC_EQ_CNT_2048);
16126                 break;
16127         case 4096:
16128                 bf_set(lpfc_eq_context_count, &eq_create->u.request.context,
16129                        LPFC_EQ_CNT_4096);
16130                 break;
16131         }
16132         list_for_each_entry(dmabuf, &eq->page_list, list) {
16133                 memset(dmabuf->virt, 0, hw_page_size);
16134                 eq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16135                                         putPaddrLow(dmabuf->phys);
16136                 eq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16137                                         putPaddrHigh(dmabuf->phys);
16138         }
16139         mbox->vport = phba->pport;
16140         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
16141         mbox->ctx_buf = NULL;
16142         mbox->ctx_ndlp = NULL;
16143         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16144         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16145         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16146         if (shdr_status || shdr_add_status || rc) {
16147                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16148                                 "2500 EQ_CREATE mailbox failed with "
16149                                 "status x%x add_status x%x, mbx status x%x\n",
16150                                 shdr_status, shdr_add_status, rc);
16151                 status = -ENXIO;
16152         }
16153         eq->type = LPFC_EQ;
16154         eq->subtype = LPFC_NONE;
16155         eq->queue_id = bf_get(lpfc_mbx_eq_create_q_id, &eq_create->u.response);
16156         if (eq->queue_id == 0xFFFF)
16157                 status = -ENXIO;
16158         eq->host_index = 0;
16159         eq->notify_interval = LPFC_EQ_NOTIFY_INTRVL;
16160         eq->max_proc_limit = LPFC_EQ_MAX_PROC_LIMIT;
16161 out:
16162         mempool_free(mbox, phba->mbox_mem_pool);
16163         return status;
16164 }
16165
16166 /**
16167  * lpfc_sli4_hba_intr_handler_th - SLI4 HBA threaded interrupt handler
16168  * @irq: Interrupt number.
16169  * @dev_id: The device context pointer.
16170  *
16171  * This routine is a mirror of lpfc_sli4_hba_intr_handler, but executed within
16172  * threaded irq context.
16173  *
16174  * Returns
16175  * IRQ_HANDLED - interrupt is handled
16176  * IRQ_NONE - otherwise
16177  **/
16178 irqreturn_t lpfc_sli4_hba_intr_handler_th(int irq, void *dev_id)
16179 {
16180         struct lpfc_hba *phba;
16181         struct lpfc_hba_eq_hdl *hba_eq_hdl;
16182         struct lpfc_queue *fpeq;
16183         int ecount = 0;
16184         int hba_eqidx;
16185         struct lpfc_eq_intr_info *eqi;
16186
16187         /* Get the driver's phba structure from the dev_id */
16188         hba_eq_hdl = (struct lpfc_hba_eq_hdl *)dev_id;
16189         phba = hba_eq_hdl->phba;
16190         hba_eqidx = hba_eq_hdl->idx;
16191
16192         if (unlikely(!phba))
16193                 return IRQ_NONE;
16194         if (unlikely(!phba->sli4_hba.hdwq))
16195                 return IRQ_NONE;
16196
16197         /* Get to the EQ struct associated with this vector */
16198         fpeq = phba->sli4_hba.hba_eq_hdl[hba_eqidx].eq;
16199         if (unlikely(!fpeq))
16200                 return IRQ_NONE;
16201
16202         eqi = per_cpu_ptr(phba->sli4_hba.eq_info, raw_smp_processor_id());
16203         eqi->icnt++;
16204
16205         fpeq->last_cpu = raw_smp_processor_id();
16206
16207         if (eqi->icnt > LPFC_EQD_ISR_TRIGGER &&
16208             fpeq->q_flag & HBA_EQ_DELAY_CHK &&
16209             phba->cfg_auto_imax &&
16210             fpeq->q_mode != LPFC_MAX_AUTO_EQ_DELAY &&
16211             phba->sli.sli_flag & LPFC_SLI_USE_EQDR)
16212                 lpfc_sli4_mod_hba_eq_delay(phba, fpeq, LPFC_MAX_AUTO_EQ_DELAY);
16213
16214         /* process and rearm the EQ */
16215         ecount = lpfc_sli4_process_eq(phba, fpeq, LPFC_QUEUE_REARM,
16216                                       LPFC_THREADED_IRQ);
16217
16218         if (unlikely(ecount == 0)) {
16219                 fpeq->EQ_no_entry++;
16220                 if (phba->intr_type == MSIX)
16221                         /* MSI-X treated interrupt served as no EQ share INT */
16222                         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
16223                                         "3358 MSI-X interrupt with no EQE\n");
16224                 else
16225                         /* Non MSI-X treated on interrupt as EQ share INT */
16226                         return IRQ_NONE;
16227         }
16228         return IRQ_HANDLED;
16229 }
16230
16231 /**
16232  * lpfc_cq_create - Create a Completion Queue on the HBA
16233  * @phba: HBA structure that indicates port to create a queue on.
16234  * @cq: The queue structure to use to create the completion queue.
16235  * @eq: The event queue to bind this completion queue to.
16236  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16237  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16238  *
16239  * This function creates a completion queue, as detailed in @wq, on a port,
16240  * described by @phba by sending a CQ_CREATE mailbox command to the HBA.
16241  *
16242  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16243  * is used to get the entry count and entry size that are necessary to
16244  * determine the number of pages to allocate and use for this queue. The @eq
16245  * is used to indicate which event queue to bind this completion queue to. This
16246  * function will send the CQ_CREATE mailbox command to the HBA to setup the
16247  * completion queue. This function is asynchronous and will wait for the mailbox
16248  * command to finish before continuing.
16249  *
16250  * On success this function will return a zero. If unable to allocate enough
16251  * memory this function will return -ENOMEM. If the queue create mailbox command
16252  * fails this function will return -ENXIO.
16253  **/
16254 int
16255 lpfc_cq_create(struct lpfc_hba *phba, struct lpfc_queue *cq,
16256                struct lpfc_queue *eq, uint32_t type, uint32_t subtype)
16257 {
16258         struct lpfc_mbx_cq_create *cq_create;
16259         struct lpfc_dmabuf *dmabuf;
16260         LPFC_MBOXQ_t *mbox;
16261         int rc, length, status = 0;
16262         uint32_t shdr_status, shdr_add_status;
16263         union lpfc_sli4_cfg_shdr *shdr;
16264
16265         /* sanity check on queue memory */
16266         if (!cq || !eq)
16267                 return -ENODEV;
16268
16269         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16270         if (!mbox)
16271                 return -ENOMEM;
16272         length = (sizeof(struct lpfc_mbx_cq_create) -
16273                   sizeof(struct lpfc_sli4_cfg_mhdr));
16274         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16275                          LPFC_MBOX_OPCODE_CQ_CREATE,
16276                          length, LPFC_SLI4_MBX_EMBED);
16277         cq_create = &mbox->u.mqe.un.cq_create;
16278         shdr = (union lpfc_sli4_cfg_shdr *) &cq_create->header.cfg_shdr;
16279         bf_set(lpfc_mbx_cq_create_num_pages, &cq_create->u.request,
16280                     cq->page_count);
16281         bf_set(lpfc_cq_context_event, &cq_create->u.request.context, 1);
16282         bf_set(lpfc_cq_context_valid, &cq_create->u.request.context, 1);
16283         bf_set(lpfc_mbox_hdr_version, &shdr->request,
16284                phba->sli4_hba.pc_sli4_params.cqv);
16285         if (phba->sli4_hba.pc_sli4_params.cqv == LPFC_Q_CREATE_VERSION_2) {
16286                 bf_set(lpfc_mbx_cq_create_page_size, &cq_create->u.request,
16287                        (cq->page_size / SLI4_PAGE_SIZE));
16288                 bf_set(lpfc_cq_eq_id_2, &cq_create->u.request.context,
16289                        eq->queue_id);
16290                 bf_set(lpfc_cq_context_autovalid, &cq_create->u.request.context,
16291                        phba->sli4_hba.pc_sli4_params.cqav);
16292         } else {
16293                 bf_set(lpfc_cq_eq_id, &cq_create->u.request.context,
16294                        eq->queue_id);
16295         }
16296         switch (cq->entry_count) {
16297         case 2048:
16298         case 4096:
16299                 if (phba->sli4_hba.pc_sli4_params.cqv ==
16300                     LPFC_Q_CREATE_VERSION_2) {
16301                         cq_create->u.request.context.lpfc_cq_context_count =
16302                                 cq->entry_count;
16303                         bf_set(lpfc_cq_context_count,
16304                                &cq_create->u.request.context,
16305                                LPFC_CQ_CNT_WORD7);
16306                         break;
16307                 }
16308                 fallthrough;
16309         default:
16310                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16311                                 "0361 Unsupported CQ count: "
16312                                 "entry cnt %d sz %d pg cnt %d\n",
16313                                 cq->entry_count, cq->entry_size,
16314                                 cq->page_count);
16315                 if (cq->entry_count < 256) {
16316                         status = -EINVAL;
16317                         goto out;
16318                 }
16319                 fallthrough;    /* otherwise default to smallest count */
16320         case 256:
16321                 bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16322                        LPFC_CQ_CNT_256);
16323                 break;
16324         case 512:
16325                 bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16326                        LPFC_CQ_CNT_512);
16327                 break;
16328         case 1024:
16329                 bf_set(lpfc_cq_context_count, &cq_create->u.request.context,
16330                        LPFC_CQ_CNT_1024);
16331                 break;
16332         }
16333         list_for_each_entry(dmabuf, &cq->page_list, list) {
16334                 memset(dmabuf->virt, 0, cq->page_size);
16335                 cq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16336                                         putPaddrLow(dmabuf->phys);
16337                 cq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16338                                         putPaddrHigh(dmabuf->phys);
16339         }
16340         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16341
16342         /* The IOCTL status is embedded in the mailbox subheader. */
16343         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16344         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16345         if (shdr_status || shdr_add_status || rc) {
16346                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16347                                 "2501 CQ_CREATE mailbox failed with "
16348                                 "status x%x add_status x%x, mbx status x%x\n",
16349                                 shdr_status, shdr_add_status, rc);
16350                 status = -ENXIO;
16351                 goto out;
16352         }
16353         cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16354         if (cq->queue_id == 0xFFFF) {
16355                 status = -ENXIO;
16356                 goto out;
16357         }
16358         /* link the cq onto the parent eq child list */
16359         list_add_tail(&cq->list, &eq->child_list);
16360         /* Set up completion queue's type and subtype */
16361         cq->type = type;
16362         cq->subtype = subtype;
16363         cq->queue_id = bf_get(lpfc_mbx_cq_create_q_id, &cq_create->u.response);
16364         cq->assoc_qid = eq->queue_id;
16365         cq->assoc_qp = eq;
16366         cq->host_index = 0;
16367         cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16368         cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit, cq->entry_count);
16369
16370         if (cq->queue_id > phba->sli4_hba.cq_max)
16371                 phba->sli4_hba.cq_max = cq->queue_id;
16372 out:
16373         mempool_free(mbox, phba->mbox_mem_pool);
16374         return status;
16375 }
16376
16377 /**
16378  * lpfc_cq_create_set - Create a set of Completion Queues on the HBA for MRQ
16379  * @phba: HBA structure that indicates port to create a queue on.
16380  * @cqp: The queue structure array to use to create the completion queues.
16381  * @hdwq: The hardware queue array  with the EQ to bind completion queues to.
16382  * @type: Type of queue (EQ, GCQ, MCQ, WCQ, etc).
16383  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
16384  *
16385  * This function creates a set of  completion queue, s to support MRQ
16386  * as detailed in @cqp, on a port,
16387  * described by @phba by sending a CREATE_CQ_SET mailbox command to the HBA.
16388  *
16389  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16390  * is used to get the entry count and entry size that are necessary to
16391  * determine the number of pages to allocate and use for this queue. The @eq
16392  * is used to indicate which event queue to bind this completion queue to. This
16393  * function will send the CREATE_CQ_SET mailbox command to the HBA to setup the
16394  * completion queue. This function is asynchronous and will wait for the mailbox
16395  * command to finish before continuing.
16396  *
16397  * On success this function will return a zero. If unable to allocate enough
16398  * memory this function will return -ENOMEM. If the queue create mailbox command
16399  * fails this function will return -ENXIO.
16400  **/
16401 int
16402 lpfc_cq_create_set(struct lpfc_hba *phba, struct lpfc_queue **cqp,
16403                    struct lpfc_sli4_hdw_queue *hdwq, uint32_t type,
16404                    uint32_t subtype)
16405 {
16406         struct lpfc_queue *cq;
16407         struct lpfc_queue *eq;
16408         struct lpfc_mbx_cq_create_set *cq_set;
16409         struct lpfc_dmabuf *dmabuf;
16410         LPFC_MBOXQ_t *mbox;
16411         int rc, length, alloclen, status = 0;
16412         int cnt, idx, numcq, page_idx = 0;
16413         uint32_t shdr_status, shdr_add_status;
16414         union lpfc_sli4_cfg_shdr *shdr;
16415         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16416
16417         /* sanity check on queue memory */
16418         numcq = phba->cfg_nvmet_mrq;
16419         if (!cqp || !hdwq || !numcq)
16420                 return -ENODEV;
16421
16422         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16423         if (!mbox)
16424                 return -ENOMEM;
16425
16426         length = sizeof(struct lpfc_mbx_cq_create_set);
16427         length += ((numcq * cqp[0]->page_count) *
16428                    sizeof(struct dma_address));
16429         alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16430                         LPFC_MBOX_OPCODE_FCOE_CQ_CREATE_SET, length,
16431                         LPFC_SLI4_MBX_NEMBED);
16432         if (alloclen < length) {
16433                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16434                                 "3098 Allocated DMA memory size (%d) is "
16435                                 "less than the requested DMA memory size "
16436                                 "(%d)\n", alloclen, length);
16437                 status = -ENOMEM;
16438                 goto out;
16439         }
16440         cq_set = mbox->sge_array->addr[0];
16441         shdr = (union lpfc_sli4_cfg_shdr *)&cq_set->cfg_shdr;
16442         bf_set(lpfc_mbox_hdr_version, &shdr->request, 0);
16443
16444         for (idx = 0; idx < numcq; idx++) {
16445                 cq = cqp[idx];
16446                 eq = hdwq[idx].hba_eq;
16447                 if (!cq || !eq) {
16448                         status = -ENOMEM;
16449                         goto out;
16450                 }
16451                 if (!phba->sli4_hba.pc_sli4_params.supported)
16452                         hw_page_size = cq->page_size;
16453
16454                 switch (idx) {
16455                 case 0:
16456                         bf_set(lpfc_mbx_cq_create_set_page_size,
16457                                &cq_set->u.request,
16458                                (hw_page_size / SLI4_PAGE_SIZE));
16459                         bf_set(lpfc_mbx_cq_create_set_num_pages,
16460                                &cq_set->u.request, cq->page_count);
16461                         bf_set(lpfc_mbx_cq_create_set_evt,
16462                                &cq_set->u.request, 1);
16463                         bf_set(lpfc_mbx_cq_create_set_valid,
16464                                &cq_set->u.request, 1);
16465                         bf_set(lpfc_mbx_cq_create_set_cqe_size,
16466                                &cq_set->u.request, 0);
16467                         bf_set(lpfc_mbx_cq_create_set_num_cq,
16468                                &cq_set->u.request, numcq);
16469                         bf_set(lpfc_mbx_cq_create_set_autovalid,
16470                                &cq_set->u.request,
16471                                phba->sli4_hba.pc_sli4_params.cqav);
16472                         switch (cq->entry_count) {
16473                         case 2048:
16474                         case 4096:
16475                                 if (phba->sli4_hba.pc_sli4_params.cqv ==
16476                                     LPFC_Q_CREATE_VERSION_2) {
16477                                         bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16478                                                &cq_set->u.request,
16479                                                 cq->entry_count);
16480                                         bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16481                                                &cq_set->u.request,
16482                                                LPFC_CQ_CNT_WORD7);
16483                                         break;
16484                                 }
16485                                 fallthrough;
16486                         default:
16487                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16488                                                 "3118 Bad CQ count. (%d)\n",
16489                                                 cq->entry_count);
16490                                 if (cq->entry_count < 256) {
16491                                         status = -EINVAL;
16492                                         goto out;
16493                                 }
16494                                 fallthrough;    /* otherwise default to smallest */
16495                         case 256:
16496                                 bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16497                                        &cq_set->u.request, LPFC_CQ_CNT_256);
16498                                 break;
16499                         case 512:
16500                                 bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16501                                        &cq_set->u.request, LPFC_CQ_CNT_512);
16502                                 break;
16503                         case 1024:
16504                                 bf_set(lpfc_mbx_cq_create_set_cqe_cnt,
16505                                        &cq_set->u.request, LPFC_CQ_CNT_1024);
16506                                 break;
16507                         }
16508                         bf_set(lpfc_mbx_cq_create_set_eq_id0,
16509                                &cq_set->u.request, eq->queue_id);
16510                         break;
16511                 case 1:
16512                         bf_set(lpfc_mbx_cq_create_set_eq_id1,
16513                                &cq_set->u.request, eq->queue_id);
16514                         break;
16515                 case 2:
16516                         bf_set(lpfc_mbx_cq_create_set_eq_id2,
16517                                &cq_set->u.request, eq->queue_id);
16518                         break;
16519                 case 3:
16520                         bf_set(lpfc_mbx_cq_create_set_eq_id3,
16521                                &cq_set->u.request, eq->queue_id);
16522                         break;
16523                 case 4:
16524                         bf_set(lpfc_mbx_cq_create_set_eq_id4,
16525                                &cq_set->u.request, eq->queue_id);
16526                         break;
16527                 case 5:
16528                         bf_set(lpfc_mbx_cq_create_set_eq_id5,
16529                                &cq_set->u.request, eq->queue_id);
16530                         break;
16531                 case 6:
16532                         bf_set(lpfc_mbx_cq_create_set_eq_id6,
16533                                &cq_set->u.request, eq->queue_id);
16534                         break;
16535                 case 7:
16536                         bf_set(lpfc_mbx_cq_create_set_eq_id7,
16537                                &cq_set->u.request, eq->queue_id);
16538                         break;
16539                 case 8:
16540                         bf_set(lpfc_mbx_cq_create_set_eq_id8,
16541                                &cq_set->u.request, eq->queue_id);
16542                         break;
16543                 case 9:
16544                         bf_set(lpfc_mbx_cq_create_set_eq_id9,
16545                                &cq_set->u.request, eq->queue_id);
16546                         break;
16547                 case 10:
16548                         bf_set(lpfc_mbx_cq_create_set_eq_id10,
16549                                &cq_set->u.request, eq->queue_id);
16550                         break;
16551                 case 11:
16552                         bf_set(lpfc_mbx_cq_create_set_eq_id11,
16553                                &cq_set->u.request, eq->queue_id);
16554                         break;
16555                 case 12:
16556                         bf_set(lpfc_mbx_cq_create_set_eq_id12,
16557                                &cq_set->u.request, eq->queue_id);
16558                         break;
16559                 case 13:
16560                         bf_set(lpfc_mbx_cq_create_set_eq_id13,
16561                                &cq_set->u.request, eq->queue_id);
16562                         break;
16563                 case 14:
16564                         bf_set(lpfc_mbx_cq_create_set_eq_id14,
16565                                &cq_set->u.request, eq->queue_id);
16566                         break;
16567                 case 15:
16568                         bf_set(lpfc_mbx_cq_create_set_eq_id15,
16569                                &cq_set->u.request, eq->queue_id);
16570                         break;
16571                 }
16572
16573                 /* link the cq onto the parent eq child list */
16574                 list_add_tail(&cq->list, &eq->child_list);
16575                 /* Set up completion queue's type and subtype */
16576                 cq->type = type;
16577                 cq->subtype = subtype;
16578                 cq->assoc_qid = eq->queue_id;
16579                 cq->assoc_qp = eq;
16580                 cq->host_index = 0;
16581                 cq->notify_interval = LPFC_CQ_NOTIFY_INTRVL;
16582                 cq->max_proc_limit = min(phba->cfg_cq_max_proc_limit,
16583                                          cq->entry_count);
16584                 cq->chann = idx;
16585
16586                 rc = 0;
16587                 list_for_each_entry(dmabuf, &cq->page_list, list) {
16588                         memset(dmabuf->virt, 0, hw_page_size);
16589                         cnt = page_idx + dmabuf->buffer_tag;
16590                         cq_set->u.request.page[cnt].addr_lo =
16591                                         putPaddrLow(dmabuf->phys);
16592                         cq_set->u.request.page[cnt].addr_hi =
16593                                         putPaddrHigh(dmabuf->phys);
16594                         rc++;
16595                 }
16596                 page_idx += rc;
16597         }
16598
16599         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16600
16601         /* The IOCTL status is embedded in the mailbox subheader. */
16602         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16603         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16604         if (shdr_status || shdr_add_status || rc) {
16605                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16606                                 "3119 CQ_CREATE_SET mailbox failed with "
16607                                 "status x%x add_status x%x, mbx status x%x\n",
16608                                 shdr_status, shdr_add_status, rc);
16609                 status = -ENXIO;
16610                 goto out;
16611         }
16612         rc = bf_get(lpfc_mbx_cq_create_set_base_id, &cq_set->u.response);
16613         if (rc == 0xFFFF) {
16614                 status = -ENXIO;
16615                 goto out;
16616         }
16617
16618         for (idx = 0; idx < numcq; idx++) {
16619                 cq = cqp[idx];
16620                 cq->queue_id = rc + idx;
16621                 if (cq->queue_id > phba->sli4_hba.cq_max)
16622                         phba->sli4_hba.cq_max = cq->queue_id;
16623         }
16624
16625 out:
16626         lpfc_sli4_mbox_cmd_free(phba, mbox);
16627         return status;
16628 }
16629
16630 /**
16631  * lpfc_mq_create_fb_init - Send MCC_CREATE without async events registration
16632  * @phba: HBA structure that indicates port to create a queue on.
16633  * @mq: The queue structure to use to create the mailbox queue.
16634  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
16635  * @cq: The completion queue to associate with this cq.
16636  *
16637  * This function provides failback (fb) functionality when the
16638  * mq_create_ext fails on older FW generations.  It's purpose is identical
16639  * to mq_create_ext otherwise.
16640  *
16641  * This routine cannot fail as all attributes were previously accessed and
16642  * initialized in mq_create_ext.
16643  **/
16644 static void
16645 lpfc_mq_create_fb_init(struct lpfc_hba *phba, struct lpfc_queue *mq,
16646                        LPFC_MBOXQ_t *mbox, struct lpfc_queue *cq)
16647 {
16648         struct lpfc_mbx_mq_create *mq_create;
16649         struct lpfc_dmabuf *dmabuf;
16650         int length;
16651
16652         length = (sizeof(struct lpfc_mbx_mq_create) -
16653                   sizeof(struct lpfc_sli4_cfg_mhdr));
16654         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16655                          LPFC_MBOX_OPCODE_MQ_CREATE,
16656                          length, LPFC_SLI4_MBX_EMBED);
16657         mq_create = &mbox->u.mqe.un.mq_create;
16658         bf_set(lpfc_mbx_mq_create_num_pages, &mq_create->u.request,
16659                mq->page_count);
16660         bf_set(lpfc_mq_context_cq_id, &mq_create->u.request.context,
16661                cq->queue_id);
16662         bf_set(lpfc_mq_context_valid, &mq_create->u.request.context, 1);
16663         switch (mq->entry_count) {
16664         case 16:
16665                 bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16666                        LPFC_MQ_RING_SIZE_16);
16667                 break;
16668         case 32:
16669                 bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16670                        LPFC_MQ_RING_SIZE_32);
16671                 break;
16672         case 64:
16673                 bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16674                        LPFC_MQ_RING_SIZE_64);
16675                 break;
16676         case 128:
16677                 bf_set(lpfc_mq_context_ring_size, &mq_create->u.request.context,
16678                        LPFC_MQ_RING_SIZE_128);
16679                 break;
16680         }
16681         list_for_each_entry(dmabuf, &mq->page_list, list) {
16682                 mq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
16683                         putPaddrLow(dmabuf->phys);
16684                 mq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
16685                         putPaddrHigh(dmabuf->phys);
16686         }
16687 }
16688
16689 /**
16690  * lpfc_mq_create - Create a mailbox Queue on the HBA
16691  * @phba: HBA structure that indicates port to create a queue on.
16692  * @mq: The queue structure to use to create the mailbox queue.
16693  * @cq: The completion queue to associate with this cq.
16694  * @subtype: The queue's subtype.
16695  *
16696  * This function creates a mailbox queue, as detailed in @mq, on a port,
16697  * described by @phba by sending a MQ_CREATE mailbox command to the HBA.
16698  *
16699  * The @phba struct is used to send mailbox command to HBA. The @cq struct
16700  * is used to get the entry count and entry size that are necessary to
16701  * determine the number of pages to allocate and use for this queue. This
16702  * function will send the MQ_CREATE mailbox command to the HBA to setup the
16703  * mailbox queue. This function is asynchronous and will wait for the mailbox
16704  * command to finish before continuing.
16705  *
16706  * On success this function will return a zero. If unable to allocate enough
16707  * memory this function will return -ENOMEM. If the queue create mailbox command
16708  * fails this function will return -ENXIO.
16709  **/
16710 int32_t
16711 lpfc_mq_create(struct lpfc_hba *phba, struct lpfc_queue *mq,
16712                struct lpfc_queue *cq, uint32_t subtype)
16713 {
16714         struct lpfc_mbx_mq_create *mq_create;
16715         struct lpfc_mbx_mq_create_ext *mq_create_ext;
16716         struct lpfc_dmabuf *dmabuf;
16717         LPFC_MBOXQ_t *mbox;
16718         int rc, length, status = 0;
16719         uint32_t shdr_status, shdr_add_status;
16720         union lpfc_sli4_cfg_shdr *shdr;
16721         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16722
16723         /* sanity check on queue memory */
16724         if (!mq || !cq)
16725                 return -ENODEV;
16726         if (!phba->sli4_hba.pc_sli4_params.supported)
16727                 hw_page_size = SLI4_PAGE_SIZE;
16728
16729         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16730         if (!mbox)
16731                 return -ENOMEM;
16732         length = (sizeof(struct lpfc_mbx_mq_create_ext) -
16733                   sizeof(struct lpfc_sli4_cfg_mhdr));
16734         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
16735                          LPFC_MBOX_OPCODE_MQ_CREATE_EXT,
16736                          length, LPFC_SLI4_MBX_EMBED);
16737
16738         mq_create_ext = &mbox->u.mqe.un.mq_create_ext;
16739         shdr = (union lpfc_sli4_cfg_shdr *) &mq_create_ext->header.cfg_shdr;
16740         bf_set(lpfc_mbx_mq_create_ext_num_pages,
16741                &mq_create_ext->u.request, mq->page_count);
16742         bf_set(lpfc_mbx_mq_create_ext_async_evt_link,
16743                &mq_create_ext->u.request, 1);
16744         bf_set(lpfc_mbx_mq_create_ext_async_evt_fip,
16745                &mq_create_ext->u.request, 1);
16746         bf_set(lpfc_mbx_mq_create_ext_async_evt_group5,
16747                &mq_create_ext->u.request, 1);
16748         bf_set(lpfc_mbx_mq_create_ext_async_evt_fc,
16749                &mq_create_ext->u.request, 1);
16750         bf_set(lpfc_mbx_mq_create_ext_async_evt_sli,
16751                &mq_create_ext->u.request, 1);
16752         bf_set(lpfc_mq_context_valid, &mq_create_ext->u.request.context, 1);
16753         bf_set(lpfc_mbox_hdr_version, &shdr->request,
16754                phba->sli4_hba.pc_sli4_params.mqv);
16755         if (phba->sli4_hba.pc_sli4_params.mqv == LPFC_Q_CREATE_VERSION_1)
16756                 bf_set(lpfc_mbx_mq_create_ext_cq_id, &mq_create_ext->u.request,
16757                        cq->queue_id);
16758         else
16759                 bf_set(lpfc_mq_context_cq_id, &mq_create_ext->u.request.context,
16760                        cq->queue_id);
16761         switch (mq->entry_count) {
16762         default:
16763                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16764                                 "0362 Unsupported MQ count. (%d)\n",
16765                                 mq->entry_count);
16766                 if (mq->entry_count < 16) {
16767                         status = -EINVAL;
16768                         goto out;
16769                 }
16770                 fallthrough;    /* otherwise default to smallest count */
16771         case 16:
16772                 bf_set(lpfc_mq_context_ring_size,
16773                        &mq_create_ext->u.request.context,
16774                        LPFC_MQ_RING_SIZE_16);
16775                 break;
16776         case 32:
16777                 bf_set(lpfc_mq_context_ring_size,
16778                        &mq_create_ext->u.request.context,
16779                        LPFC_MQ_RING_SIZE_32);
16780                 break;
16781         case 64:
16782                 bf_set(lpfc_mq_context_ring_size,
16783                        &mq_create_ext->u.request.context,
16784                        LPFC_MQ_RING_SIZE_64);
16785                 break;
16786         case 128:
16787                 bf_set(lpfc_mq_context_ring_size,
16788                        &mq_create_ext->u.request.context,
16789                        LPFC_MQ_RING_SIZE_128);
16790                 break;
16791         }
16792         list_for_each_entry(dmabuf, &mq->page_list, list) {
16793                 memset(dmabuf->virt, 0, hw_page_size);
16794                 mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_lo =
16795                                         putPaddrLow(dmabuf->phys);
16796                 mq_create_ext->u.request.page[dmabuf->buffer_tag].addr_hi =
16797                                         putPaddrHigh(dmabuf->phys);
16798         }
16799         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16800         mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16801                               &mq_create_ext->u.response);
16802         if (rc != MBX_SUCCESS) {
16803                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
16804                                 "2795 MQ_CREATE_EXT failed with "
16805                                 "status x%x. Failback to MQ_CREATE.\n",
16806                                 rc);
16807                 lpfc_mq_create_fb_init(phba, mq, mbox, cq);
16808                 mq_create = &mbox->u.mqe.un.mq_create;
16809                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16810                 shdr = (union lpfc_sli4_cfg_shdr *) &mq_create->header.cfg_shdr;
16811                 mq->queue_id = bf_get(lpfc_mbx_mq_create_q_id,
16812                                       &mq_create->u.response);
16813         }
16814
16815         /* The IOCTL status is embedded in the mailbox subheader. */
16816         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16817         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16818         if (shdr_status || shdr_add_status || rc) {
16819                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16820                                 "2502 MQ_CREATE mailbox failed with "
16821                                 "status x%x add_status x%x, mbx status x%x\n",
16822                                 shdr_status, shdr_add_status, rc);
16823                 status = -ENXIO;
16824                 goto out;
16825         }
16826         if (mq->queue_id == 0xFFFF) {
16827                 status = -ENXIO;
16828                 goto out;
16829         }
16830         mq->type = LPFC_MQ;
16831         mq->assoc_qid = cq->queue_id;
16832         mq->subtype = subtype;
16833         mq->host_index = 0;
16834         mq->hba_index = 0;
16835
16836         /* link the mq onto the parent cq child list */
16837         list_add_tail(&mq->list, &cq->child_list);
16838 out:
16839         mempool_free(mbox, phba->mbox_mem_pool);
16840         return status;
16841 }
16842
16843 /**
16844  * lpfc_wq_create - Create a Work Queue on the HBA
16845  * @phba: HBA structure that indicates port to create a queue on.
16846  * @wq: The queue structure to use to create the work queue.
16847  * @cq: The completion queue to bind this work queue to.
16848  * @subtype: The subtype of the work queue indicating its functionality.
16849  *
16850  * This function creates a work queue, as detailed in @wq, on a port, described
16851  * by @phba by sending a WQ_CREATE mailbox command to the HBA.
16852  *
16853  * The @phba struct is used to send mailbox command to HBA. The @wq struct
16854  * is used to get the entry count and entry size that are necessary to
16855  * determine the number of pages to allocate and use for this queue. The @cq
16856  * is used to indicate which completion queue to bind this work queue to. This
16857  * function will send the WQ_CREATE mailbox command to the HBA to setup the
16858  * work queue. This function is asynchronous and will wait for the mailbox
16859  * command to finish before continuing.
16860  *
16861  * On success this function will return a zero. If unable to allocate enough
16862  * memory this function will return -ENOMEM. If the queue create mailbox command
16863  * fails this function will return -ENXIO.
16864  **/
16865 int
16866 lpfc_wq_create(struct lpfc_hba *phba, struct lpfc_queue *wq,
16867                struct lpfc_queue *cq, uint32_t subtype)
16868 {
16869         struct lpfc_mbx_wq_create *wq_create;
16870         struct lpfc_dmabuf *dmabuf;
16871         LPFC_MBOXQ_t *mbox;
16872         int rc, length, status = 0;
16873         uint32_t shdr_status, shdr_add_status;
16874         union lpfc_sli4_cfg_shdr *shdr;
16875         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
16876         struct dma_address *page;
16877         void __iomem *bar_memmap_p;
16878         uint32_t db_offset;
16879         uint16_t pci_barset;
16880         uint8_t dpp_barset;
16881         uint32_t dpp_offset;
16882         uint8_t wq_create_version;
16883 #ifdef CONFIG_X86
16884         unsigned long pg_addr;
16885 #endif
16886
16887         /* sanity check on queue memory */
16888         if (!wq || !cq)
16889                 return -ENODEV;
16890         if (!phba->sli4_hba.pc_sli4_params.supported)
16891                 hw_page_size = wq->page_size;
16892
16893         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
16894         if (!mbox)
16895                 return -ENOMEM;
16896         length = (sizeof(struct lpfc_mbx_wq_create) -
16897                   sizeof(struct lpfc_sli4_cfg_mhdr));
16898         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
16899                          LPFC_MBOX_OPCODE_FCOE_WQ_CREATE,
16900                          length, LPFC_SLI4_MBX_EMBED);
16901         wq_create = &mbox->u.mqe.un.wq_create;
16902         shdr = (union lpfc_sli4_cfg_shdr *) &wq_create->header.cfg_shdr;
16903         bf_set(lpfc_mbx_wq_create_num_pages, &wq_create->u.request,
16904                     wq->page_count);
16905         bf_set(lpfc_mbx_wq_create_cq_id, &wq_create->u.request,
16906                     cq->queue_id);
16907
16908         /* wqv is the earliest version supported, NOT the latest */
16909         bf_set(lpfc_mbox_hdr_version, &shdr->request,
16910                phba->sli4_hba.pc_sli4_params.wqv);
16911
16912         if ((phba->sli4_hba.pc_sli4_params.wqsize & LPFC_WQ_SZ128_SUPPORT) ||
16913             (wq->page_size > SLI4_PAGE_SIZE))
16914                 wq_create_version = LPFC_Q_CREATE_VERSION_1;
16915         else
16916                 wq_create_version = LPFC_Q_CREATE_VERSION_0;
16917
16918         switch (wq_create_version) {
16919         case LPFC_Q_CREATE_VERSION_1:
16920                 bf_set(lpfc_mbx_wq_create_wqe_count, &wq_create->u.request_1,
16921                        wq->entry_count);
16922                 bf_set(lpfc_mbox_hdr_version, &shdr->request,
16923                        LPFC_Q_CREATE_VERSION_1);
16924
16925                 switch (wq->entry_size) {
16926                 default:
16927                 case 64:
16928                         bf_set(lpfc_mbx_wq_create_wqe_size,
16929                                &wq_create->u.request_1,
16930                                LPFC_WQ_WQE_SIZE_64);
16931                         break;
16932                 case 128:
16933                         bf_set(lpfc_mbx_wq_create_wqe_size,
16934                                &wq_create->u.request_1,
16935                                LPFC_WQ_WQE_SIZE_128);
16936                         break;
16937                 }
16938                 /* Request DPP by default */
16939                 bf_set(lpfc_mbx_wq_create_dpp_req, &wq_create->u.request_1, 1);
16940                 bf_set(lpfc_mbx_wq_create_page_size,
16941                        &wq_create->u.request_1,
16942                        (wq->page_size / SLI4_PAGE_SIZE));
16943                 page = wq_create->u.request_1.page;
16944                 break;
16945         default:
16946                 page = wq_create->u.request.page;
16947                 break;
16948         }
16949
16950         list_for_each_entry(dmabuf, &wq->page_list, list) {
16951                 memset(dmabuf->virt, 0, hw_page_size);
16952                 page[dmabuf->buffer_tag].addr_lo = putPaddrLow(dmabuf->phys);
16953                 page[dmabuf->buffer_tag].addr_hi = putPaddrHigh(dmabuf->phys);
16954         }
16955
16956         if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
16957                 bf_set(lpfc_mbx_wq_create_dua, &wq_create->u.request, 1);
16958
16959         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
16960         /* The IOCTL status is embedded in the mailbox subheader. */
16961         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
16962         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
16963         if (shdr_status || shdr_add_status || rc) {
16964                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16965                                 "2503 WQ_CREATE mailbox failed with "
16966                                 "status x%x add_status x%x, mbx status x%x\n",
16967                                 shdr_status, shdr_add_status, rc);
16968                 status = -ENXIO;
16969                 goto out;
16970         }
16971
16972         if (wq_create_version == LPFC_Q_CREATE_VERSION_0)
16973                 wq->queue_id = bf_get(lpfc_mbx_wq_create_q_id,
16974                                         &wq_create->u.response);
16975         else
16976                 wq->queue_id = bf_get(lpfc_mbx_wq_create_v1_q_id,
16977                                         &wq_create->u.response_1);
16978
16979         if (wq->queue_id == 0xFFFF) {
16980                 status = -ENXIO;
16981                 goto out;
16982         }
16983
16984         wq->db_format = LPFC_DB_LIST_FORMAT;
16985         if (wq_create_version == LPFC_Q_CREATE_VERSION_0) {
16986                 if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
16987                         wq->db_format = bf_get(lpfc_mbx_wq_create_db_format,
16988                                                &wq_create->u.response);
16989                         if ((wq->db_format != LPFC_DB_LIST_FORMAT) &&
16990                             (wq->db_format != LPFC_DB_RING_FORMAT)) {
16991                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
16992                                                 "3265 WQ[%d] doorbell format "
16993                                                 "not supported: x%x\n",
16994                                                 wq->queue_id, wq->db_format);
16995                                 status = -EINVAL;
16996                                 goto out;
16997                         }
16998                         pci_barset = bf_get(lpfc_mbx_wq_create_bar_set,
16999                                             &wq_create->u.response);
17000                         bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17001                                                                    pci_barset);
17002                         if (!bar_memmap_p) {
17003                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17004                                                 "3263 WQ[%d] failed to memmap "
17005                                                 "pci barset:x%x\n",
17006                                                 wq->queue_id, pci_barset);
17007                                 status = -ENOMEM;
17008                                 goto out;
17009                         }
17010                         db_offset = wq_create->u.response.doorbell_offset;
17011                         if ((db_offset != LPFC_ULP0_WQ_DOORBELL) &&
17012                             (db_offset != LPFC_ULP1_WQ_DOORBELL)) {
17013                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17014                                                 "3252 WQ[%d] doorbell offset "
17015                                                 "not supported: x%x\n",
17016                                                 wq->queue_id, db_offset);
17017                                 status = -EINVAL;
17018                                 goto out;
17019                         }
17020                         wq->db_regaddr = bar_memmap_p + db_offset;
17021                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17022                                         "3264 WQ[%d]: barset:x%x, offset:x%x, "
17023                                         "format:x%x\n", wq->queue_id,
17024                                         pci_barset, db_offset, wq->db_format);
17025                 } else
17026                         wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17027         } else {
17028                 /* Check if DPP was honored by the firmware */
17029                 wq->dpp_enable = bf_get(lpfc_mbx_wq_create_dpp_rsp,
17030                                     &wq_create->u.response_1);
17031                 if (wq->dpp_enable) {
17032                         pci_barset = bf_get(lpfc_mbx_wq_create_v1_bar_set,
17033                                             &wq_create->u.response_1);
17034                         bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17035                                                                    pci_barset);
17036                         if (!bar_memmap_p) {
17037                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17038                                                 "3267 WQ[%d] failed to memmap "
17039                                                 "pci barset:x%x\n",
17040                                                 wq->queue_id, pci_barset);
17041                                 status = -ENOMEM;
17042                                 goto out;
17043                         }
17044                         db_offset = wq_create->u.response_1.doorbell_offset;
17045                         wq->db_regaddr = bar_memmap_p + db_offset;
17046                         wq->dpp_id = bf_get(lpfc_mbx_wq_create_dpp_id,
17047                                             &wq_create->u.response_1);
17048                         dpp_barset = bf_get(lpfc_mbx_wq_create_dpp_bar,
17049                                             &wq_create->u.response_1);
17050                         bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba,
17051                                                                    dpp_barset);
17052                         if (!bar_memmap_p) {
17053                                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17054                                                 "3268 WQ[%d] failed to memmap "
17055                                                 "pci barset:x%x\n",
17056                                                 wq->queue_id, dpp_barset);
17057                                 status = -ENOMEM;
17058                                 goto out;
17059                         }
17060                         dpp_offset = wq_create->u.response_1.dpp_offset;
17061                         wq->dpp_regaddr = bar_memmap_p + dpp_offset;
17062                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17063                                         "3271 WQ[%d]: barset:x%x, offset:x%x, "
17064                                         "dpp_id:x%x dpp_barset:x%x "
17065                                         "dpp_offset:x%x\n",
17066                                         wq->queue_id, pci_barset, db_offset,
17067                                         wq->dpp_id, dpp_barset, dpp_offset);
17068
17069 #ifdef CONFIG_X86
17070                         /* Enable combined writes for DPP aperture */
17071                         pg_addr = (unsigned long)(wq->dpp_regaddr) & PAGE_MASK;
17072                         rc = set_memory_wc(pg_addr, 1);
17073                         if (rc) {
17074                                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT,
17075                                         "3272 Cannot setup Combined "
17076                                         "Write on WQ[%d] - disable DPP\n",
17077                                         wq->queue_id);
17078                                 phba->cfg_enable_dpp = 0;
17079                         }
17080 #else
17081                         phba->cfg_enable_dpp = 0;
17082 #endif
17083                 } else
17084                         wq->db_regaddr = phba->sli4_hba.WQDBregaddr;
17085         }
17086         wq->pring = kzalloc(sizeof(struct lpfc_sli_ring), GFP_KERNEL);
17087         if (wq->pring == NULL) {
17088                 status = -ENOMEM;
17089                 goto out;
17090         }
17091         wq->type = LPFC_WQ;
17092         wq->assoc_qid = cq->queue_id;
17093         wq->subtype = subtype;
17094         wq->host_index = 0;
17095         wq->hba_index = 0;
17096         wq->notify_interval = LPFC_WQ_NOTIFY_INTRVL;
17097
17098         /* link the wq onto the parent cq child list */
17099         list_add_tail(&wq->list, &cq->child_list);
17100 out:
17101         mempool_free(mbox, phba->mbox_mem_pool);
17102         return status;
17103 }
17104
17105 /**
17106  * lpfc_rq_create - Create a Receive Queue on the HBA
17107  * @phba: HBA structure that indicates port to create a queue on.
17108  * @hrq: The queue structure to use to create the header receive queue.
17109  * @drq: The queue structure to use to create the data receive queue.
17110  * @cq: The completion queue to bind this work queue to.
17111  * @subtype: The subtype of the work queue indicating its functionality.
17112  *
17113  * This function creates a receive buffer queue pair , as detailed in @hrq and
17114  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17115  * to the HBA.
17116  *
17117  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17118  * struct is used to get the entry count that is necessary to determine the
17119  * number of pages to use for this queue. The @cq is used to indicate which
17120  * completion queue to bind received buffers that are posted to these queues to.
17121  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17122  * receive queue pair. This function is asynchronous and will wait for the
17123  * mailbox command to finish before continuing.
17124  *
17125  * On success this function will return a zero. If unable to allocate enough
17126  * memory this function will return -ENOMEM. If the queue create mailbox command
17127  * fails this function will return -ENXIO.
17128  **/
17129 int
17130 lpfc_rq_create(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17131                struct lpfc_queue *drq, struct lpfc_queue *cq, uint32_t subtype)
17132 {
17133         struct lpfc_mbx_rq_create *rq_create;
17134         struct lpfc_dmabuf *dmabuf;
17135         LPFC_MBOXQ_t *mbox;
17136         int rc, length, status = 0;
17137         uint32_t shdr_status, shdr_add_status;
17138         union lpfc_sli4_cfg_shdr *shdr;
17139         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17140         void __iomem *bar_memmap_p;
17141         uint32_t db_offset;
17142         uint16_t pci_barset;
17143
17144         /* sanity check on queue memory */
17145         if (!hrq || !drq || !cq)
17146                 return -ENODEV;
17147         if (!phba->sli4_hba.pc_sli4_params.supported)
17148                 hw_page_size = SLI4_PAGE_SIZE;
17149
17150         if (hrq->entry_count != drq->entry_count)
17151                 return -EINVAL;
17152         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17153         if (!mbox)
17154                 return -ENOMEM;
17155         length = (sizeof(struct lpfc_mbx_rq_create) -
17156                   sizeof(struct lpfc_sli4_cfg_mhdr));
17157         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17158                          LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17159                          length, LPFC_SLI4_MBX_EMBED);
17160         rq_create = &mbox->u.mqe.un.rq_create;
17161         shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17162         bf_set(lpfc_mbox_hdr_version, &shdr->request,
17163                phba->sli4_hba.pc_sli4_params.rqv);
17164         if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17165                 bf_set(lpfc_rq_context_rqe_count_1,
17166                        &rq_create->u.request.context,
17167                        hrq->entry_count);
17168                 rq_create->u.request.context.buffer_size = LPFC_HDR_BUF_SIZE;
17169                 bf_set(lpfc_rq_context_rqe_size,
17170                        &rq_create->u.request.context,
17171                        LPFC_RQE_SIZE_8);
17172                 bf_set(lpfc_rq_context_page_size,
17173                        &rq_create->u.request.context,
17174                        LPFC_RQ_PAGE_SIZE_4096);
17175         } else {
17176                 switch (hrq->entry_count) {
17177                 default:
17178                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17179                                         "2535 Unsupported RQ count. (%d)\n",
17180                                         hrq->entry_count);
17181                         if (hrq->entry_count < 512) {
17182                                 status = -EINVAL;
17183                                 goto out;
17184                         }
17185                         fallthrough;    /* otherwise default to smallest count */
17186                 case 512:
17187                         bf_set(lpfc_rq_context_rqe_count,
17188                                &rq_create->u.request.context,
17189                                LPFC_RQ_RING_SIZE_512);
17190                         break;
17191                 case 1024:
17192                         bf_set(lpfc_rq_context_rqe_count,
17193                                &rq_create->u.request.context,
17194                                LPFC_RQ_RING_SIZE_1024);
17195                         break;
17196                 case 2048:
17197                         bf_set(lpfc_rq_context_rqe_count,
17198                                &rq_create->u.request.context,
17199                                LPFC_RQ_RING_SIZE_2048);
17200                         break;
17201                 case 4096:
17202                         bf_set(lpfc_rq_context_rqe_count,
17203                                &rq_create->u.request.context,
17204                                LPFC_RQ_RING_SIZE_4096);
17205                         break;
17206                 }
17207                 bf_set(lpfc_rq_context_buf_size, &rq_create->u.request.context,
17208                        LPFC_HDR_BUF_SIZE);
17209         }
17210         bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17211                cq->queue_id);
17212         bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17213                hrq->page_count);
17214         list_for_each_entry(dmabuf, &hrq->page_list, list) {
17215                 memset(dmabuf->virt, 0, hw_page_size);
17216                 rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17217                                         putPaddrLow(dmabuf->phys);
17218                 rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17219                                         putPaddrHigh(dmabuf->phys);
17220         }
17221         if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17222                 bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17223
17224         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17225         /* The IOCTL status is embedded in the mailbox subheader. */
17226         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17227         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17228         if (shdr_status || shdr_add_status || rc) {
17229                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17230                                 "2504 RQ_CREATE mailbox failed with "
17231                                 "status x%x add_status x%x, mbx status x%x\n",
17232                                 shdr_status, shdr_add_status, rc);
17233                 status = -ENXIO;
17234                 goto out;
17235         }
17236         hrq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17237         if (hrq->queue_id == 0xFFFF) {
17238                 status = -ENXIO;
17239                 goto out;
17240         }
17241
17242         if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE) {
17243                 hrq->db_format = bf_get(lpfc_mbx_rq_create_db_format,
17244                                         &rq_create->u.response);
17245                 if ((hrq->db_format != LPFC_DB_LIST_FORMAT) &&
17246                     (hrq->db_format != LPFC_DB_RING_FORMAT)) {
17247                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17248                                         "3262 RQ [%d] doorbell format not "
17249                                         "supported: x%x\n", hrq->queue_id,
17250                                         hrq->db_format);
17251                         status = -EINVAL;
17252                         goto out;
17253                 }
17254
17255                 pci_barset = bf_get(lpfc_mbx_rq_create_bar_set,
17256                                     &rq_create->u.response);
17257                 bar_memmap_p = lpfc_dual_chute_pci_bar_map(phba, pci_barset);
17258                 if (!bar_memmap_p) {
17259                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17260                                         "3269 RQ[%d] failed to memmap pci "
17261                                         "barset:x%x\n", hrq->queue_id,
17262                                         pci_barset);
17263                         status = -ENOMEM;
17264                         goto out;
17265                 }
17266
17267                 db_offset = rq_create->u.response.doorbell_offset;
17268                 if ((db_offset != LPFC_ULP0_RQ_DOORBELL) &&
17269                     (db_offset != LPFC_ULP1_RQ_DOORBELL)) {
17270                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17271                                         "3270 RQ[%d] doorbell offset not "
17272                                         "supported: x%x\n", hrq->queue_id,
17273                                         db_offset);
17274                         status = -EINVAL;
17275                         goto out;
17276                 }
17277                 hrq->db_regaddr = bar_memmap_p + db_offset;
17278                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
17279                                 "3266 RQ[qid:%d]: barset:x%x, offset:x%x, "
17280                                 "format:x%x\n", hrq->queue_id, pci_barset,
17281                                 db_offset, hrq->db_format);
17282         } else {
17283                 hrq->db_format = LPFC_DB_RING_FORMAT;
17284                 hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17285         }
17286         hrq->type = LPFC_HRQ;
17287         hrq->assoc_qid = cq->queue_id;
17288         hrq->subtype = subtype;
17289         hrq->host_index = 0;
17290         hrq->hba_index = 0;
17291         hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17292
17293         /* now create the data queue */
17294         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17295                          LPFC_MBOX_OPCODE_FCOE_RQ_CREATE,
17296                          length, LPFC_SLI4_MBX_EMBED);
17297         bf_set(lpfc_mbox_hdr_version, &shdr->request,
17298                phba->sli4_hba.pc_sli4_params.rqv);
17299         if (phba->sli4_hba.pc_sli4_params.rqv == LPFC_Q_CREATE_VERSION_1) {
17300                 bf_set(lpfc_rq_context_rqe_count_1,
17301                        &rq_create->u.request.context, hrq->entry_count);
17302                 if (subtype == LPFC_NVMET)
17303                         rq_create->u.request.context.buffer_size =
17304                                 LPFC_NVMET_DATA_BUF_SIZE;
17305                 else
17306                         rq_create->u.request.context.buffer_size =
17307                                 LPFC_DATA_BUF_SIZE;
17308                 bf_set(lpfc_rq_context_rqe_size, &rq_create->u.request.context,
17309                        LPFC_RQE_SIZE_8);
17310                 bf_set(lpfc_rq_context_page_size, &rq_create->u.request.context,
17311                        (PAGE_SIZE/SLI4_PAGE_SIZE));
17312         } else {
17313                 switch (drq->entry_count) {
17314                 default:
17315                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17316                                         "2536 Unsupported RQ count. (%d)\n",
17317                                         drq->entry_count);
17318                         if (drq->entry_count < 512) {
17319                                 status = -EINVAL;
17320                                 goto out;
17321                         }
17322                         fallthrough;    /* otherwise default to smallest count */
17323                 case 512:
17324                         bf_set(lpfc_rq_context_rqe_count,
17325                                &rq_create->u.request.context,
17326                                LPFC_RQ_RING_SIZE_512);
17327                         break;
17328                 case 1024:
17329                         bf_set(lpfc_rq_context_rqe_count,
17330                                &rq_create->u.request.context,
17331                                LPFC_RQ_RING_SIZE_1024);
17332                         break;
17333                 case 2048:
17334                         bf_set(lpfc_rq_context_rqe_count,
17335                                &rq_create->u.request.context,
17336                                LPFC_RQ_RING_SIZE_2048);
17337                         break;
17338                 case 4096:
17339                         bf_set(lpfc_rq_context_rqe_count,
17340                                &rq_create->u.request.context,
17341                                LPFC_RQ_RING_SIZE_4096);
17342                         break;
17343                 }
17344                 if (subtype == LPFC_NVMET)
17345                         bf_set(lpfc_rq_context_buf_size,
17346                                &rq_create->u.request.context,
17347                                LPFC_NVMET_DATA_BUF_SIZE);
17348                 else
17349                         bf_set(lpfc_rq_context_buf_size,
17350                                &rq_create->u.request.context,
17351                                LPFC_DATA_BUF_SIZE);
17352         }
17353         bf_set(lpfc_rq_context_cq_id, &rq_create->u.request.context,
17354                cq->queue_id);
17355         bf_set(lpfc_mbx_rq_create_num_pages, &rq_create->u.request,
17356                drq->page_count);
17357         list_for_each_entry(dmabuf, &drq->page_list, list) {
17358                 rq_create->u.request.page[dmabuf->buffer_tag].addr_lo =
17359                                         putPaddrLow(dmabuf->phys);
17360                 rq_create->u.request.page[dmabuf->buffer_tag].addr_hi =
17361                                         putPaddrHigh(dmabuf->phys);
17362         }
17363         if (phba->sli4_hba.fw_func_mode & LPFC_DUA_MODE)
17364                 bf_set(lpfc_mbx_rq_create_dua, &rq_create->u.request, 1);
17365         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17366         /* The IOCTL status is embedded in the mailbox subheader. */
17367         shdr = (union lpfc_sli4_cfg_shdr *) &rq_create->header.cfg_shdr;
17368         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17369         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17370         if (shdr_status || shdr_add_status || rc) {
17371                 status = -ENXIO;
17372                 goto out;
17373         }
17374         drq->queue_id = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17375         if (drq->queue_id == 0xFFFF) {
17376                 status = -ENXIO;
17377                 goto out;
17378         }
17379         drq->type = LPFC_DRQ;
17380         drq->assoc_qid = cq->queue_id;
17381         drq->subtype = subtype;
17382         drq->host_index = 0;
17383         drq->hba_index = 0;
17384         drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17385
17386         /* link the header and data RQs onto the parent cq child list */
17387         list_add_tail(&hrq->list, &cq->child_list);
17388         list_add_tail(&drq->list, &cq->child_list);
17389
17390 out:
17391         mempool_free(mbox, phba->mbox_mem_pool);
17392         return status;
17393 }
17394
17395 /**
17396  * lpfc_mrq_create - Create MRQ Receive Queues on the HBA
17397  * @phba: HBA structure that indicates port to create a queue on.
17398  * @hrqp: The queue structure array to use to create the header receive queues.
17399  * @drqp: The queue structure array to use to create the data receive queues.
17400  * @cqp: The completion queue array to bind these receive queues to.
17401  * @subtype: Functional purpose of the queue (MBOX, IO, ELS, NVMET, etc).
17402  *
17403  * This function creates a receive buffer queue pair , as detailed in @hrq and
17404  * @drq, on a port, described by @phba by sending a RQ_CREATE mailbox command
17405  * to the HBA.
17406  *
17407  * The @phba struct is used to send mailbox command to HBA. The @drq and @hrq
17408  * struct is used to get the entry count that is necessary to determine the
17409  * number of pages to use for this queue. The @cq is used to indicate which
17410  * completion queue to bind received buffers that are posted to these queues to.
17411  * This function will send the RQ_CREATE mailbox command to the HBA to setup the
17412  * receive queue pair. This function is asynchronous and will wait for the
17413  * mailbox command to finish before continuing.
17414  *
17415  * On success this function will return a zero. If unable to allocate enough
17416  * memory this function will return -ENOMEM. If the queue create mailbox command
17417  * fails this function will return -ENXIO.
17418  **/
17419 int
17420 lpfc_mrq_create(struct lpfc_hba *phba, struct lpfc_queue **hrqp,
17421                 struct lpfc_queue **drqp, struct lpfc_queue **cqp,
17422                 uint32_t subtype)
17423 {
17424         struct lpfc_queue *hrq, *drq, *cq;
17425         struct lpfc_mbx_rq_create_v2 *rq_create;
17426         struct lpfc_dmabuf *dmabuf;
17427         LPFC_MBOXQ_t *mbox;
17428         int rc, length, alloclen, status = 0;
17429         int cnt, idx, numrq, page_idx = 0;
17430         uint32_t shdr_status, shdr_add_status;
17431         union lpfc_sli4_cfg_shdr *shdr;
17432         uint32_t hw_page_size = phba->sli4_hba.pc_sli4_params.if_page_sz;
17433
17434         numrq = phba->cfg_nvmet_mrq;
17435         /* sanity check on array memory */
17436         if (!hrqp || !drqp || !cqp || !numrq)
17437                 return -ENODEV;
17438         if (!phba->sli4_hba.pc_sli4_params.supported)
17439                 hw_page_size = SLI4_PAGE_SIZE;
17440
17441         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17442         if (!mbox)
17443                 return -ENOMEM;
17444
17445         length = sizeof(struct lpfc_mbx_rq_create_v2);
17446         length += ((2 * numrq * hrqp[0]->page_count) *
17447                    sizeof(struct dma_address));
17448
17449         alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17450                                     LPFC_MBOX_OPCODE_FCOE_RQ_CREATE, length,
17451                                     LPFC_SLI4_MBX_NEMBED);
17452         if (alloclen < length) {
17453                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17454                                 "3099 Allocated DMA memory size (%d) is "
17455                                 "less than the requested DMA memory size "
17456                                 "(%d)\n", alloclen, length);
17457                 status = -ENOMEM;
17458                 goto out;
17459         }
17460
17461
17462
17463         rq_create = mbox->sge_array->addr[0];
17464         shdr = (union lpfc_sli4_cfg_shdr *)&rq_create->cfg_shdr;
17465
17466         bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_2);
17467         cnt = 0;
17468
17469         for (idx = 0; idx < numrq; idx++) {
17470                 hrq = hrqp[idx];
17471                 drq = drqp[idx];
17472                 cq  = cqp[idx];
17473
17474                 /* sanity check on queue memory */
17475                 if (!hrq || !drq || !cq) {
17476                         status = -ENODEV;
17477                         goto out;
17478                 }
17479
17480                 if (hrq->entry_count != drq->entry_count) {
17481                         status = -EINVAL;
17482                         goto out;
17483                 }
17484
17485                 if (idx == 0) {
17486                         bf_set(lpfc_mbx_rq_create_num_pages,
17487                                &rq_create->u.request,
17488                                hrq->page_count);
17489                         bf_set(lpfc_mbx_rq_create_rq_cnt,
17490                                &rq_create->u.request, (numrq * 2));
17491                         bf_set(lpfc_mbx_rq_create_dnb, &rq_create->u.request,
17492                                1);
17493                         bf_set(lpfc_rq_context_base_cq,
17494                                &rq_create->u.request.context,
17495                                cq->queue_id);
17496                         bf_set(lpfc_rq_context_data_size,
17497                                &rq_create->u.request.context,
17498                                LPFC_NVMET_DATA_BUF_SIZE);
17499                         bf_set(lpfc_rq_context_hdr_size,
17500                                &rq_create->u.request.context,
17501                                LPFC_HDR_BUF_SIZE);
17502                         bf_set(lpfc_rq_context_rqe_count_1,
17503                                &rq_create->u.request.context,
17504                                hrq->entry_count);
17505                         bf_set(lpfc_rq_context_rqe_size,
17506                                &rq_create->u.request.context,
17507                                LPFC_RQE_SIZE_8);
17508                         bf_set(lpfc_rq_context_page_size,
17509                                &rq_create->u.request.context,
17510                                (PAGE_SIZE/SLI4_PAGE_SIZE));
17511                 }
17512                 rc = 0;
17513                 list_for_each_entry(dmabuf, &hrq->page_list, list) {
17514                         memset(dmabuf->virt, 0, hw_page_size);
17515                         cnt = page_idx + dmabuf->buffer_tag;
17516                         rq_create->u.request.page[cnt].addr_lo =
17517                                         putPaddrLow(dmabuf->phys);
17518                         rq_create->u.request.page[cnt].addr_hi =
17519                                         putPaddrHigh(dmabuf->phys);
17520                         rc++;
17521                 }
17522                 page_idx += rc;
17523
17524                 rc = 0;
17525                 list_for_each_entry(dmabuf, &drq->page_list, list) {
17526                         memset(dmabuf->virt, 0, hw_page_size);
17527                         cnt = page_idx + dmabuf->buffer_tag;
17528                         rq_create->u.request.page[cnt].addr_lo =
17529                                         putPaddrLow(dmabuf->phys);
17530                         rq_create->u.request.page[cnt].addr_hi =
17531                                         putPaddrHigh(dmabuf->phys);
17532                         rc++;
17533                 }
17534                 page_idx += rc;
17535
17536                 hrq->db_format = LPFC_DB_RING_FORMAT;
17537                 hrq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17538                 hrq->type = LPFC_HRQ;
17539                 hrq->assoc_qid = cq->queue_id;
17540                 hrq->subtype = subtype;
17541                 hrq->host_index = 0;
17542                 hrq->hba_index = 0;
17543                 hrq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17544
17545                 drq->db_format = LPFC_DB_RING_FORMAT;
17546                 drq->db_regaddr = phba->sli4_hba.RQDBregaddr;
17547                 drq->type = LPFC_DRQ;
17548                 drq->assoc_qid = cq->queue_id;
17549                 drq->subtype = subtype;
17550                 drq->host_index = 0;
17551                 drq->hba_index = 0;
17552                 drq->notify_interval = LPFC_RQ_NOTIFY_INTRVL;
17553
17554                 list_add_tail(&hrq->list, &cq->child_list);
17555                 list_add_tail(&drq->list, &cq->child_list);
17556         }
17557
17558         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17559         /* The IOCTL status is embedded in the mailbox subheader. */
17560         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17561         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17562         if (shdr_status || shdr_add_status || rc) {
17563                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17564                                 "3120 RQ_CREATE mailbox failed with "
17565                                 "status x%x add_status x%x, mbx status x%x\n",
17566                                 shdr_status, shdr_add_status, rc);
17567                 status = -ENXIO;
17568                 goto out;
17569         }
17570         rc = bf_get(lpfc_mbx_rq_create_q_id, &rq_create->u.response);
17571         if (rc == 0xFFFF) {
17572                 status = -ENXIO;
17573                 goto out;
17574         }
17575
17576         /* Initialize all RQs with associated queue id */
17577         for (idx = 0; idx < numrq; idx++) {
17578                 hrq = hrqp[idx];
17579                 hrq->queue_id = rc + (2 * idx);
17580                 drq = drqp[idx];
17581                 drq->queue_id = rc + (2 * idx) + 1;
17582         }
17583
17584 out:
17585         lpfc_sli4_mbox_cmd_free(phba, mbox);
17586         return status;
17587 }
17588
17589 /**
17590  * lpfc_eq_destroy - Destroy an event Queue on the HBA
17591  * @phba: HBA structure that indicates port to destroy a queue on.
17592  * @eq: The queue structure associated with the queue to destroy.
17593  *
17594  * This function destroys a queue, as detailed in @eq by sending an mailbox
17595  * command, specific to the type of queue, to the HBA.
17596  *
17597  * The @eq struct is used to get the queue ID of the queue to destroy.
17598  *
17599  * On success this function will return a zero. If the queue destroy mailbox
17600  * command fails this function will return -ENXIO.
17601  **/
17602 int
17603 lpfc_eq_destroy(struct lpfc_hba *phba, struct lpfc_queue *eq)
17604 {
17605         LPFC_MBOXQ_t *mbox;
17606         int rc, length, status = 0;
17607         uint32_t shdr_status, shdr_add_status;
17608         union lpfc_sli4_cfg_shdr *shdr;
17609
17610         /* sanity check on queue memory */
17611         if (!eq)
17612                 return -ENODEV;
17613
17614         if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17615                 goto list_remove;
17616
17617         mbox = mempool_alloc(eq->phba->mbox_mem_pool, GFP_KERNEL);
17618         if (!mbox)
17619                 return -ENOMEM;
17620         length = (sizeof(struct lpfc_mbx_eq_destroy) -
17621                   sizeof(struct lpfc_sli4_cfg_mhdr));
17622         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17623                          LPFC_MBOX_OPCODE_EQ_DESTROY,
17624                          length, LPFC_SLI4_MBX_EMBED);
17625         bf_set(lpfc_mbx_eq_destroy_q_id, &mbox->u.mqe.un.eq_destroy.u.request,
17626                eq->queue_id);
17627         mbox->vport = eq->phba->pport;
17628         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17629
17630         rc = lpfc_sli_issue_mbox(eq->phba, mbox, MBX_POLL);
17631         /* The IOCTL status is embedded in the mailbox subheader. */
17632         shdr = (union lpfc_sli4_cfg_shdr *)
17633                 &mbox->u.mqe.un.eq_destroy.header.cfg_shdr;
17634         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17635         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17636         if (shdr_status || shdr_add_status || rc) {
17637                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17638                                 "2505 EQ_DESTROY mailbox failed with "
17639                                 "status x%x add_status x%x, mbx status x%x\n",
17640                                 shdr_status, shdr_add_status, rc);
17641                 status = -ENXIO;
17642         }
17643         mempool_free(mbox, eq->phba->mbox_mem_pool);
17644
17645 list_remove:
17646         /* Remove eq from any list */
17647         list_del_init(&eq->list);
17648
17649         return status;
17650 }
17651
17652 /**
17653  * lpfc_cq_destroy - Destroy a Completion Queue on the HBA
17654  * @phba: HBA structure that indicates port to destroy a queue on.
17655  * @cq: The queue structure associated with the queue to destroy.
17656  *
17657  * This function destroys a queue, as detailed in @cq by sending an mailbox
17658  * command, specific to the type of queue, to the HBA.
17659  *
17660  * The @cq struct is used to get the queue ID of the queue to destroy.
17661  *
17662  * On success this function will return a zero. If the queue destroy mailbox
17663  * command fails this function will return -ENXIO.
17664  **/
17665 int
17666 lpfc_cq_destroy(struct lpfc_hba *phba, struct lpfc_queue *cq)
17667 {
17668         LPFC_MBOXQ_t *mbox;
17669         int rc, length, status = 0;
17670         uint32_t shdr_status, shdr_add_status;
17671         union lpfc_sli4_cfg_shdr *shdr;
17672
17673         /* sanity check on queue memory */
17674         if (!cq)
17675                 return -ENODEV;
17676
17677         if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17678                 goto list_remove;
17679
17680         mbox = mempool_alloc(cq->phba->mbox_mem_pool, GFP_KERNEL);
17681         if (!mbox)
17682                 return -ENOMEM;
17683         length = (sizeof(struct lpfc_mbx_cq_destroy) -
17684                   sizeof(struct lpfc_sli4_cfg_mhdr));
17685         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17686                          LPFC_MBOX_OPCODE_CQ_DESTROY,
17687                          length, LPFC_SLI4_MBX_EMBED);
17688         bf_set(lpfc_mbx_cq_destroy_q_id, &mbox->u.mqe.un.cq_destroy.u.request,
17689                cq->queue_id);
17690         mbox->vport = cq->phba->pport;
17691         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17692         rc = lpfc_sli_issue_mbox(cq->phba, mbox, MBX_POLL);
17693         /* The IOCTL status is embedded in the mailbox subheader. */
17694         shdr = (union lpfc_sli4_cfg_shdr *)
17695                 &mbox->u.mqe.un.wq_create.header.cfg_shdr;
17696         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17697         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17698         if (shdr_status || shdr_add_status || rc) {
17699                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17700                                 "2506 CQ_DESTROY mailbox failed with "
17701                                 "status x%x add_status x%x, mbx status x%x\n",
17702                                 shdr_status, shdr_add_status, rc);
17703                 status = -ENXIO;
17704         }
17705         mempool_free(mbox, cq->phba->mbox_mem_pool);
17706
17707 list_remove:
17708         /* Remove cq from any list */
17709         list_del_init(&cq->list);
17710         return status;
17711 }
17712
17713 /**
17714  * lpfc_mq_destroy - Destroy a Mailbox Queue on the HBA
17715  * @phba: HBA structure that indicates port to destroy a queue on.
17716  * @mq: The queue structure associated with the queue to destroy.
17717  *
17718  * This function destroys a queue, as detailed in @mq by sending an mailbox
17719  * command, specific to the type of queue, to the HBA.
17720  *
17721  * The @mq struct is used to get the queue ID of the queue to destroy.
17722  *
17723  * On success this function will return a zero. If the queue destroy mailbox
17724  * command fails this function will return -ENXIO.
17725  **/
17726 int
17727 lpfc_mq_destroy(struct lpfc_hba *phba, struct lpfc_queue *mq)
17728 {
17729         LPFC_MBOXQ_t *mbox;
17730         int rc, length, status = 0;
17731         uint32_t shdr_status, shdr_add_status;
17732         union lpfc_sli4_cfg_shdr *shdr;
17733
17734         /* sanity check on queue memory */
17735         if (!mq)
17736                 return -ENODEV;
17737
17738         if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17739                 goto list_remove;
17740
17741         mbox = mempool_alloc(mq->phba->mbox_mem_pool, GFP_KERNEL);
17742         if (!mbox)
17743                 return -ENOMEM;
17744         length = (sizeof(struct lpfc_mbx_mq_destroy) -
17745                   sizeof(struct lpfc_sli4_cfg_mhdr));
17746         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
17747                          LPFC_MBOX_OPCODE_MQ_DESTROY,
17748                          length, LPFC_SLI4_MBX_EMBED);
17749         bf_set(lpfc_mbx_mq_destroy_q_id, &mbox->u.mqe.un.mq_destroy.u.request,
17750                mq->queue_id);
17751         mbox->vport = mq->phba->pport;
17752         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17753         rc = lpfc_sli_issue_mbox(mq->phba, mbox, MBX_POLL);
17754         /* The IOCTL status is embedded in the mailbox subheader. */
17755         shdr = (union lpfc_sli4_cfg_shdr *)
17756                 &mbox->u.mqe.un.mq_destroy.header.cfg_shdr;
17757         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17758         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17759         if (shdr_status || shdr_add_status || rc) {
17760                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17761                                 "2507 MQ_DESTROY mailbox failed with "
17762                                 "status x%x add_status x%x, mbx status x%x\n",
17763                                 shdr_status, shdr_add_status, rc);
17764                 status = -ENXIO;
17765         }
17766         mempool_free(mbox, mq->phba->mbox_mem_pool);
17767
17768 list_remove:
17769         /* Remove mq from any list */
17770         list_del_init(&mq->list);
17771         return status;
17772 }
17773
17774 /**
17775  * lpfc_wq_destroy - Destroy a Work Queue on the HBA
17776  * @phba: HBA structure that indicates port to destroy a queue on.
17777  * @wq: The queue structure associated with the queue to destroy.
17778  *
17779  * This function destroys a queue, as detailed in @wq by sending an mailbox
17780  * command, specific to the type of queue, to the HBA.
17781  *
17782  * The @wq struct is used to get the queue ID of the queue to destroy.
17783  *
17784  * On success this function will return a zero. If the queue destroy mailbox
17785  * command fails this function will return -ENXIO.
17786  **/
17787 int
17788 lpfc_wq_destroy(struct lpfc_hba *phba, struct lpfc_queue *wq)
17789 {
17790         LPFC_MBOXQ_t *mbox;
17791         int rc, length, status = 0;
17792         uint32_t shdr_status, shdr_add_status;
17793         union lpfc_sli4_cfg_shdr *shdr;
17794
17795         /* sanity check on queue memory */
17796         if (!wq)
17797                 return -ENODEV;
17798
17799         if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17800                 goto list_remove;
17801
17802         mbox = mempool_alloc(wq->phba->mbox_mem_pool, GFP_KERNEL);
17803         if (!mbox)
17804                 return -ENOMEM;
17805         length = (sizeof(struct lpfc_mbx_wq_destroy) -
17806                   sizeof(struct lpfc_sli4_cfg_mhdr));
17807         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17808                          LPFC_MBOX_OPCODE_FCOE_WQ_DESTROY,
17809                          length, LPFC_SLI4_MBX_EMBED);
17810         bf_set(lpfc_mbx_wq_destroy_q_id, &mbox->u.mqe.un.wq_destroy.u.request,
17811                wq->queue_id);
17812         mbox->vport = wq->phba->pport;
17813         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17814         rc = lpfc_sli_issue_mbox(wq->phba, mbox, MBX_POLL);
17815         shdr = (union lpfc_sli4_cfg_shdr *)
17816                 &mbox->u.mqe.un.wq_destroy.header.cfg_shdr;
17817         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17818         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17819         if (shdr_status || shdr_add_status || rc) {
17820                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17821                                 "2508 WQ_DESTROY mailbox failed with "
17822                                 "status x%x add_status x%x, mbx status x%x\n",
17823                                 shdr_status, shdr_add_status, rc);
17824                 status = -ENXIO;
17825         }
17826         mempool_free(mbox, wq->phba->mbox_mem_pool);
17827
17828 list_remove:
17829         /* Remove wq from any list */
17830         list_del_init(&wq->list);
17831         kfree(wq->pring);
17832         wq->pring = NULL;
17833         return status;
17834 }
17835
17836 /**
17837  * lpfc_rq_destroy - Destroy a Receive Queue on the HBA
17838  * @phba: HBA structure that indicates port to destroy a queue on.
17839  * @hrq: The queue structure associated with the queue to destroy.
17840  * @drq: The queue structure associated with the queue to destroy.
17841  *
17842  * This function destroys a queue, as detailed in @rq by sending an mailbox
17843  * command, specific to the type of queue, to the HBA.
17844  *
17845  * The @rq struct is used to get the queue ID of the queue to destroy.
17846  *
17847  * On success this function will return a zero. If the queue destroy mailbox
17848  * command fails this function will return -ENXIO.
17849  **/
17850 int
17851 lpfc_rq_destroy(struct lpfc_hba *phba, struct lpfc_queue *hrq,
17852                 struct lpfc_queue *drq)
17853 {
17854         LPFC_MBOXQ_t *mbox;
17855         int rc, length, status = 0;
17856         uint32_t shdr_status, shdr_add_status;
17857         union lpfc_sli4_cfg_shdr *shdr;
17858
17859         /* sanity check on queue memory */
17860         if (!hrq || !drq)
17861                 return -ENODEV;
17862
17863         if (!(phba->sli.sli_flag & LPFC_SLI_ACTIVE))
17864                 goto list_remove;
17865
17866         mbox = mempool_alloc(hrq->phba->mbox_mem_pool, GFP_KERNEL);
17867         if (!mbox)
17868                 return -ENOMEM;
17869         length = (sizeof(struct lpfc_mbx_rq_destroy) -
17870                   sizeof(struct lpfc_sli4_cfg_mhdr));
17871         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17872                          LPFC_MBOX_OPCODE_FCOE_RQ_DESTROY,
17873                          length, LPFC_SLI4_MBX_EMBED);
17874         bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17875                hrq->queue_id);
17876         mbox->vport = hrq->phba->pport;
17877         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
17878         rc = lpfc_sli_issue_mbox(hrq->phba, mbox, MBX_POLL);
17879         /* The IOCTL status is embedded in the mailbox subheader. */
17880         shdr = (union lpfc_sli4_cfg_shdr *)
17881                 &mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17882         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17883         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17884         if (shdr_status || shdr_add_status || rc) {
17885                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17886                                 "2509 RQ_DESTROY mailbox failed with "
17887                                 "status x%x add_status x%x, mbx status x%x\n",
17888                                 shdr_status, shdr_add_status, rc);
17889                 mempool_free(mbox, hrq->phba->mbox_mem_pool);
17890                 return -ENXIO;
17891         }
17892         bf_set(lpfc_mbx_rq_destroy_q_id, &mbox->u.mqe.un.rq_destroy.u.request,
17893                drq->queue_id);
17894         rc = lpfc_sli_issue_mbox(drq->phba, mbox, MBX_POLL);
17895         shdr = (union lpfc_sli4_cfg_shdr *)
17896                 &mbox->u.mqe.un.rq_destroy.header.cfg_shdr;
17897         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17898         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17899         if (shdr_status || shdr_add_status || rc) {
17900                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17901                                 "2510 RQ_DESTROY mailbox failed with "
17902                                 "status x%x add_status x%x, mbx status x%x\n",
17903                                 shdr_status, shdr_add_status, rc);
17904                 status = -ENXIO;
17905         }
17906         mempool_free(mbox, hrq->phba->mbox_mem_pool);
17907
17908 list_remove:
17909         list_del_init(&hrq->list);
17910         list_del_init(&drq->list);
17911         return status;
17912 }
17913
17914 /**
17915  * lpfc_sli4_post_sgl - Post scatter gather list for an XRI to HBA
17916  * @phba: The virtual port for which this call being executed.
17917  * @pdma_phys_addr0: Physical address of the 1st SGL page.
17918  * @pdma_phys_addr1: Physical address of the 2nd SGL page.
17919  * @xritag: the xritag that ties this io to the SGL pages.
17920  *
17921  * This routine will post the sgl pages for the IO that has the xritag
17922  * that is in the iocbq structure. The xritag is assigned during iocbq
17923  * creation and persists for as long as the driver is loaded.
17924  * if the caller has fewer than 256 scatter gather segments to map then
17925  * pdma_phys_addr1 should be 0.
17926  * If the caller needs to map more than 256 scatter gather segment then
17927  * pdma_phys_addr1 should be a valid physical address.
17928  * physical address for SGLs must be 64 byte aligned.
17929  * If you are going to map 2 SGL's then the first one must have 256 entries
17930  * the second sgl can have between 1 and 256 entries.
17931  *
17932  * Return codes:
17933  *      0 - Success
17934  *      -ENXIO, -ENOMEM - Failure
17935  **/
17936 int
17937 lpfc_sli4_post_sgl(struct lpfc_hba *phba,
17938                 dma_addr_t pdma_phys_addr0,
17939                 dma_addr_t pdma_phys_addr1,
17940                 uint16_t xritag)
17941 {
17942         struct lpfc_mbx_post_sgl_pages *post_sgl_pages;
17943         LPFC_MBOXQ_t *mbox;
17944         int rc;
17945         uint32_t shdr_status, shdr_add_status;
17946         uint32_t mbox_tmo;
17947         union lpfc_sli4_cfg_shdr *shdr;
17948
17949         if (xritag == NO_XRI) {
17950                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17951                                 "0364 Invalid param:\n");
17952                 return -EINVAL;
17953         }
17954
17955         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
17956         if (!mbox)
17957                 return -ENOMEM;
17958
17959         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
17960                         LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
17961                         sizeof(struct lpfc_mbx_post_sgl_pages) -
17962                         sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
17963
17964         post_sgl_pages = (struct lpfc_mbx_post_sgl_pages *)
17965                                 &mbox->u.mqe.un.post_sgl_pages;
17966         bf_set(lpfc_post_sgl_pages_xri, post_sgl_pages, xritag);
17967         bf_set(lpfc_post_sgl_pages_xricnt, post_sgl_pages, 1);
17968
17969         post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_lo =
17970                                 cpu_to_le32(putPaddrLow(pdma_phys_addr0));
17971         post_sgl_pages->sgl_pg_pairs[0].sgl_pg0_addr_hi =
17972                                 cpu_to_le32(putPaddrHigh(pdma_phys_addr0));
17973
17974         post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_lo =
17975                                 cpu_to_le32(putPaddrLow(pdma_phys_addr1));
17976         post_sgl_pages->sgl_pg_pairs[0].sgl_pg1_addr_hi =
17977                                 cpu_to_le32(putPaddrHigh(pdma_phys_addr1));
17978         if (!phba->sli4_hba.intr_enable)
17979                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
17980         else {
17981                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
17982                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
17983         }
17984         /* The IOCTL status is embedded in the mailbox subheader. */
17985         shdr = (union lpfc_sli4_cfg_shdr *) &post_sgl_pages->header.cfg_shdr;
17986         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
17987         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
17988         if (!phba->sli4_hba.intr_enable)
17989                 mempool_free(mbox, phba->mbox_mem_pool);
17990         else if (rc != MBX_TIMEOUT)
17991                 mempool_free(mbox, phba->mbox_mem_pool);
17992         if (shdr_status || shdr_add_status || rc) {
17993                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
17994                                 "2511 POST_SGL mailbox failed with "
17995                                 "status x%x add_status x%x, mbx status x%x\n",
17996                                 shdr_status, shdr_add_status, rc);
17997         }
17998         return 0;
17999 }
18000
18001 /**
18002  * lpfc_sli4_alloc_xri - Get an available rpi in the device's range
18003  * @phba: pointer to lpfc hba data structure.
18004  *
18005  * This routine is invoked to post rpi header templates to the
18006  * HBA consistent with the SLI-4 interface spec.  This routine
18007  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
18008  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
18009  *
18010  * Returns
18011  *      A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
18012  *      LPFC_RPI_ALLOC_ERROR if no rpis are available.
18013  **/
18014 static uint16_t
18015 lpfc_sli4_alloc_xri(struct lpfc_hba *phba)
18016 {
18017         unsigned long xri;
18018
18019         /*
18020          * Fetch the next logical xri.  Because this index is logical,
18021          * the driver starts at 0 each time.
18022          */
18023         spin_lock_irq(&phba->hbalock);
18024         xri = find_first_zero_bit(phba->sli4_hba.xri_bmask,
18025                                  phba->sli4_hba.max_cfg_param.max_xri);
18026         if (xri >= phba->sli4_hba.max_cfg_param.max_xri) {
18027                 spin_unlock_irq(&phba->hbalock);
18028                 return NO_XRI;
18029         } else {
18030                 set_bit(xri, phba->sli4_hba.xri_bmask);
18031                 phba->sli4_hba.max_cfg_param.xri_used++;
18032         }
18033         spin_unlock_irq(&phba->hbalock);
18034         return xri;
18035 }
18036
18037 /**
18038  * __lpfc_sli4_free_xri - Release an xri for reuse.
18039  * @phba: pointer to lpfc hba data structure.
18040  * @xri: xri to release.
18041  *
18042  * This routine is invoked to release an xri to the pool of
18043  * available rpis maintained by the driver.
18044  **/
18045 static void
18046 __lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18047 {
18048         if (test_and_clear_bit(xri, phba->sli4_hba.xri_bmask)) {
18049                 phba->sli4_hba.max_cfg_param.xri_used--;
18050         }
18051 }
18052
18053 /**
18054  * lpfc_sli4_free_xri - Release an xri for reuse.
18055  * @phba: pointer to lpfc hba data structure.
18056  * @xri: xri to release.
18057  *
18058  * This routine is invoked to release an xri to the pool of
18059  * available rpis maintained by the driver.
18060  **/
18061 void
18062 lpfc_sli4_free_xri(struct lpfc_hba *phba, int xri)
18063 {
18064         spin_lock_irq(&phba->hbalock);
18065         __lpfc_sli4_free_xri(phba, xri);
18066         spin_unlock_irq(&phba->hbalock);
18067 }
18068
18069 /**
18070  * lpfc_sli4_next_xritag - Get an xritag for the io
18071  * @phba: Pointer to HBA context object.
18072  *
18073  * This function gets an xritag for the iocb. If there is no unused xritag
18074  * it will return 0xffff.
18075  * The function returns the allocated xritag if successful, else returns zero.
18076  * Zero is not a valid xritag.
18077  * The caller is not required to hold any lock.
18078  **/
18079 uint16_t
18080 lpfc_sli4_next_xritag(struct lpfc_hba *phba)
18081 {
18082         uint16_t xri_index;
18083
18084         xri_index = lpfc_sli4_alloc_xri(phba);
18085         if (xri_index == NO_XRI)
18086                 lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
18087                                 "2004 Failed to allocate XRI.last XRITAG is %d"
18088                                 " Max XRI is %d, Used XRI is %d\n",
18089                                 xri_index,
18090                                 phba->sli4_hba.max_cfg_param.max_xri,
18091                                 phba->sli4_hba.max_cfg_param.xri_used);
18092         return xri_index;
18093 }
18094
18095 /**
18096  * lpfc_sli4_post_sgl_list - post a block of ELS sgls to the port.
18097  * @phba: pointer to lpfc hba data structure.
18098  * @post_sgl_list: pointer to els sgl entry list.
18099  * @post_cnt: number of els sgl entries on the list.
18100  *
18101  * This routine is invoked to post a block of driver's sgl pages to the
18102  * HBA using non-embedded mailbox command. No Lock is held. This routine
18103  * is only called when the driver is loading and after all IO has been
18104  * stopped.
18105  **/
18106 static int
18107 lpfc_sli4_post_sgl_list(struct lpfc_hba *phba,
18108                             struct list_head *post_sgl_list,
18109                             int post_cnt)
18110 {
18111         struct lpfc_sglq *sglq_entry = NULL, *sglq_next = NULL;
18112         struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18113         struct sgl_page_pairs *sgl_pg_pairs;
18114         void *viraddr;
18115         LPFC_MBOXQ_t *mbox;
18116         uint32_t reqlen, alloclen, pg_pairs;
18117         uint32_t mbox_tmo;
18118         uint16_t xritag_start = 0;
18119         int rc = 0;
18120         uint32_t shdr_status, shdr_add_status;
18121         union lpfc_sli4_cfg_shdr *shdr;
18122
18123         reqlen = post_cnt * sizeof(struct sgl_page_pairs) +
18124                  sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18125         if (reqlen > SLI4_PAGE_SIZE) {
18126                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18127                                 "2559 Block sgl registration required DMA "
18128                                 "size (%d) great than a page\n", reqlen);
18129                 return -ENOMEM;
18130         }
18131
18132         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18133         if (!mbox)
18134                 return -ENOMEM;
18135
18136         /* Allocate DMA memory and set up the non-embedded mailbox command */
18137         alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18138                          LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES, reqlen,
18139                          LPFC_SLI4_MBX_NEMBED);
18140
18141         if (alloclen < reqlen) {
18142                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18143                                 "0285 Allocated DMA memory size (%d) is "
18144                                 "less than the requested DMA memory "
18145                                 "size (%d)\n", alloclen, reqlen);
18146                 lpfc_sli4_mbox_cmd_free(phba, mbox);
18147                 return -ENOMEM;
18148         }
18149         /* Set up the SGL pages in the non-embedded DMA pages */
18150         viraddr = mbox->sge_array->addr[0];
18151         sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18152         sgl_pg_pairs = &sgl->sgl_pg_pairs;
18153
18154         pg_pairs = 0;
18155         list_for_each_entry_safe(sglq_entry, sglq_next, post_sgl_list, list) {
18156                 /* Set up the sge entry */
18157                 sgl_pg_pairs->sgl_pg0_addr_lo =
18158                                 cpu_to_le32(putPaddrLow(sglq_entry->phys));
18159                 sgl_pg_pairs->sgl_pg0_addr_hi =
18160                                 cpu_to_le32(putPaddrHigh(sglq_entry->phys));
18161                 sgl_pg_pairs->sgl_pg1_addr_lo =
18162                                 cpu_to_le32(putPaddrLow(0));
18163                 sgl_pg_pairs->sgl_pg1_addr_hi =
18164                                 cpu_to_le32(putPaddrHigh(0));
18165
18166                 /* Keep the first xritag on the list */
18167                 if (pg_pairs == 0)
18168                         xritag_start = sglq_entry->sli4_xritag;
18169                 sgl_pg_pairs++;
18170                 pg_pairs++;
18171         }
18172
18173         /* Complete initialization and perform endian conversion. */
18174         bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18175         bf_set(lpfc_post_sgl_pages_xricnt, sgl, post_cnt);
18176         sgl->word0 = cpu_to_le32(sgl->word0);
18177
18178         if (!phba->sli4_hba.intr_enable)
18179                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18180         else {
18181                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18182                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18183         }
18184         shdr = (union lpfc_sli4_cfg_shdr *) &sgl->cfg_shdr;
18185         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18186         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18187         if (!phba->sli4_hba.intr_enable)
18188                 lpfc_sli4_mbox_cmd_free(phba, mbox);
18189         else if (rc != MBX_TIMEOUT)
18190                 lpfc_sli4_mbox_cmd_free(phba, mbox);
18191         if (shdr_status || shdr_add_status || rc) {
18192                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18193                                 "2513 POST_SGL_BLOCK mailbox command failed "
18194                                 "status x%x add_status x%x mbx status x%x\n",
18195                                 shdr_status, shdr_add_status, rc);
18196                 rc = -ENXIO;
18197         }
18198         return rc;
18199 }
18200
18201 /**
18202  * lpfc_sli4_post_io_sgl_block - post a block of nvme sgl list to firmware
18203  * @phba: pointer to lpfc hba data structure.
18204  * @nblist: pointer to nvme buffer list.
18205  * @count: number of scsi buffers on the list.
18206  *
18207  * This routine is invoked to post a block of @count scsi sgl pages from a
18208  * SCSI buffer list @nblist to the HBA using non-embedded mailbox command.
18209  * No Lock is held.
18210  *
18211  **/
18212 static int
18213 lpfc_sli4_post_io_sgl_block(struct lpfc_hba *phba, struct list_head *nblist,
18214                             int count)
18215 {
18216         struct lpfc_io_buf *lpfc_ncmd;
18217         struct lpfc_mbx_post_uembed_sgl_page1 *sgl;
18218         struct sgl_page_pairs *sgl_pg_pairs;
18219         void *viraddr;
18220         LPFC_MBOXQ_t *mbox;
18221         uint32_t reqlen, alloclen, pg_pairs;
18222         uint32_t mbox_tmo;
18223         uint16_t xritag_start = 0;
18224         int rc = 0;
18225         uint32_t shdr_status, shdr_add_status;
18226         dma_addr_t pdma_phys_bpl1;
18227         union lpfc_sli4_cfg_shdr *shdr;
18228
18229         /* Calculate the requested length of the dma memory */
18230         reqlen = count * sizeof(struct sgl_page_pairs) +
18231                  sizeof(union lpfc_sli4_cfg_shdr) + sizeof(uint32_t);
18232         if (reqlen > SLI4_PAGE_SIZE) {
18233                 lpfc_printf_log(phba, KERN_WARNING, LOG_INIT,
18234                                 "6118 Block sgl registration required DMA "
18235                                 "size (%d) great than a page\n", reqlen);
18236                 return -ENOMEM;
18237         }
18238         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
18239         if (!mbox) {
18240                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18241                                 "6119 Failed to allocate mbox cmd memory\n");
18242                 return -ENOMEM;
18243         }
18244
18245         /* Allocate DMA memory and set up the non-embedded mailbox command */
18246         alloclen = lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
18247                                     LPFC_MBOX_OPCODE_FCOE_POST_SGL_PAGES,
18248                                     reqlen, LPFC_SLI4_MBX_NEMBED);
18249
18250         if (alloclen < reqlen) {
18251                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18252                                 "6120 Allocated DMA memory size (%d) is "
18253                                 "less than the requested DMA memory "
18254                                 "size (%d)\n", alloclen, reqlen);
18255                 lpfc_sli4_mbox_cmd_free(phba, mbox);
18256                 return -ENOMEM;
18257         }
18258
18259         /* Get the first SGE entry from the non-embedded DMA memory */
18260         viraddr = mbox->sge_array->addr[0];
18261
18262         /* Set up the SGL pages in the non-embedded DMA pages */
18263         sgl = (struct lpfc_mbx_post_uembed_sgl_page1 *)viraddr;
18264         sgl_pg_pairs = &sgl->sgl_pg_pairs;
18265
18266         pg_pairs = 0;
18267         list_for_each_entry(lpfc_ncmd, nblist, list) {
18268                 /* Set up the sge entry */
18269                 sgl_pg_pairs->sgl_pg0_addr_lo =
18270                         cpu_to_le32(putPaddrLow(lpfc_ncmd->dma_phys_sgl));
18271                 sgl_pg_pairs->sgl_pg0_addr_hi =
18272                         cpu_to_le32(putPaddrHigh(lpfc_ncmd->dma_phys_sgl));
18273                 if (phba->cfg_sg_dma_buf_size > SGL_PAGE_SIZE)
18274                         pdma_phys_bpl1 = lpfc_ncmd->dma_phys_sgl +
18275                                                 SGL_PAGE_SIZE;
18276                 else
18277                         pdma_phys_bpl1 = 0;
18278                 sgl_pg_pairs->sgl_pg1_addr_lo =
18279                         cpu_to_le32(putPaddrLow(pdma_phys_bpl1));
18280                 sgl_pg_pairs->sgl_pg1_addr_hi =
18281                         cpu_to_le32(putPaddrHigh(pdma_phys_bpl1));
18282                 /* Keep the first xritag on the list */
18283                 if (pg_pairs == 0)
18284                         xritag_start = lpfc_ncmd->cur_iocbq.sli4_xritag;
18285                 sgl_pg_pairs++;
18286                 pg_pairs++;
18287         }
18288         bf_set(lpfc_post_sgl_pages_xri, sgl, xritag_start);
18289         bf_set(lpfc_post_sgl_pages_xricnt, sgl, pg_pairs);
18290         /* Perform endian conversion if necessary */
18291         sgl->word0 = cpu_to_le32(sgl->word0);
18292
18293         if (!phba->sli4_hba.intr_enable) {
18294                 rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
18295         } else {
18296                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
18297                 rc = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
18298         }
18299         shdr = (union lpfc_sli4_cfg_shdr *)&sgl->cfg_shdr;
18300         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
18301         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
18302         if (!phba->sli4_hba.intr_enable)
18303                 lpfc_sli4_mbox_cmd_free(phba, mbox);
18304         else if (rc != MBX_TIMEOUT)
18305                 lpfc_sli4_mbox_cmd_free(phba, mbox);
18306         if (shdr_status || shdr_add_status || rc) {
18307                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18308                                 "6125 POST_SGL_BLOCK mailbox command failed "
18309                                 "status x%x add_status x%x mbx status x%x\n",
18310                                 shdr_status, shdr_add_status, rc);
18311                 rc = -ENXIO;
18312         }
18313         return rc;
18314 }
18315
18316 /**
18317  * lpfc_sli4_post_io_sgl_list - Post blocks of nvme buffer sgls from a list
18318  * @phba: pointer to lpfc hba data structure.
18319  * @post_nblist: pointer to the nvme buffer list.
18320  * @sb_count: number of nvme buffers.
18321  *
18322  * This routine walks a list of nvme buffers that was passed in. It attempts
18323  * to construct blocks of nvme buffer sgls which contains contiguous xris and
18324  * uses the non-embedded SGL block post mailbox commands to post to the port.
18325  * For single NVME buffer sgl with non-contiguous xri, if any, it shall use
18326  * embedded SGL post mailbox command for posting. The @post_nblist passed in
18327  * must be local list, thus no lock is needed when manipulate the list.
18328  *
18329  * Returns: 0 = failure, non-zero number of successfully posted buffers.
18330  **/
18331 int
18332 lpfc_sli4_post_io_sgl_list(struct lpfc_hba *phba,
18333                            struct list_head *post_nblist, int sb_count)
18334 {
18335         struct lpfc_io_buf *lpfc_ncmd, *lpfc_ncmd_next;
18336         int status, sgl_size;
18337         int post_cnt = 0, block_cnt = 0, num_posting = 0, num_posted = 0;
18338         dma_addr_t pdma_phys_sgl1;
18339         int last_xritag = NO_XRI;
18340         int cur_xritag;
18341         LIST_HEAD(prep_nblist);
18342         LIST_HEAD(blck_nblist);
18343         LIST_HEAD(nvme_nblist);
18344
18345         /* sanity check */
18346         if (sb_count <= 0)
18347                 return -EINVAL;
18348
18349         sgl_size = phba->cfg_sg_dma_buf_size;
18350         list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next, post_nblist, list) {
18351                 list_del_init(&lpfc_ncmd->list);
18352                 block_cnt++;
18353                 if ((last_xritag != NO_XRI) &&
18354                     (lpfc_ncmd->cur_iocbq.sli4_xritag != last_xritag + 1)) {
18355                         /* a hole in xri block, form a sgl posting block */
18356                         list_splice_init(&prep_nblist, &blck_nblist);
18357                         post_cnt = block_cnt - 1;
18358                         /* prepare list for next posting block */
18359                         list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18360                         block_cnt = 1;
18361                 } else {
18362                         /* prepare list for next posting block */
18363                         list_add_tail(&lpfc_ncmd->list, &prep_nblist);
18364                         /* enough sgls for non-embed sgl mbox command */
18365                         if (block_cnt == LPFC_NEMBED_MBOX_SGL_CNT) {
18366                                 list_splice_init(&prep_nblist, &blck_nblist);
18367                                 post_cnt = block_cnt;
18368                                 block_cnt = 0;
18369                         }
18370                 }
18371                 num_posting++;
18372                 last_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18373
18374                 /* end of repost sgl list condition for NVME buffers */
18375                 if (num_posting == sb_count) {
18376                         if (post_cnt == 0) {
18377                                 /* last sgl posting block */
18378                                 list_splice_init(&prep_nblist, &blck_nblist);
18379                                 post_cnt = block_cnt;
18380                         } else if (block_cnt == 1) {
18381                                 /* last single sgl with non-contiguous xri */
18382                                 if (sgl_size > SGL_PAGE_SIZE)
18383                                         pdma_phys_sgl1 =
18384                                                 lpfc_ncmd->dma_phys_sgl +
18385                                                 SGL_PAGE_SIZE;
18386                                 else
18387                                         pdma_phys_sgl1 = 0;
18388                                 cur_xritag = lpfc_ncmd->cur_iocbq.sli4_xritag;
18389                                 status = lpfc_sli4_post_sgl(
18390                                                 phba, lpfc_ncmd->dma_phys_sgl,
18391                                                 pdma_phys_sgl1, cur_xritag);
18392                                 if (status) {
18393                                         /* Post error.  Buffer unavailable. */
18394                                         lpfc_ncmd->flags |=
18395                                                 LPFC_SBUF_NOT_POSTED;
18396                                 } else {
18397                                         /* Post success. Bffer available. */
18398                                         lpfc_ncmd->flags &=
18399                                                 ~LPFC_SBUF_NOT_POSTED;
18400                                         lpfc_ncmd->status = IOSTAT_SUCCESS;
18401                                         num_posted++;
18402                                 }
18403                                 /* success, put on NVME buffer sgl list */
18404                                 list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18405                         }
18406                 }
18407
18408                 /* continue until a nembed page worth of sgls */
18409                 if (post_cnt == 0)
18410                         continue;
18411
18412                 /* post block of NVME buffer list sgls */
18413                 status = lpfc_sli4_post_io_sgl_block(phba, &blck_nblist,
18414                                                      post_cnt);
18415
18416                 /* don't reset xirtag due to hole in xri block */
18417                 if (block_cnt == 0)
18418                         last_xritag = NO_XRI;
18419
18420                 /* reset NVME buffer post count for next round of posting */
18421                 post_cnt = 0;
18422
18423                 /* put posted NVME buffer-sgl posted on NVME buffer sgl list */
18424                 while (!list_empty(&blck_nblist)) {
18425                         list_remove_head(&blck_nblist, lpfc_ncmd,
18426                                          struct lpfc_io_buf, list);
18427                         if (status) {
18428                                 /* Post error.  Mark buffer unavailable. */
18429                                 lpfc_ncmd->flags |= LPFC_SBUF_NOT_POSTED;
18430                         } else {
18431                                 /* Post success, Mark buffer available. */
18432                                 lpfc_ncmd->flags &= ~LPFC_SBUF_NOT_POSTED;
18433                                 lpfc_ncmd->status = IOSTAT_SUCCESS;
18434                                 num_posted++;
18435                         }
18436                         list_add_tail(&lpfc_ncmd->list, &nvme_nblist);
18437                 }
18438         }
18439         /* Push NVME buffers with sgl posted to the available list */
18440         lpfc_io_buf_replenish(phba, &nvme_nblist);
18441
18442         return num_posted;
18443 }
18444
18445 /**
18446  * lpfc_fc_frame_check - Check that this frame is a valid frame to handle
18447  * @phba: pointer to lpfc_hba struct that the frame was received on
18448  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18449  *
18450  * This function checks the fields in the @fc_hdr to see if the FC frame is a
18451  * valid type of frame that the LPFC driver will handle. This function will
18452  * return a zero if the frame is a valid frame or a non zero value when the
18453  * frame does not pass the check.
18454  **/
18455 static int
18456 lpfc_fc_frame_check(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr)
18457 {
18458         /*  make rctl_names static to save stack space */
18459         struct fc_vft_header *fc_vft_hdr;
18460         struct fc_app_header *fc_app_hdr;
18461         uint32_t *header = (uint32_t *) fc_hdr;
18462
18463 #define FC_RCTL_MDS_DIAGS       0xF4
18464
18465         switch (fc_hdr->fh_r_ctl) {
18466         case FC_RCTL_DD_UNCAT:          /* uncategorized information */
18467         case FC_RCTL_DD_SOL_DATA:       /* solicited data */
18468         case FC_RCTL_DD_UNSOL_CTL:      /* unsolicited control */
18469         case FC_RCTL_DD_SOL_CTL:        /* solicited control or reply */
18470         case FC_RCTL_DD_UNSOL_DATA:     /* unsolicited data */
18471         case FC_RCTL_DD_DATA_DESC:      /* data descriptor */
18472         case FC_RCTL_DD_UNSOL_CMD:      /* unsolicited command */
18473         case FC_RCTL_DD_CMD_STATUS:     /* command status */
18474         case FC_RCTL_ELS_REQ:   /* extended link services request */
18475         case FC_RCTL_ELS_REP:   /* extended link services reply */
18476         case FC_RCTL_ELS4_REQ:  /* FC-4 ELS request */
18477         case FC_RCTL_ELS4_REP:  /* FC-4 ELS reply */
18478         case FC_RCTL_BA_ABTS:   /* basic link service abort */
18479         case FC_RCTL_BA_RMC:    /* remove connection */
18480         case FC_RCTL_BA_ACC:    /* basic accept */
18481         case FC_RCTL_BA_RJT:    /* basic reject */
18482         case FC_RCTL_BA_PRMT:
18483         case FC_RCTL_ACK_1:     /* acknowledge_1 */
18484         case FC_RCTL_ACK_0:     /* acknowledge_0 */
18485         case FC_RCTL_P_RJT:     /* port reject */
18486         case FC_RCTL_F_RJT:     /* fabric reject */
18487         case FC_RCTL_P_BSY:     /* port busy */
18488         case FC_RCTL_F_BSY:     /* fabric busy to data frame */
18489         case FC_RCTL_F_BSYL:    /* fabric busy to link control frame */
18490         case FC_RCTL_LCR:       /* link credit reset */
18491         case FC_RCTL_MDS_DIAGS: /* MDS Diagnostics */
18492         case FC_RCTL_END:       /* end */
18493                 break;
18494         case FC_RCTL_VFTH:      /* Virtual Fabric tagging Header */
18495                 fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18496                 fc_hdr = &((struct fc_frame_header *)fc_vft_hdr)[1];
18497                 return lpfc_fc_frame_check(phba, fc_hdr);
18498         case FC_RCTL_BA_NOP:    /* basic link service NOP */
18499         default:
18500                 goto drop;
18501         }
18502
18503         switch (fc_hdr->fh_type) {
18504         case FC_TYPE_BLS:
18505         case FC_TYPE_ELS:
18506         case FC_TYPE_FCP:
18507         case FC_TYPE_CT:
18508         case FC_TYPE_NVME:
18509                 break;
18510         case FC_TYPE_IP:
18511         case FC_TYPE_ILS:
18512         default:
18513                 goto drop;
18514         }
18515
18516         if (unlikely(phba->link_flag == LS_LOOPBACK_MODE &&
18517                                 phba->cfg_vmid_app_header)) {
18518                 /* Application header is 16B device header */
18519                 if (fc_hdr->fh_df_ctl & LPFC_FC_16B_DEVICE_HEADER) {
18520                         fc_app_hdr = (struct fc_app_header *) (fc_hdr + 1);
18521                         if (be32_to_cpu(fc_app_hdr->src_app_id) !=
18522                                         LOOPBACK_SRC_APPID) {
18523                                 lpfc_printf_log(phba, KERN_WARNING,
18524                                                 LOG_ELS | LOG_LIBDFC,
18525                                                 "1932 Loopback src app id "
18526                                                 "not matched, app_id:x%x\n",
18527                                                 be32_to_cpu(fc_app_hdr->src_app_id));
18528
18529                                 goto drop;
18530                         }
18531                 } else {
18532                         lpfc_printf_log(phba, KERN_WARNING,
18533                                         LOG_ELS | LOG_LIBDFC,
18534                                         "1933 Loopback df_ctl bit not set, "
18535                                         "df_ctl:x%x\n",
18536                                         fc_hdr->fh_df_ctl);
18537
18538                         goto drop;
18539                 }
18540         }
18541
18542         lpfc_printf_log(phba, KERN_INFO, LOG_ELS,
18543                         "2538 Received frame rctl:x%x, type:x%x, "
18544                         "frame Data:%08x %08x %08x %08x %08x %08x %08x\n",
18545                         fc_hdr->fh_r_ctl, fc_hdr->fh_type,
18546                         be32_to_cpu(header[0]), be32_to_cpu(header[1]),
18547                         be32_to_cpu(header[2]), be32_to_cpu(header[3]),
18548                         be32_to_cpu(header[4]), be32_to_cpu(header[5]),
18549                         be32_to_cpu(header[6]));
18550         return 0;
18551 drop:
18552         lpfc_printf_log(phba, KERN_WARNING, LOG_ELS,
18553                         "2539 Dropped frame rctl:x%x type:x%x\n",
18554                         fc_hdr->fh_r_ctl, fc_hdr->fh_type);
18555         return 1;
18556 }
18557
18558 /**
18559  * lpfc_fc_hdr_get_vfi - Get the VFI from an FC frame
18560  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18561  *
18562  * This function processes the FC header to retrieve the VFI from the VF
18563  * header, if one exists. This function will return the VFI if one exists
18564  * or 0 if no VSAN Header exists.
18565  **/
18566 static uint32_t
18567 lpfc_fc_hdr_get_vfi(struct fc_frame_header *fc_hdr)
18568 {
18569         struct fc_vft_header *fc_vft_hdr = (struct fc_vft_header *)fc_hdr;
18570
18571         if (fc_hdr->fh_r_ctl != FC_RCTL_VFTH)
18572                 return 0;
18573         return bf_get(fc_vft_hdr_vf_id, fc_vft_hdr);
18574 }
18575
18576 /**
18577  * lpfc_fc_frame_to_vport - Finds the vport that a frame is destined to
18578  * @phba: Pointer to the HBA structure to search for the vport on
18579  * @fc_hdr: A pointer to the FC Header data (In Big Endian Format)
18580  * @fcfi: The FC Fabric ID that the frame came from
18581  * @did: Destination ID to match against
18582  *
18583  * This function searches the @phba for a vport that matches the content of the
18584  * @fc_hdr passed in and the @fcfi. This function uses the @fc_hdr to fetch the
18585  * VFI, if the Virtual Fabric Tagging Header exists, and the DID. This function
18586  * returns the matching vport pointer or NULL if unable to match frame to a
18587  * vport.
18588  **/
18589 static struct lpfc_vport *
18590 lpfc_fc_frame_to_vport(struct lpfc_hba *phba, struct fc_frame_header *fc_hdr,
18591                        uint16_t fcfi, uint32_t did)
18592 {
18593         struct lpfc_vport **vports;
18594         struct lpfc_vport *vport = NULL;
18595         int i;
18596
18597         if (did == Fabric_DID)
18598                 return phba->pport;
18599         if (test_bit(FC_PT2PT, &phba->pport->fc_flag) &&
18600             phba->link_state != LPFC_HBA_READY)
18601                 return phba->pport;
18602
18603         vports = lpfc_create_vport_work_array(phba);
18604         if (vports != NULL) {
18605                 for (i = 0; i <= phba->max_vpi && vports[i] != NULL; i++) {
18606                         if (phba->fcf.fcfi == fcfi &&
18607                             vports[i]->vfi == lpfc_fc_hdr_get_vfi(fc_hdr) &&
18608                             vports[i]->fc_myDID == did) {
18609                                 vport = vports[i];
18610                                 break;
18611                         }
18612                 }
18613         }
18614         lpfc_destroy_vport_work_array(phba, vports);
18615         return vport;
18616 }
18617
18618 /**
18619  * lpfc_update_rcv_time_stamp - Update vport's rcv seq time stamp
18620  * @vport: The vport to work on.
18621  *
18622  * This function updates the receive sequence time stamp for this vport. The
18623  * receive sequence time stamp indicates the time that the last frame of the
18624  * the sequence that has been idle for the longest amount of time was received.
18625  * the driver uses this time stamp to indicate if any received sequences have
18626  * timed out.
18627  **/
18628 static void
18629 lpfc_update_rcv_time_stamp(struct lpfc_vport *vport)
18630 {
18631         struct lpfc_dmabuf *h_buf;
18632         struct hbq_dmabuf *dmabuf = NULL;
18633
18634         /* get the oldest sequence on the rcv list */
18635         h_buf = list_get_first(&vport->rcv_buffer_list,
18636                                struct lpfc_dmabuf, list);
18637         if (!h_buf)
18638                 return;
18639         dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18640         vport->rcv_buffer_time_stamp = dmabuf->time_stamp;
18641 }
18642
18643 /**
18644  * lpfc_cleanup_rcv_buffers - Cleans up all outstanding receive sequences.
18645  * @vport: The vport that the received sequences were sent to.
18646  *
18647  * This function cleans up all outstanding received sequences. This is called
18648  * by the driver when a link event or user action invalidates all the received
18649  * sequences.
18650  **/
18651 void
18652 lpfc_cleanup_rcv_buffers(struct lpfc_vport *vport)
18653 {
18654         struct lpfc_dmabuf *h_buf, *hnext;
18655         struct lpfc_dmabuf *d_buf, *dnext;
18656         struct hbq_dmabuf *dmabuf = NULL;
18657
18658         /* start with the oldest sequence on the rcv list */
18659         list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18660                 dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18661                 list_del_init(&dmabuf->hbuf.list);
18662                 list_for_each_entry_safe(d_buf, dnext,
18663                                          &dmabuf->dbuf.list, list) {
18664                         list_del_init(&d_buf->list);
18665                         lpfc_in_buf_free(vport->phba, d_buf);
18666                 }
18667                 lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18668         }
18669 }
18670
18671 /**
18672  * lpfc_rcv_seq_check_edtov - Cleans up timed out receive sequences.
18673  * @vport: The vport that the received sequences were sent to.
18674  *
18675  * This function determines whether any received sequences have timed out by
18676  * first checking the vport's rcv_buffer_time_stamp. If this time_stamp
18677  * indicates that there is at least one timed out sequence this routine will
18678  * go through the received sequences one at a time from most inactive to most
18679  * active to determine which ones need to be cleaned up. Once it has determined
18680  * that a sequence needs to be cleaned up it will simply free up the resources
18681  * without sending an abort.
18682  **/
18683 void
18684 lpfc_rcv_seq_check_edtov(struct lpfc_vport *vport)
18685 {
18686         struct lpfc_dmabuf *h_buf, *hnext;
18687         struct lpfc_dmabuf *d_buf, *dnext;
18688         struct hbq_dmabuf *dmabuf = NULL;
18689         unsigned long timeout;
18690         int abort_count = 0;
18691
18692         timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18693                    vport->rcv_buffer_time_stamp);
18694         if (list_empty(&vport->rcv_buffer_list) ||
18695             time_before(jiffies, timeout))
18696                 return;
18697         /* start with the oldest sequence on the rcv list */
18698         list_for_each_entry_safe(h_buf, hnext, &vport->rcv_buffer_list, list) {
18699                 dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18700                 timeout = (msecs_to_jiffies(vport->phba->fc_edtov) +
18701                            dmabuf->time_stamp);
18702                 if (time_before(jiffies, timeout))
18703                         break;
18704                 abort_count++;
18705                 list_del_init(&dmabuf->hbuf.list);
18706                 list_for_each_entry_safe(d_buf, dnext,
18707                                          &dmabuf->dbuf.list, list) {
18708                         list_del_init(&d_buf->list);
18709                         lpfc_in_buf_free(vport->phba, d_buf);
18710                 }
18711                 lpfc_in_buf_free(vport->phba, &dmabuf->dbuf);
18712         }
18713         if (abort_count)
18714                 lpfc_update_rcv_time_stamp(vport);
18715 }
18716
18717 /**
18718  * lpfc_fc_frame_add - Adds a frame to the vport's list of received sequences
18719  * @vport: pointer to a vitural port
18720  * @dmabuf: pointer to a dmabuf that describes the hdr and data of the FC frame
18721  *
18722  * This function searches through the existing incomplete sequences that have
18723  * been sent to this @vport. If the frame matches one of the incomplete
18724  * sequences then the dbuf in the @dmabuf is added to the list of frames that
18725  * make up that sequence. If no sequence is found that matches this frame then
18726  * the function will add the hbuf in the @dmabuf to the @vport's rcv_buffer_list
18727  * This function returns a pointer to the first dmabuf in the sequence list that
18728  * the frame was linked to.
18729  **/
18730 static struct hbq_dmabuf *
18731 lpfc_fc_frame_add(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18732 {
18733         struct fc_frame_header *new_hdr;
18734         struct fc_frame_header *temp_hdr;
18735         struct lpfc_dmabuf *d_buf;
18736         struct lpfc_dmabuf *h_buf;
18737         struct hbq_dmabuf *seq_dmabuf = NULL;
18738         struct hbq_dmabuf *temp_dmabuf = NULL;
18739         uint8_t found = 0;
18740
18741         INIT_LIST_HEAD(&dmabuf->dbuf.list);
18742         dmabuf->time_stamp = jiffies;
18743         new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18744
18745         /* Use the hdr_buf to find the sequence that this frame belongs to */
18746         list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18747                 temp_hdr = (struct fc_frame_header *)h_buf->virt;
18748                 if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18749                     (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18750                     (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18751                         continue;
18752                 /* found a pending sequence that matches this frame */
18753                 seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18754                 break;
18755         }
18756         if (!seq_dmabuf) {
18757                 /*
18758                  * This indicates first frame received for this sequence.
18759                  * Queue the buffer on the vport's rcv_buffer_list.
18760                  */
18761                 list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18762                 lpfc_update_rcv_time_stamp(vport);
18763                 return dmabuf;
18764         }
18765         temp_hdr = seq_dmabuf->hbuf.virt;
18766         if (be16_to_cpu(new_hdr->fh_seq_cnt) <
18767                 be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18768                 list_del_init(&seq_dmabuf->hbuf.list);
18769                 list_add_tail(&dmabuf->hbuf.list, &vport->rcv_buffer_list);
18770                 list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18771                 lpfc_update_rcv_time_stamp(vport);
18772                 return dmabuf;
18773         }
18774         /* move this sequence to the tail to indicate a young sequence */
18775         list_move_tail(&seq_dmabuf->hbuf.list, &vport->rcv_buffer_list);
18776         seq_dmabuf->time_stamp = jiffies;
18777         lpfc_update_rcv_time_stamp(vport);
18778         if (list_empty(&seq_dmabuf->dbuf.list)) {
18779                 list_add_tail(&dmabuf->dbuf.list, &seq_dmabuf->dbuf.list);
18780                 return seq_dmabuf;
18781         }
18782         /* find the correct place in the sequence to insert this frame */
18783         d_buf = list_entry(seq_dmabuf->dbuf.list.prev, typeof(*d_buf), list);
18784         while (!found) {
18785                 temp_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
18786                 temp_hdr = (struct fc_frame_header *)temp_dmabuf->hbuf.virt;
18787                 /*
18788                  * If the frame's sequence count is greater than the frame on
18789                  * the list then insert the frame right after this frame
18790                  */
18791                 if (be16_to_cpu(new_hdr->fh_seq_cnt) >
18792                         be16_to_cpu(temp_hdr->fh_seq_cnt)) {
18793                         list_add(&dmabuf->dbuf.list, &temp_dmabuf->dbuf.list);
18794                         found = 1;
18795                         break;
18796                 }
18797
18798                 if (&d_buf->list == &seq_dmabuf->dbuf.list)
18799                         break;
18800                 d_buf = list_entry(d_buf->list.prev, typeof(*d_buf), list);
18801         }
18802
18803         if (found)
18804                 return seq_dmabuf;
18805         return NULL;
18806 }
18807
18808 /**
18809  * lpfc_sli4_abort_partial_seq - Abort partially assembled unsol sequence
18810  * @vport: pointer to a vitural port
18811  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18812  *
18813  * This function tries to abort from the partially assembed sequence, described
18814  * by the information from basic abbort @dmabuf. It checks to see whether such
18815  * partially assembled sequence held by the driver. If so, it shall free up all
18816  * the frames from the partially assembled sequence.
18817  *
18818  * Return
18819  * true  -- if there is matching partially assembled sequence present and all
18820  *          the frames freed with the sequence;
18821  * false -- if there is no matching partially assembled sequence present so
18822  *          nothing got aborted in the lower layer driver
18823  **/
18824 static bool
18825 lpfc_sli4_abort_partial_seq(struct lpfc_vport *vport,
18826                             struct hbq_dmabuf *dmabuf)
18827 {
18828         struct fc_frame_header *new_hdr;
18829         struct fc_frame_header *temp_hdr;
18830         struct lpfc_dmabuf *d_buf, *n_buf, *h_buf;
18831         struct hbq_dmabuf *seq_dmabuf = NULL;
18832
18833         /* Use the hdr_buf to find the sequence that matches this frame */
18834         INIT_LIST_HEAD(&dmabuf->dbuf.list);
18835         INIT_LIST_HEAD(&dmabuf->hbuf.list);
18836         new_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
18837         list_for_each_entry(h_buf, &vport->rcv_buffer_list, list) {
18838                 temp_hdr = (struct fc_frame_header *)h_buf->virt;
18839                 if ((temp_hdr->fh_seq_id != new_hdr->fh_seq_id) ||
18840                     (temp_hdr->fh_ox_id != new_hdr->fh_ox_id) ||
18841                     (memcmp(&temp_hdr->fh_s_id, &new_hdr->fh_s_id, 3)))
18842                         continue;
18843                 /* found a pending sequence that matches this frame */
18844                 seq_dmabuf = container_of(h_buf, struct hbq_dmabuf, hbuf);
18845                 break;
18846         }
18847
18848         /* Free up all the frames from the partially assembled sequence */
18849         if (seq_dmabuf) {
18850                 list_for_each_entry_safe(d_buf, n_buf,
18851                                          &seq_dmabuf->dbuf.list, list) {
18852                         list_del_init(&d_buf->list);
18853                         lpfc_in_buf_free(vport->phba, d_buf);
18854                 }
18855                 return true;
18856         }
18857         return false;
18858 }
18859
18860 /**
18861  * lpfc_sli4_abort_ulp_seq - Abort assembled unsol sequence from ulp
18862  * @vport: pointer to a vitural port
18863  * @dmabuf: pointer to a dmabuf that describes the FC sequence
18864  *
18865  * This function tries to abort from the assembed sequence from upper level
18866  * protocol, described by the information from basic abbort @dmabuf. It
18867  * checks to see whether such pending context exists at upper level protocol.
18868  * If so, it shall clean up the pending context.
18869  *
18870  * Return
18871  * true  -- if there is matching pending context of the sequence cleaned
18872  *          at ulp;
18873  * false -- if there is no matching pending context of the sequence present
18874  *          at ulp.
18875  **/
18876 static bool
18877 lpfc_sli4_abort_ulp_seq(struct lpfc_vport *vport, struct hbq_dmabuf *dmabuf)
18878 {
18879         struct lpfc_hba *phba = vport->phba;
18880         int handled;
18881
18882         /* Accepting abort at ulp with SLI4 only */
18883         if (phba->sli_rev < LPFC_SLI_REV4)
18884                 return false;
18885
18886         /* Register all caring upper level protocols to attend abort */
18887         handled = lpfc_ct_handle_unsol_abort(phba, dmabuf);
18888         if (handled)
18889                 return true;
18890
18891         return false;
18892 }
18893
18894 /**
18895  * lpfc_sli4_seq_abort_rsp_cmpl - BLS ABORT RSP seq abort iocb complete handler
18896  * @phba: Pointer to HBA context object.
18897  * @cmd_iocbq: pointer to the command iocbq structure.
18898  * @rsp_iocbq: pointer to the response iocbq structure.
18899  *
18900  * This function handles the sequence abort response iocb command complete
18901  * event. It properly releases the memory allocated to the sequence abort
18902  * accept iocb.
18903  **/
18904 static void
18905 lpfc_sli4_seq_abort_rsp_cmpl(struct lpfc_hba *phba,
18906                              struct lpfc_iocbq *cmd_iocbq,
18907                              struct lpfc_iocbq *rsp_iocbq)
18908 {
18909         if (cmd_iocbq) {
18910                 lpfc_nlp_put(cmd_iocbq->ndlp);
18911                 lpfc_sli_release_iocbq(phba, cmd_iocbq);
18912         }
18913
18914         /* Failure means BLS ABORT RSP did not get delivered to remote node*/
18915         if (rsp_iocbq && rsp_iocbq->iocb.ulpStatus)
18916                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
18917                         "3154 BLS ABORT RSP failed, data:  x%x/x%x\n",
18918                         get_job_ulpstatus(phba, rsp_iocbq),
18919                         get_job_word4(phba, rsp_iocbq));
18920 }
18921
18922 /**
18923  * lpfc_sli4_xri_inrange - check xri is in range of xris owned by driver.
18924  * @phba: Pointer to HBA context object.
18925  * @xri: xri id in transaction.
18926  *
18927  * This function validates the xri maps to the known range of XRIs allocated an
18928  * used by the driver.
18929  **/
18930 uint16_t
18931 lpfc_sli4_xri_inrange(struct lpfc_hba *phba,
18932                       uint16_t xri)
18933 {
18934         uint16_t i;
18935
18936         for (i = 0; i < phba->sli4_hba.max_cfg_param.max_xri; i++) {
18937                 if (xri == phba->sli4_hba.xri_ids[i])
18938                         return i;
18939         }
18940         return NO_XRI;
18941 }
18942
18943 /**
18944  * lpfc_sli4_seq_abort_rsp - bls rsp to sequence abort
18945  * @vport: pointer to a virtual port.
18946  * @fc_hdr: pointer to a FC frame header.
18947  * @aborted: was the partially assembled receive sequence successfully aborted
18948  *
18949  * This function sends a basic response to a previous unsol sequence abort
18950  * event after aborting the sequence handling.
18951  **/
18952 void
18953 lpfc_sli4_seq_abort_rsp(struct lpfc_vport *vport,
18954                         struct fc_frame_header *fc_hdr, bool aborted)
18955 {
18956         struct lpfc_hba *phba = vport->phba;
18957         struct lpfc_iocbq *ctiocb = NULL;
18958         struct lpfc_nodelist *ndlp;
18959         uint16_t oxid, rxid, xri, lxri;
18960         uint32_t sid, fctl;
18961         union lpfc_wqe128 *icmd;
18962         int rc;
18963
18964         if (!lpfc_is_link_up(phba))
18965                 return;
18966
18967         sid = sli4_sid_from_fc_hdr(fc_hdr);
18968         oxid = be16_to_cpu(fc_hdr->fh_ox_id);
18969         rxid = be16_to_cpu(fc_hdr->fh_rx_id);
18970
18971         ndlp = lpfc_findnode_did(vport, sid);
18972         if (!ndlp) {
18973                 ndlp = lpfc_nlp_init(vport, sid);
18974                 if (!ndlp) {
18975                         lpfc_printf_vlog(vport, KERN_WARNING, LOG_ELS,
18976                                          "1268 Failed to allocate ndlp for "
18977                                          "oxid:x%x SID:x%x\n", oxid, sid);
18978                         return;
18979                 }
18980                 /* Put ndlp onto vport node list */
18981                 lpfc_enqueue_node(vport, ndlp);
18982         }
18983
18984         /* Allocate buffer for rsp iocb */
18985         ctiocb = lpfc_sli_get_iocbq(phba);
18986         if (!ctiocb)
18987                 return;
18988
18989         icmd = &ctiocb->wqe;
18990
18991         /* Extract the F_CTL field from FC_HDR */
18992         fctl = sli4_fctl_from_fc_hdr(fc_hdr);
18993
18994         ctiocb->ndlp = lpfc_nlp_get(ndlp);
18995         if (!ctiocb->ndlp) {
18996                 lpfc_sli_release_iocbq(phba, ctiocb);
18997                 return;
18998         }
18999
19000         ctiocb->vport = vport;
19001         ctiocb->cmd_cmpl = lpfc_sli4_seq_abort_rsp_cmpl;
19002         ctiocb->sli4_lxritag = NO_XRI;
19003         ctiocb->sli4_xritag = NO_XRI;
19004         ctiocb->abort_rctl = FC_RCTL_BA_ACC;
19005
19006         if (fctl & FC_FC_EX_CTX)
19007                 /* Exchange responder sent the abort so we
19008                  * own the oxid.
19009                  */
19010                 xri = oxid;
19011         else
19012                 xri = rxid;
19013         lxri = lpfc_sli4_xri_inrange(phba, xri);
19014         if (lxri != NO_XRI)
19015                 lpfc_set_rrq_active(phba, ndlp, lxri,
19016                         (xri == oxid) ? rxid : oxid, 0);
19017         /* For BA_ABTS from exchange responder, if the logical xri with
19018          * the oxid maps to the FCP XRI range, the port no longer has
19019          * that exchange context, send a BLS_RJT. Override the IOCB for
19020          * a BA_RJT.
19021          */
19022         if ((fctl & FC_FC_EX_CTX) &&
19023             (lxri > lpfc_sli4_get_iocb_cnt(phba))) {
19024                 ctiocb->abort_rctl = FC_RCTL_BA_RJT;
19025                 bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
19026                 bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
19027                        FC_BA_RJT_INV_XID);
19028                 bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
19029                        FC_BA_RJT_UNABLE);
19030         }
19031
19032         /* If BA_ABTS failed to abort a partially assembled receive sequence,
19033          * the driver no longer has that exchange, send a BLS_RJT. Override
19034          * the IOCB for a BA_RJT.
19035          */
19036         if (aborted == false) {
19037                 ctiocb->abort_rctl = FC_RCTL_BA_RJT;
19038                 bf_set(xmit_bls_rsp64_rjt_vspec, &icmd->xmit_bls_rsp, 0);
19039                 bf_set(xmit_bls_rsp64_rjt_expc, &icmd->xmit_bls_rsp,
19040                        FC_BA_RJT_INV_XID);
19041                 bf_set(xmit_bls_rsp64_rjt_rsnc, &icmd->xmit_bls_rsp,
19042                        FC_BA_RJT_UNABLE);
19043         }
19044
19045         if (fctl & FC_FC_EX_CTX) {
19046                 /* ABTS sent by responder to CT exchange, construction
19047                  * of BA_ACC will use OX_ID from ABTS for the XRI_TAG
19048                  * field and RX_ID from ABTS for RX_ID field.
19049                  */
19050                 ctiocb->abort_bls = LPFC_ABTS_UNSOL_RSP;
19051                 bf_set(xmit_bls_rsp64_rxid, &icmd->xmit_bls_rsp, rxid);
19052         } else {
19053                 /* ABTS sent by initiator to CT exchange, construction
19054                  * of BA_ACC will need to allocate a new XRI as for the
19055                  * XRI_TAG field.
19056                  */
19057                 ctiocb->abort_bls = LPFC_ABTS_UNSOL_INT;
19058         }
19059
19060         /* OX_ID is invariable to who sent ABTS to CT exchange */
19061         bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, oxid);
19062         bf_set(xmit_bls_rsp64_oxid, &icmd->xmit_bls_rsp, rxid);
19063
19064         /* Use CT=VPI */
19065         bf_set(wqe_els_did, &icmd->xmit_bls_rsp.wqe_dest,
19066                ndlp->nlp_DID);
19067         bf_set(xmit_bls_rsp64_temprpi, &icmd->xmit_bls_rsp,
19068                phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
19069         bf_set(wqe_cmnd, &icmd->generic.wqe_com, CMD_XMIT_BLS_RSP64_CX);
19070
19071         /* Xmit CT abts response on exchange <xid> */
19072         lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
19073                          "1200 Send BLS cmd x%x on oxid x%x Data: x%x\n",
19074                          ctiocb->abort_rctl, oxid, phba->link_state);
19075
19076         rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, ctiocb, 0);
19077         if (rc == IOCB_ERROR) {
19078                 lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19079                                  "2925 Failed to issue CT ABTS RSP x%x on "
19080                                  "xri x%x, Data x%x\n",
19081                                  ctiocb->abort_rctl, oxid,
19082                                  phba->link_state);
19083                 lpfc_nlp_put(ndlp);
19084                 ctiocb->ndlp = NULL;
19085                 lpfc_sli_release_iocbq(phba, ctiocb);
19086         }
19087
19088         /* if only usage of this nodelist is BLS response, release initial ref
19089          * to free ndlp when transmit completes
19090          */
19091         if (ndlp->nlp_state == NLP_STE_UNUSED_NODE &&
19092             !test_bit(NLP_DROPPED, &ndlp->nlp_flag) &&
19093             !(ndlp->fc4_xpt_flags & (NVME_XPT_REGD | SCSI_XPT_REGD))) {
19094                 set_bit(NLP_DROPPED, &ndlp->nlp_flag);
19095                 lpfc_nlp_put(ndlp);
19096         }
19097 }
19098
19099 /**
19100  * lpfc_sli4_handle_unsol_abort - Handle sli-4 unsolicited abort event
19101  * @vport: Pointer to the vport on which this sequence was received
19102  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19103  *
19104  * This function handles an SLI-4 unsolicited abort event. If the unsolicited
19105  * receive sequence is only partially assembed by the driver, it shall abort
19106  * the partially assembled frames for the sequence. Otherwise, if the
19107  * unsolicited receive sequence has been completely assembled and passed to
19108  * the Upper Layer Protocol (ULP), it then mark the per oxid status for the
19109  * unsolicited sequence has been aborted. After that, it will issue a basic
19110  * accept to accept the abort.
19111  **/
19112 static void
19113 lpfc_sli4_handle_unsol_abort(struct lpfc_vport *vport,
19114                              struct hbq_dmabuf *dmabuf)
19115 {
19116         struct lpfc_hba *phba = vport->phba;
19117         struct fc_frame_header fc_hdr;
19118         uint32_t fctl;
19119         bool aborted;
19120
19121         /* Make a copy of fc_hdr before the dmabuf being released */
19122         memcpy(&fc_hdr, dmabuf->hbuf.virt, sizeof(struct fc_frame_header));
19123         fctl = sli4_fctl_from_fc_hdr(&fc_hdr);
19124
19125         if (fctl & FC_FC_EX_CTX) {
19126                 /* ABTS by responder to exchange, no cleanup needed */
19127                 aborted = true;
19128         } else {
19129                 /* ABTS by initiator to exchange, need to do cleanup */
19130                 aborted = lpfc_sli4_abort_partial_seq(vport, dmabuf);
19131                 if (aborted == false)
19132                         aborted = lpfc_sli4_abort_ulp_seq(vport, dmabuf);
19133         }
19134         lpfc_in_buf_free(phba, &dmabuf->dbuf);
19135
19136         if (phba->nvmet_support) {
19137                 lpfc_nvmet_rcv_unsol_abort(vport, &fc_hdr);
19138                 return;
19139         }
19140
19141         /* Respond with BA_ACC or BA_RJT accordingly */
19142         lpfc_sli4_seq_abort_rsp(vport, &fc_hdr, aborted);
19143 }
19144
19145 /**
19146  * lpfc_seq_complete - Indicates if a sequence is complete
19147  * @dmabuf: pointer to a dmabuf that describes the FC sequence
19148  *
19149  * This function checks the sequence, starting with the frame described by
19150  * @dmabuf, to see if all the frames associated with this sequence are present.
19151  * the frames associated with this sequence are linked to the @dmabuf using the
19152  * dbuf list. This function looks for two major things. 1) That the first frame
19153  * has a sequence count of zero. 2) There is a frame with last frame of sequence
19154  * set. 3) That there are no holes in the sequence count. The function will
19155  * return 1 when the sequence is complete, otherwise it will return 0.
19156  **/
19157 static int
19158 lpfc_seq_complete(struct hbq_dmabuf *dmabuf)
19159 {
19160         struct fc_frame_header *hdr;
19161         struct lpfc_dmabuf *d_buf;
19162         struct hbq_dmabuf *seq_dmabuf;
19163         uint32_t fctl;
19164         int seq_count = 0;
19165
19166         hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19167         /* make sure first fame of sequence has a sequence count of zero */
19168         if (hdr->fh_seq_cnt != seq_count)
19169                 return 0;
19170         fctl = (hdr->fh_f_ctl[0] << 16 |
19171                 hdr->fh_f_ctl[1] << 8 |
19172                 hdr->fh_f_ctl[2]);
19173         /* If last frame of sequence we can return success. */
19174         if (fctl & FC_FC_END_SEQ)
19175                 return 1;
19176         list_for_each_entry(d_buf, &dmabuf->dbuf.list, list) {
19177                 seq_dmabuf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19178                 hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19179                 /* If there is a hole in the sequence count then fail. */
19180                 if (++seq_count != be16_to_cpu(hdr->fh_seq_cnt))
19181                         return 0;
19182                 fctl = (hdr->fh_f_ctl[0] << 16 |
19183                         hdr->fh_f_ctl[1] << 8 |
19184                         hdr->fh_f_ctl[2]);
19185                 /* If last frame of sequence we can return success. */
19186                 if (fctl & FC_FC_END_SEQ)
19187                         return 1;
19188         }
19189         return 0;
19190 }
19191
19192 /**
19193  * lpfc_prep_seq - Prep sequence for ULP processing
19194  * @vport: Pointer to the vport on which this sequence was received
19195  * @seq_dmabuf: pointer to a dmabuf that describes the FC sequence
19196  *
19197  * This function takes a sequence, described by a list of frames, and creates
19198  * a list of iocbq structures to describe the sequence. This iocbq list will be
19199  * used to issue to the generic unsolicited sequence handler. This routine
19200  * returns a pointer to the first iocbq in the list. If the function is unable
19201  * to allocate an iocbq then it throw out the received frames that were not
19202  * able to be described and return a pointer to the first iocbq. If unable to
19203  * allocate any iocbqs (including the first) this function will return NULL.
19204  **/
19205 static struct lpfc_iocbq *
19206 lpfc_prep_seq(struct lpfc_vport *vport, struct hbq_dmabuf *seq_dmabuf)
19207 {
19208         struct hbq_dmabuf *hbq_buf;
19209         struct lpfc_dmabuf *d_buf, *n_buf;
19210         struct lpfc_iocbq *first_iocbq, *iocbq;
19211         struct fc_frame_header *fc_hdr;
19212         uint32_t sid;
19213         uint32_t len, tot_len;
19214
19215         fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19216         /* remove from receive buffer list */
19217         list_del_init(&seq_dmabuf->hbuf.list);
19218         lpfc_update_rcv_time_stamp(vport);
19219         /* get the Remote Port's SID */
19220         sid = sli4_sid_from_fc_hdr(fc_hdr);
19221         tot_len = 0;
19222         /* Get an iocbq struct to fill in. */
19223         first_iocbq = lpfc_sli_get_iocbq(vport->phba);
19224         if (first_iocbq) {
19225                 /* Initialize the first IOCB. */
19226                 first_iocbq->wcqe_cmpl.total_data_placed = 0;
19227                 bf_set(lpfc_wcqe_c_status, &first_iocbq->wcqe_cmpl,
19228                        IOSTAT_SUCCESS);
19229                 first_iocbq->vport = vport;
19230
19231                 /* Check FC Header to see what TYPE of frame we are rcv'ing */
19232                 if (sli4_type_from_fc_hdr(fc_hdr) == FC_TYPE_ELS) {
19233                         bf_set(els_rsp64_sid, &first_iocbq->wqe.xmit_els_rsp,
19234                                sli4_did_from_fc_hdr(fc_hdr));
19235                 }
19236
19237                 bf_set(wqe_ctxt_tag, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19238                        NO_XRI);
19239                 bf_set(wqe_rcvoxid, &first_iocbq->wqe.xmit_els_rsp.wqe_com,
19240                        be16_to_cpu(fc_hdr->fh_ox_id));
19241
19242                 /* put the first buffer into the first iocb */
19243                 tot_len = bf_get(lpfc_rcqe_length,
19244                                  &seq_dmabuf->cq_event.cqe.rcqe_cmpl);
19245
19246                 first_iocbq->cmd_dmabuf = &seq_dmabuf->dbuf;
19247                 first_iocbq->bpl_dmabuf = NULL;
19248                 /* Keep track of the BDE count */
19249                 first_iocbq->wcqe_cmpl.word3 = 1;
19250
19251                 if (tot_len > LPFC_DATA_BUF_SIZE)
19252                         first_iocbq->wqe.gen_req.bde.tus.f.bdeSize =
19253                                 LPFC_DATA_BUF_SIZE;
19254                 else
19255                         first_iocbq->wqe.gen_req.bde.tus.f.bdeSize = tot_len;
19256
19257                 first_iocbq->wcqe_cmpl.total_data_placed = tot_len;
19258                 bf_set(wqe_els_did, &first_iocbq->wqe.xmit_els_rsp.wqe_dest,
19259                        sid);
19260         }
19261         iocbq = first_iocbq;
19262         /*
19263          * Each IOCBq can have two Buffers assigned, so go through the list
19264          * of buffers for this sequence and save two buffers in each IOCBq
19265          */
19266         list_for_each_entry_safe(d_buf, n_buf, &seq_dmabuf->dbuf.list, list) {
19267                 if (!iocbq) {
19268                         lpfc_in_buf_free(vport->phba, d_buf);
19269                         continue;
19270                 }
19271                 if (!iocbq->bpl_dmabuf) {
19272                         iocbq->bpl_dmabuf = d_buf;
19273                         iocbq->wcqe_cmpl.word3++;
19274                         /* We need to get the size out of the right CQE */
19275                         hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19276                         len = bf_get(lpfc_rcqe_length,
19277                                        &hbq_buf->cq_event.cqe.rcqe_cmpl);
19278                         iocbq->unsol_rcv_len = len;
19279                         iocbq->wcqe_cmpl.total_data_placed += len;
19280                         tot_len += len;
19281                 } else {
19282                         iocbq = lpfc_sli_get_iocbq(vport->phba);
19283                         if (!iocbq) {
19284                                 if (first_iocbq) {
19285                                         bf_set(lpfc_wcqe_c_status,
19286                                                &first_iocbq->wcqe_cmpl,
19287                                                IOSTAT_SUCCESS);
19288                                         first_iocbq->wcqe_cmpl.parameter =
19289                                                 IOERR_NO_RESOURCES;
19290                                 }
19291                                 lpfc_in_buf_free(vport->phba, d_buf);
19292                                 continue;
19293                         }
19294                         /* We need to get the size out of the right CQE */
19295                         hbq_buf = container_of(d_buf, struct hbq_dmabuf, dbuf);
19296                         len = bf_get(lpfc_rcqe_length,
19297                                        &hbq_buf->cq_event.cqe.rcqe_cmpl);
19298                         iocbq->cmd_dmabuf = d_buf;
19299                         iocbq->bpl_dmabuf = NULL;
19300                         iocbq->wcqe_cmpl.word3 = 1;
19301
19302                         if (len > LPFC_DATA_BUF_SIZE)
19303                                 iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19304                                         LPFC_DATA_BUF_SIZE;
19305                         else
19306                                 iocbq->wqe.xmit_els_rsp.bde.tus.f.bdeSize =
19307                                         len;
19308
19309                         tot_len += len;
19310                         iocbq->wcqe_cmpl.total_data_placed = tot_len;
19311                         bf_set(wqe_els_did, &iocbq->wqe.xmit_els_rsp.wqe_dest,
19312                                sid);
19313                         list_add_tail(&iocbq->list, &first_iocbq->list);
19314                 }
19315         }
19316         /* Free the sequence's header buffer */
19317         if (!first_iocbq)
19318                 lpfc_in_buf_free(vport->phba, &seq_dmabuf->dbuf);
19319
19320         return first_iocbq;
19321 }
19322
19323 static void
19324 lpfc_sli4_send_seq_to_ulp(struct lpfc_vport *vport,
19325                           struct hbq_dmabuf *seq_dmabuf)
19326 {
19327         struct fc_frame_header *fc_hdr;
19328         struct lpfc_iocbq *iocbq, *curr_iocb, *next_iocb;
19329         struct lpfc_hba *phba = vport->phba;
19330
19331         fc_hdr = (struct fc_frame_header *)seq_dmabuf->hbuf.virt;
19332         iocbq = lpfc_prep_seq(vport, seq_dmabuf);
19333         if (!iocbq) {
19334                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19335                                 "2707 Ring %d handler: Failed to allocate "
19336                                 "iocb Rctl x%x Type x%x received\n",
19337                                 LPFC_ELS_RING,
19338                                 fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19339                 return;
19340         }
19341         if (!lpfc_complete_unsol_iocb(phba,
19342                                       phba->sli4_hba.els_wq->pring,
19343                                       iocbq, fc_hdr->fh_r_ctl,
19344                                       fc_hdr->fh_type)) {
19345                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19346                                 "2540 Ring %d handler: unexpected Rctl "
19347                                 "x%x Type x%x received\n",
19348                                 LPFC_ELS_RING,
19349                                 fc_hdr->fh_r_ctl, fc_hdr->fh_type);
19350                 lpfc_in_buf_free(phba, &seq_dmabuf->dbuf);
19351         }
19352
19353         /* Free iocb created in lpfc_prep_seq */
19354         list_for_each_entry_safe(curr_iocb, next_iocb,
19355                                  &iocbq->list, list) {
19356                 list_del_init(&curr_iocb->list);
19357                 lpfc_sli_release_iocbq(phba, curr_iocb);
19358         }
19359         lpfc_sli_release_iocbq(phba, iocbq);
19360 }
19361
19362 static void
19363 lpfc_sli4_mds_loopback_cmpl(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
19364                             struct lpfc_iocbq *rspiocb)
19365 {
19366         struct lpfc_dmabuf *pcmd = cmdiocb->cmd_dmabuf;
19367
19368         if (pcmd && pcmd->virt)
19369                 dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19370         kfree(pcmd);
19371         lpfc_sli_release_iocbq(phba, cmdiocb);
19372         lpfc_drain_txq(phba);
19373 }
19374
19375 static void
19376 lpfc_sli4_handle_mds_loopback(struct lpfc_vport *vport,
19377                               struct hbq_dmabuf *dmabuf)
19378 {
19379         struct fc_frame_header *fc_hdr;
19380         struct lpfc_hba *phba = vport->phba;
19381         struct lpfc_iocbq *iocbq = NULL;
19382         union  lpfc_wqe128 *pwqe;
19383         struct lpfc_dmabuf *pcmd = NULL;
19384         uint32_t frame_len;
19385         int rc;
19386         unsigned long iflags;
19387
19388         fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19389         frame_len = bf_get(lpfc_rcqe_length, &dmabuf->cq_event.cqe.rcqe_cmpl);
19390
19391         /* Send the received frame back */
19392         iocbq = lpfc_sli_get_iocbq(phba);
19393         if (!iocbq) {
19394                 /* Queue cq event and wakeup worker thread to process it */
19395                 spin_lock_irqsave(&phba->hbalock, iflags);
19396                 list_add_tail(&dmabuf->cq_event.list,
19397                               &phba->sli4_hba.sp_queue_event);
19398                 spin_unlock_irqrestore(&phba->hbalock, iflags);
19399                 set_bit(HBA_SP_QUEUE_EVT, &phba->hba_flag);
19400                 lpfc_worker_wake_up(phba);
19401                 return;
19402         }
19403
19404         /* Allocate buffer for command payload */
19405         pcmd = kmalloc(sizeof(struct lpfc_dmabuf), GFP_KERNEL);
19406         if (pcmd)
19407                 pcmd->virt = dma_pool_alloc(phba->lpfc_drb_pool, GFP_KERNEL,
19408                                             &pcmd->phys);
19409         if (!pcmd || !pcmd->virt)
19410                 goto exit;
19411
19412         INIT_LIST_HEAD(&pcmd->list);
19413
19414         /* copyin the payload */
19415         memcpy(pcmd->virt, dmabuf->dbuf.virt, frame_len);
19416
19417         iocbq->cmd_dmabuf = pcmd;
19418         iocbq->vport = vport;
19419         iocbq->cmd_flag &= ~LPFC_FIP_ELS_ID_MASK;
19420         iocbq->cmd_flag |= LPFC_USE_FCPWQIDX;
19421         iocbq->num_bdes = 0;
19422
19423         pwqe = &iocbq->wqe;
19424         /* fill in BDE's for command */
19425         pwqe->gen_req.bde.addrHigh = putPaddrHigh(pcmd->phys);
19426         pwqe->gen_req.bde.addrLow = putPaddrLow(pcmd->phys);
19427         pwqe->gen_req.bde.tus.f.bdeSize = frame_len;
19428         pwqe->gen_req.bde.tus.f.bdeFlags = BUFF_TYPE_BDE_64;
19429
19430         pwqe->send_frame.frame_len = frame_len;
19431         pwqe->send_frame.fc_hdr_wd0 = be32_to_cpu(*((__be32 *)fc_hdr));
19432         pwqe->send_frame.fc_hdr_wd1 = be32_to_cpu(*((__be32 *)fc_hdr + 1));
19433         pwqe->send_frame.fc_hdr_wd2 = be32_to_cpu(*((__be32 *)fc_hdr + 2));
19434         pwqe->send_frame.fc_hdr_wd3 = be32_to_cpu(*((__be32 *)fc_hdr + 3));
19435         pwqe->send_frame.fc_hdr_wd4 = be32_to_cpu(*((__be32 *)fc_hdr + 4));
19436         pwqe->send_frame.fc_hdr_wd5 = be32_to_cpu(*((__be32 *)fc_hdr + 5));
19437
19438         pwqe->generic.wqe_com.word7 = 0;
19439         pwqe->generic.wqe_com.word10 = 0;
19440
19441         bf_set(wqe_cmnd, &pwqe->generic.wqe_com, CMD_SEND_FRAME);
19442         bf_set(wqe_sof, &pwqe->generic.wqe_com, 0x2E); /* SOF byte */
19443         bf_set(wqe_eof, &pwqe->generic.wqe_com, 0x41); /* EOF byte */
19444         bf_set(wqe_lenloc, &pwqe->generic.wqe_com, 1);
19445         bf_set(wqe_xbl, &pwqe->generic.wqe_com, 1);
19446         bf_set(wqe_dbde, &pwqe->generic.wqe_com, 1);
19447         bf_set(wqe_xc, &pwqe->generic.wqe_com, 1);
19448         bf_set(wqe_cmd_type, &pwqe->generic.wqe_com, 0xA);
19449         bf_set(wqe_cqid, &pwqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
19450         bf_set(wqe_xri_tag, &pwqe->generic.wqe_com, iocbq->sli4_xritag);
19451         bf_set(wqe_reqtag, &pwqe->generic.wqe_com, iocbq->iotag);
19452         bf_set(wqe_class, &pwqe->generic.wqe_com, CLASS3);
19453         pwqe->generic.wqe_com.abort_tag = iocbq->iotag;
19454
19455         iocbq->cmd_cmpl = lpfc_sli4_mds_loopback_cmpl;
19456
19457         rc = lpfc_sli_issue_iocb(phba, LPFC_ELS_RING, iocbq, 0);
19458         if (rc == IOCB_ERROR)
19459                 goto exit;
19460
19461         lpfc_in_buf_free(phba, &dmabuf->dbuf);
19462         return;
19463
19464 exit:
19465         lpfc_printf_log(phba, KERN_WARNING, LOG_SLI,
19466                         "2023 Unable to process MDS loopback frame\n");
19467         if (pcmd && pcmd->virt)
19468                 dma_pool_free(phba->lpfc_drb_pool, pcmd->virt, pcmd->phys);
19469         kfree(pcmd);
19470         if (iocbq)
19471                 lpfc_sli_release_iocbq(phba, iocbq);
19472         lpfc_in_buf_free(phba, &dmabuf->dbuf);
19473 }
19474
19475 /**
19476  * lpfc_sli4_handle_received_buffer - Handle received buffers from firmware
19477  * @phba: Pointer to HBA context object.
19478  * @dmabuf: Pointer to a dmabuf that describes the FC sequence.
19479  *
19480  * This function is called with no lock held. This function processes all
19481  * the received buffers and gives it to upper layers when a received buffer
19482  * indicates that it is the final frame in the sequence. The interrupt
19483  * service routine processes received buffers at interrupt contexts.
19484  * Worker thread calls lpfc_sli4_handle_received_buffer, which will call the
19485  * appropriate receive function when the final frame in a sequence is received.
19486  **/
19487 void
19488 lpfc_sli4_handle_received_buffer(struct lpfc_hba *phba,
19489                                  struct hbq_dmabuf *dmabuf)
19490 {
19491         struct hbq_dmabuf *seq_dmabuf;
19492         struct fc_frame_header *fc_hdr;
19493         struct lpfc_vport *vport;
19494         uint32_t fcfi;
19495         uint32_t did;
19496
19497         /* Process each received buffer */
19498         fc_hdr = (struct fc_frame_header *)dmabuf->hbuf.virt;
19499
19500         if (fc_hdr->fh_r_ctl == FC_RCTL_MDS_DIAGS ||
19501             fc_hdr->fh_r_ctl == FC_RCTL_DD_UNSOL_DATA) {
19502                 vport = phba->pport;
19503                 /* Handle MDS Loopback frames */
19504                 if  (!test_bit(FC_UNLOADING, &phba->pport->load_flag))
19505                         lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19506                 else
19507                         lpfc_in_buf_free(phba, &dmabuf->dbuf);
19508                 return;
19509         }
19510
19511         /* check to see if this a valid type of frame */
19512         if (lpfc_fc_frame_check(phba, fc_hdr)) {
19513                 lpfc_in_buf_free(phba, &dmabuf->dbuf);
19514                 return;
19515         }
19516
19517         if ((bf_get(lpfc_cqe_code,
19518                     &dmabuf->cq_event.cqe.rcqe_cmpl) == CQE_CODE_RECEIVE_V1))
19519                 fcfi = bf_get(lpfc_rcqe_fcf_id_v1,
19520                               &dmabuf->cq_event.cqe.rcqe_cmpl);
19521         else
19522                 fcfi = bf_get(lpfc_rcqe_fcf_id,
19523                               &dmabuf->cq_event.cqe.rcqe_cmpl);
19524
19525         if (fc_hdr->fh_r_ctl == 0xF4 && fc_hdr->fh_type == 0xFF) {
19526                 vport = phba->pport;
19527                 lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
19528                                 "2023 MDS Loopback %d bytes\n",
19529                                 bf_get(lpfc_rcqe_length,
19530                                        &dmabuf->cq_event.cqe.rcqe_cmpl));
19531                 /* Handle MDS Loopback frames */
19532                 lpfc_sli4_handle_mds_loopback(vport, dmabuf);
19533                 return;
19534         }
19535
19536         /* d_id this frame is directed to */
19537         did = sli4_did_from_fc_hdr(fc_hdr);
19538
19539         vport = lpfc_fc_frame_to_vport(phba, fc_hdr, fcfi, did);
19540         if (!vport) {
19541                 /* throw out the frame */
19542                 lpfc_in_buf_free(phba, &dmabuf->dbuf);
19543                 return;
19544         }
19545
19546         /* vport is registered unless we rcv a FLOGI directed to Fabric_DID */
19547         if (!(vport->vpi_state & LPFC_VPI_REGISTERED) &&
19548                 (did != Fabric_DID)) {
19549                 /*
19550                  * Throw out the frame if we are not pt2pt.
19551                  * The pt2pt protocol allows for discovery frames
19552                  * to be received without a registered VPI.
19553                  */
19554                 if (!test_bit(FC_PT2PT, &vport->fc_flag) ||
19555                     phba->link_state == LPFC_HBA_READY) {
19556                         lpfc_in_buf_free(phba, &dmabuf->dbuf);
19557                         return;
19558                 }
19559         }
19560
19561         /* Handle the basic abort sequence (BA_ABTS) event */
19562         if (fc_hdr->fh_r_ctl == FC_RCTL_BA_ABTS) {
19563                 lpfc_sli4_handle_unsol_abort(vport, dmabuf);
19564                 return;
19565         }
19566
19567         /* Link this frame */
19568         seq_dmabuf = lpfc_fc_frame_add(vport, dmabuf);
19569         if (!seq_dmabuf) {
19570                 /* unable to add frame to vport - throw it out */
19571                 lpfc_in_buf_free(phba, &dmabuf->dbuf);
19572                 return;
19573         }
19574         /* If not last frame in sequence continue processing frames. */
19575         if (!lpfc_seq_complete(seq_dmabuf))
19576                 return;
19577
19578         /* Send the complete sequence to the upper layer protocol */
19579         lpfc_sli4_send_seq_to_ulp(vport, seq_dmabuf);
19580 }
19581
19582 /**
19583  * lpfc_sli4_post_all_rpi_hdrs - Post the rpi header memory region to the port
19584  * @phba: pointer to lpfc hba data structure.
19585  *
19586  * This routine is invoked to post rpi header templates to the
19587  * HBA consistent with the SLI-4 interface spec.  This routine
19588  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19589  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19590  *
19591  * This routine does not require any locks.  It's usage is expected
19592  * to be driver load or reset recovery when the driver is
19593  * sequential.
19594  *
19595  * Return codes
19596  *      0 - successful
19597  *      -EIO - The mailbox failed to complete successfully.
19598  *      When this error occurs, the driver is not guaranteed
19599  *      to have any rpi regions posted to the device and
19600  *      must either attempt to repost the regions or take a
19601  *      fatal error.
19602  **/
19603 int
19604 lpfc_sli4_post_all_rpi_hdrs(struct lpfc_hba *phba)
19605 {
19606         struct lpfc_rpi_hdr *rpi_page;
19607         uint32_t rc = 0;
19608         uint16_t lrpi = 0;
19609
19610         /* SLI4 ports that support extents do not require RPI headers. */
19611         if (!phba->sli4_hba.rpi_hdrs_in_use)
19612                 goto exit;
19613         if (phba->sli4_hba.extents_in_use)
19614                 return -EIO;
19615
19616         list_for_each_entry(rpi_page, &phba->sli4_hba.lpfc_rpi_hdr_list, list) {
19617                 /*
19618                  * Assign the rpi headers a physical rpi only if the driver
19619                  * has not initialized those resources.  A port reset only
19620                  * needs the headers posted.
19621                  */
19622                 if (bf_get(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags) !=
19623                     LPFC_RPI_RSRC_RDY)
19624                         rpi_page->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19625
19626                 rc = lpfc_sli4_post_rpi_hdr(phba, rpi_page);
19627                 if (rc != MBX_SUCCESS) {
19628                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19629                                         "2008 Error %d posting all rpi "
19630                                         "headers\n", rc);
19631                         rc = -EIO;
19632                         break;
19633                 }
19634         }
19635
19636  exit:
19637         bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags,
19638                LPFC_RPI_RSRC_RDY);
19639         return rc;
19640 }
19641
19642 /**
19643  * lpfc_sli4_post_rpi_hdr - Post an rpi header memory region to the port
19644  * @phba: pointer to lpfc hba data structure.
19645  * @rpi_page:  pointer to the rpi memory region.
19646  *
19647  * This routine is invoked to post a single rpi header to the
19648  * HBA consistent with the SLI-4 interface spec.  This memory region
19649  * maps up to 64 rpi context regions.
19650  *
19651  * Return codes
19652  *      0 - successful
19653  *      -ENOMEM - No available memory
19654  *      -EIO - The mailbox failed to complete successfully.
19655  **/
19656 int
19657 lpfc_sli4_post_rpi_hdr(struct lpfc_hba *phba, struct lpfc_rpi_hdr *rpi_page)
19658 {
19659         LPFC_MBOXQ_t *mboxq;
19660         struct lpfc_mbx_post_hdr_tmpl *hdr_tmpl;
19661         uint32_t rc = 0;
19662         uint32_t shdr_status, shdr_add_status;
19663         union lpfc_sli4_cfg_shdr *shdr;
19664
19665         /* SLI4 ports that support extents do not require RPI headers. */
19666         if (!phba->sli4_hba.rpi_hdrs_in_use)
19667                 return rc;
19668         if (phba->sli4_hba.extents_in_use)
19669                 return -EIO;
19670
19671         /* The port is notified of the header region via a mailbox command. */
19672         mboxq = (LPFC_MBOXQ_t *) mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19673         if (!mboxq) {
19674                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19675                                 "2001 Unable to allocate memory for issuing "
19676                                 "SLI_CONFIG_SPECIAL mailbox command\n");
19677                 return -ENOMEM;
19678         }
19679
19680         /* Post all rpi memory regions to the port. */
19681         hdr_tmpl = &mboxq->u.mqe.un.hdr_tmpl;
19682         lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
19683                          LPFC_MBOX_OPCODE_FCOE_POST_HDR_TEMPLATE,
19684                          sizeof(struct lpfc_mbx_post_hdr_tmpl) -
19685                          sizeof(struct lpfc_sli4_cfg_mhdr),
19686                          LPFC_SLI4_MBX_EMBED);
19687
19688
19689         /* Post the physical rpi to the port for this rpi header. */
19690         bf_set(lpfc_mbx_post_hdr_tmpl_rpi_offset, hdr_tmpl,
19691                rpi_page->start_rpi);
19692         bf_set(lpfc_mbx_post_hdr_tmpl_page_cnt,
19693                hdr_tmpl, rpi_page->page_count);
19694
19695         hdr_tmpl->rpi_paddr_lo = putPaddrLow(rpi_page->dmabuf->phys);
19696         hdr_tmpl->rpi_paddr_hi = putPaddrHigh(rpi_page->dmabuf->phys);
19697         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
19698         shdr = (union lpfc_sli4_cfg_shdr *) &hdr_tmpl->header.cfg_shdr;
19699         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19700         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19701         mempool_free(mboxq, phba->mbox_mem_pool);
19702         if (shdr_status || shdr_add_status || rc) {
19703                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19704                                 "2514 POST_RPI_HDR mailbox failed with "
19705                                 "status x%x add_status x%x, mbx status x%x\n",
19706                                 shdr_status, shdr_add_status, rc);
19707                 rc = -ENXIO;
19708         } else {
19709                 /*
19710                  * The next_rpi stores the next logical module-64 rpi value used
19711                  * to post physical rpis in subsequent rpi postings.
19712                  */
19713                 spin_lock_irq(&phba->hbalock);
19714                 phba->sli4_hba.next_rpi = rpi_page->next_rpi;
19715                 spin_unlock_irq(&phba->hbalock);
19716         }
19717         return rc;
19718 }
19719
19720 /**
19721  * lpfc_sli4_alloc_rpi - Get an available rpi in the device's range
19722  * @phba: pointer to lpfc hba data structure.
19723  *
19724  * This routine is invoked to post rpi header templates to the
19725  * HBA consistent with the SLI-4 interface spec.  This routine
19726  * posts a SLI4_PAGE_SIZE memory region to the port to hold up to
19727  * SLI4_PAGE_SIZE modulo 64 rpi context headers.
19728  *
19729  * Returns
19730  *      A nonzero rpi defined as rpi_base <= rpi < max_rpi if successful
19731  *      LPFC_RPI_ALLOC_ERROR if no rpis are available.
19732  **/
19733 int
19734 lpfc_sli4_alloc_rpi(struct lpfc_hba *phba)
19735 {
19736         unsigned long rpi;
19737         uint16_t max_rpi, rpi_limit;
19738         uint16_t rpi_remaining, lrpi = 0;
19739         struct lpfc_rpi_hdr *rpi_hdr;
19740         unsigned long iflag;
19741
19742         /*
19743          * Fetch the next logical rpi.  Because this index is logical,
19744          * the  driver starts at 0 each time.
19745          */
19746         spin_lock_irqsave(&phba->hbalock, iflag);
19747         max_rpi = phba->sli4_hba.max_cfg_param.max_rpi;
19748         rpi_limit = phba->sli4_hba.next_rpi;
19749
19750         rpi = find_first_zero_bit(phba->sli4_hba.rpi_bmask, rpi_limit);
19751         if (rpi >= rpi_limit)
19752                 rpi = LPFC_RPI_ALLOC_ERROR;
19753         else {
19754                 set_bit(rpi, phba->sli4_hba.rpi_bmask);
19755                 phba->sli4_hba.max_cfg_param.rpi_used++;
19756                 phba->sli4_hba.rpi_count++;
19757         }
19758         lpfc_printf_log(phba, KERN_INFO,
19759                         LOG_NODE | LOG_DISCOVERY,
19760                         "0001 Allocated rpi:x%x max:x%x lim:x%x\n",
19761                         (int) rpi, max_rpi, rpi_limit);
19762
19763         /*
19764          * Don't try to allocate more rpi header regions if the device limit
19765          * has been exhausted.
19766          */
19767         if ((rpi == LPFC_RPI_ALLOC_ERROR) &&
19768             (phba->sli4_hba.rpi_count >= max_rpi)) {
19769                 spin_unlock_irqrestore(&phba->hbalock, iflag);
19770                 return rpi;
19771         }
19772
19773         /*
19774          * RPI header postings are not required for SLI4 ports capable of
19775          * extents.
19776          */
19777         if (!phba->sli4_hba.rpi_hdrs_in_use) {
19778                 spin_unlock_irqrestore(&phba->hbalock, iflag);
19779                 return rpi;
19780         }
19781
19782         /*
19783          * If the driver is running low on rpi resources, allocate another
19784          * page now.  Note that the next_rpi value is used because
19785          * it represents how many are actually in use whereas max_rpi notes
19786          * how many are supported max by the device.
19787          */
19788         rpi_remaining = phba->sli4_hba.next_rpi - phba->sli4_hba.rpi_count;
19789         spin_unlock_irqrestore(&phba->hbalock, iflag);
19790         if (rpi_remaining < LPFC_RPI_LOW_WATER_MARK) {
19791                 rpi_hdr = lpfc_sli4_create_rpi_hdr(phba);
19792                 if (!rpi_hdr) {
19793                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19794                                         "2002 Error Could not grow rpi "
19795                                         "count\n");
19796                 } else {
19797                         lrpi = rpi_hdr->start_rpi;
19798                         rpi_hdr->start_rpi = phba->sli4_hba.rpi_ids[lrpi];
19799                         lpfc_sli4_post_rpi_hdr(phba, rpi_hdr);
19800                 }
19801         }
19802
19803         return rpi;
19804 }
19805
19806 /**
19807  * __lpfc_sli4_free_rpi - Release an rpi for reuse.
19808  * @phba: pointer to lpfc hba data structure.
19809  * @rpi: rpi to free
19810  *
19811  * This routine is invoked to release an rpi to the pool of
19812  * available rpis maintained by the driver.
19813  **/
19814 static void
19815 __lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19816 {
19817         /*
19818          * if the rpi value indicates a prior unreg has already
19819          * been done, skip the unreg.
19820          */
19821         if (rpi == LPFC_RPI_ALLOC_ERROR)
19822                 return;
19823
19824         if (test_and_clear_bit(rpi, phba->sli4_hba.rpi_bmask)) {
19825                 phba->sli4_hba.rpi_count--;
19826                 phba->sli4_hba.max_cfg_param.rpi_used--;
19827         } else {
19828                 lpfc_printf_log(phba, KERN_INFO,
19829                                 LOG_NODE | LOG_DISCOVERY,
19830                                 "2016 rpi %x not inuse\n",
19831                                 rpi);
19832         }
19833 }
19834
19835 /**
19836  * lpfc_sli4_free_rpi - Release an rpi for reuse.
19837  * @phba: pointer to lpfc hba data structure.
19838  * @rpi: rpi to free
19839  *
19840  * This routine is invoked to release an rpi to the pool of
19841  * available rpis maintained by the driver.
19842  **/
19843 void
19844 lpfc_sli4_free_rpi(struct lpfc_hba *phba, int rpi)
19845 {
19846         spin_lock_irq(&phba->hbalock);
19847         __lpfc_sli4_free_rpi(phba, rpi);
19848         spin_unlock_irq(&phba->hbalock);
19849 }
19850
19851 /**
19852  * lpfc_sli4_remove_rpis - Remove the rpi bitmask region
19853  * @phba: pointer to lpfc hba data structure.
19854  *
19855  * This routine is invoked to remove the memory region that
19856  * provided rpi via a bitmask.
19857  **/
19858 void
19859 lpfc_sli4_remove_rpis(struct lpfc_hba *phba)
19860 {
19861         kfree(phba->sli4_hba.rpi_bmask);
19862         kfree(phba->sli4_hba.rpi_ids);
19863         bf_set(lpfc_rpi_rsrc_rdy, &phba->sli4_hba.sli4_flags, 0);
19864 }
19865
19866 /**
19867  * lpfc_sli4_resume_rpi - Remove the rpi bitmask region
19868  * @ndlp: pointer to lpfc nodelist data structure.
19869  * @cmpl: completion call-back.
19870  * @iocbq: data to load as mbox ctx_u information
19871  *
19872  * This routine is invoked to remove the memory region that
19873  * provided rpi via a bitmask.
19874  **/
19875 int
19876 lpfc_sli4_resume_rpi(struct lpfc_nodelist *ndlp,
19877                      void (*cmpl)(struct lpfc_hba *, LPFC_MBOXQ_t *),
19878                      struct lpfc_iocbq *iocbq)
19879 {
19880         LPFC_MBOXQ_t *mboxq;
19881         struct lpfc_hba *phba = ndlp->phba;
19882         int rc;
19883
19884         /* The port is notified of the header region via a mailbox command. */
19885         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19886         if (!mboxq)
19887                 return -ENOMEM;
19888
19889         /* If cmpl assigned, then this nlp_get pairs with
19890          * lpfc_mbx_cmpl_resume_rpi.
19891          *
19892          * Else cmpl is NULL, then this nlp_get pairs with
19893          * lpfc_sli_def_mbox_cmpl.
19894          */
19895         if (!lpfc_nlp_get(ndlp)) {
19896                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19897                                 "2122 %s: Failed to get nlp ref\n",
19898                                 __func__);
19899                 mempool_free(mboxq, phba->mbox_mem_pool);
19900                 return -EIO;
19901         }
19902
19903         /* Post all rpi memory regions to the port. */
19904         lpfc_resume_rpi(mboxq, ndlp);
19905         if (cmpl) {
19906                 mboxq->mbox_cmpl = cmpl;
19907                 mboxq->ctx_u.save_iocb = iocbq;
19908         } else
19909                 mboxq->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
19910         mboxq->ctx_ndlp = ndlp;
19911         mboxq->vport = ndlp->vport;
19912         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
19913         if (rc == MBX_NOT_FINISHED) {
19914                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19915                                 "2010 Resume RPI Mailbox failed "
19916                                 "status %d, mbxStatus x%x\n", rc,
19917                                 bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19918                 lpfc_nlp_put(ndlp);
19919                 mempool_free(mboxq, phba->mbox_mem_pool);
19920                 return -EIO;
19921         }
19922         return 0;
19923 }
19924
19925 /**
19926  * lpfc_sli4_init_vpi - Initialize a vpi with the port
19927  * @vport: Pointer to the vport for which the vpi is being initialized
19928  *
19929  * This routine is invoked to activate a vpi with the port.
19930  *
19931  * Returns:
19932  *    0 success
19933  *    -Evalue otherwise
19934  **/
19935 int
19936 lpfc_sli4_init_vpi(struct lpfc_vport *vport)
19937 {
19938         LPFC_MBOXQ_t *mboxq;
19939         int rc = 0;
19940         int retval = MBX_SUCCESS;
19941         uint32_t mbox_tmo;
19942         struct lpfc_hba *phba = vport->phba;
19943         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
19944         if (!mboxq)
19945                 return -ENOMEM;
19946         lpfc_init_vpi(phba, mboxq, vport->vpi);
19947         mbox_tmo = lpfc_mbox_tmo_val(phba, mboxq);
19948         rc = lpfc_sli_issue_mbox_wait(phba, mboxq, mbox_tmo);
19949         if (rc != MBX_SUCCESS) {
19950                 lpfc_printf_vlog(vport, KERN_ERR, LOG_TRACE_EVENT,
19951                                 "2022 INIT VPI Mailbox failed "
19952                                 "status %d, mbxStatus x%x\n", rc,
19953                                 bf_get(lpfc_mqe_status, &mboxq->u.mqe));
19954                 retval = -EIO;
19955         }
19956         if (rc != MBX_TIMEOUT)
19957                 mempool_free(mboxq, vport->phba->mbox_mem_pool);
19958
19959         return retval;
19960 }
19961
19962 /**
19963  * lpfc_mbx_cmpl_add_fcf_record - add fcf mbox completion handler.
19964  * @phba: pointer to lpfc hba data structure.
19965  * @mboxq: Pointer to mailbox object.
19966  *
19967  * This routine is invoked to manually add a single FCF record. The caller
19968  * must pass a completely initialized FCF_Record.  This routine takes
19969  * care of the nonembedded mailbox operations.
19970  **/
19971 static void
19972 lpfc_mbx_cmpl_add_fcf_record(struct lpfc_hba *phba, LPFC_MBOXQ_t *mboxq)
19973 {
19974         void *virt_addr;
19975         union lpfc_sli4_cfg_shdr *shdr;
19976         uint32_t shdr_status, shdr_add_status;
19977
19978         virt_addr = mboxq->sge_array->addr[0];
19979         /* The IOCTL status is embedded in the mailbox subheader. */
19980         shdr = (union lpfc_sli4_cfg_shdr *) virt_addr;
19981         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
19982         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
19983
19984         if ((shdr_status || shdr_add_status) &&
19985                 (shdr_status != STATUS_FCF_IN_USE))
19986                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
19987                         "2558 ADD_FCF_RECORD mailbox failed with "
19988                         "status x%x add_status x%x\n",
19989                         shdr_status, shdr_add_status);
19990
19991         lpfc_sli4_mbox_cmd_free(phba, mboxq);
19992 }
19993
19994 /**
19995  * lpfc_sli4_add_fcf_record - Manually add an FCF Record.
19996  * @phba: pointer to lpfc hba data structure.
19997  * @fcf_record:  pointer to the initialized fcf record to add.
19998  *
19999  * This routine is invoked to manually add a single FCF record. The caller
20000  * must pass a completely initialized FCF_Record.  This routine takes
20001  * care of the nonembedded mailbox operations.
20002  **/
20003 int
20004 lpfc_sli4_add_fcf_record(struct lpfc_hba *phba, struct fcf_record *fcf_record)
20005 {
20006         int rc = 0;
20007         LPFC_MBOXQ_t *mboxq;
20008         uint8_t *bytep;
20009         void *virt_addr;
20010         struct lpfc_mbx_sge sge;
20011         uint32_t alloc_len, req_len;
20012         uint32_t fcfindex;
20013
20014         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20015         if (!mboxq) {
20016                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20017                         "2009 Failed to allocate mbox for ADD_FCF cmd\n");
20018                 return -ENOMEM;
20019         }
20020
20021         req_len = sizeof(struct fcf_record) + sizeof(union lpfc_sli4_cfg_shdr) +
20022                   sizeof(uint32_t);
20023
20024         /* Allocate DMA memory and set up the non-embedded mailbox command */
20025         alloc_len = lpfc_sli4_config(phba, mboxq, LPFC_MBOX_SUBSYSTEM_FCOE,
20026                                      LPFC_MBOX_OPCODE_FCOE_ADD_FCF,
20027                                      req_len, LPFC_SLI4_MBX_NEMBED);
20028         if (alloc_len < req_len) {
20029                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20030                         "2523 Allocated DMA memory size (x%x) is "
20031                         "less than the requested DMA memory "
20032                         "size (x%x)\n", alloc_len, req_len);
20033                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
20034                 return -ENOMEM;
20035         }
20036
20037         /*
20038          * Get the first SGE entry from the non-embedded DMA memory.  This
20039          * routine only uses a single SGE.
20040          */
20041         lpfc_sli4_mbx_sge_get(mboxq, 0, &sge);
20042         virt_addr = mboxq->sge_array->addr[0];
20043         /*
20044          * Configure the FCF record for FCFI 0.  This is the driver's
20045          * hardcoded default and gets used in nonFIP mode.
20046          */
20047         fcfindex = bf_get(lpfc_fcf_record_fcf_index, fcf_record);
20048         bytep = virt_addr + sizeof(union lpfc_sli4_cfg_shdr);
20049         lpfc_sli_pcimem_bcopy(&fcfindex, bytep, sizeof(uint32_t));
20050
20051         /*
20052          * Copy the fcf_index and the FCF Record Data. The data starts after
20053          * the FCoE header plus word10. The data copy needs to be endian
20054          * correct.
20055          */
20056         bytep += sizeof(uint32_t);
20057         lpfc_sli_pcimem_bcopy(fcf_record, bytep, sizeof(struct fcf_record));
20058         mboxq->vport = phba->pport;
20059         mboxq->mbox_cmpl = lpfc_mbx_cmpl_add_fcf_record;
20060         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20061         if (rc == MBX_NOT_FINISHED) {
20062                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20063                         "2515 ADD_FCF_RECORD mailbox failed with "
20064                         "status 0x%x\n", rc);
20065                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
20066                 rc = -EIO;
20067         } else
20068                 rc = 0;
20069
20070         return rc;
20071 }
20072
20073 /**
20074  * lpfc_sli4_build_dflt_fcf_record - Build the driver's default FCF Record.
20075  * @phba: pointer to lpfc hba data structure.
20076  * @fcf_record:  pointer to the fcf record to write the default data.
20077  * @fcf_index: FCF table entry index.
20078  *
20079  * This routine is invoked to build the driver's default FCF record.  The
20080  * values used are hardcoded.  This routine handles memory initialization.
20081  *
20082  **/
20083 void
20084 lpfc_sli4_build_dflt_fcf_record(struct lpfc_hba *phba,
20085                                 struct fcf_record *fcf_record,
20086                                 uint16_t fcf_index)
20087 {
20088         memset(fcf_record, 0, sizeof(struct fcf_record));
20089         fcf_record->max_rcv_size = LPFC_FCOE_MAX_RCV_SIZE;
20090         fcf_record->fka_adv_period = LPFC_FCOE_FKA_ADV_PER;
20091         fcf_record->fip_priority = LPFC_FCOE_FIP_PRIORITY;
20092         bf_set(lpfc_fcf_record_mac_0, fcf_record, phba->fc_map[0]);
20093         bf_set(lpfc_fcf_record_mac_1, fcf_record, phba->fc_map[1]);
20094         bf_set(lpfc_fcf_record_mac_2, fcf_record, phba->fc_map[2]);
20095         bf_set(lpfc_fcf_record_mac_3, fcf_record, LPFC_FCOE_FCF_MAC3);
20096         bf_set(lpfc_fcf_record_mac_4, fcf_record, LPFC_FCOE_FCF_MAC4);
20097         bf_set(lpfc_fcf_record_mac_5, fcf_record, LPFC_FCOE_FCF_MAC5);
20098         bf_set(lpfc_fcf_record_fc_map_0, fcf_record, phba->fc_map[0]);
20099         bf_set(lpfc_fcf_record_fc_map_1, fcf_record, phba->fc_map[1]);
20100         bf_set(lpfc_fcf_record_fc_map_2, fcf_record, phba->fc_map[2]);
20101         bf_set(lpfc_fcf_record_fcf_valid, fcf_record, 1);
20102         bf_set(lpfc_fcf_record_fcf_avail, fcf_record, 1);
20103         bf_set(lpfc_fcf_record_fcf_index, fcf_record, fcf_index);
20104         bf_set(lpfc_fcf_record_mac_addr_prov, fcf_record,
20105                 LPFC_FCF_FPMA | LPFC_FCF_SPMA);
20106         /* Set the VLAN bit map */
20107         if (phba->valid_vlan) {
20108                 fcf_record->vlan_bitmap[phba->vlan_id / 8]
20109                         = 1 << (phba->vlan_id % 8);
20110         }
20111 }
20112
20113 /**
20114  * lpfc_sli4_fcf_scan_read_fcf_rec - Read hba fcf record for fcf scan.
20115  * @phba: pointer to lpfc hba data structure.
20116  * @fcf_index: FCF table entry offset.
20117  *
20118  * This routine is invoked to scan the entire FCF table by reading FCF
20119  * record and processing it one at a time starting from the @fcf_index
20120  * for initial FCF discovery or fast FCF failover rediscovery.
20121  *
20122  * Return 0 if the mailbox command is submitted successfully, none 0
20123  * otherwise.
20124  **/
20125 int
20126 lpfc_sli4_fcf_scan_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20127 {
20128         int rc = 0, error;
20129         LPFC_MBOXQ_t *mboxq;
20130
20131         phba->fcoe_eventtag_at_fcf_scan = phba->fcoe_eventtag;
20132         phba->fcoe_cvl_eventtag_attn = phba->fcoe_cvl_eventtag;
20133         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20134         if (!mboxq) {
20135                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20136                                 "2000 Failed to allocate mbox for "
20137                                 "READ_FCF cmd\n");
20138                 error = -ENOMEM;
20139                 goto fail_fcf_scan;
20140         }
20141         /* Construct the read FCF record mailbox command */
20142         rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20143         if (rc) {
20144                 error = -EINVAL;
20145                 goto fail_fcf_scan;
20146         }
20147         /* Issue the mailbox command asynchronously */
20148         mboxq->vport = phba->pport;
20149         mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_scan_read_fcf_rec;
20150
20151         set_bit(FCF_TS_INPROG, &phba->hba_flag);
20152
20153         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20154         if (rc == MBX_NOT_FINISHED)
20155                 error = -EIO;
20156         else {
20157                 /* Reset eligible FCF count for new scan */
20158                 if (fcf_index == LPFC_FCOE_FCF_GET_FIRST)
20159                         phba->fcf.eligible_fcf_cnt = 0;
20160                 error = 0;
20161         }
20162 fail_fcf_scan:
20163         if (error) {
20164                 if (mboxq)
20165                         lpfc_sli4_mbox_cmd_free(phba, mboxq);
20166                 /* FCF scan failed, clear FCF_TS_INPROG flag */
20167                 clear_bit(FCF_TS_INPROG, &phba->hba_flag);
20168         }
20169         return error;
20170 }
20171
20172 /**
20173  * lpfc_sli4_fcf_rr_read_fcf_rec - Read hba fcf record for roundrobin fcf.
20174  * @phba: pointer to lpfc hba data structure.
20175  * @fcf_index: FCF table entry offset.
20176  *
20177  * This routine is invoked to read an FCF record indicated by @fcf_index
20178  * and to use it for FLOGI roundrobin FCF failover.
20179  *
20180  * Return 0 if the mailbox command is submitted successfully, none 0
20181  * otherwise.
20182  **/
20183 int
20184 lpfc_sli4_fcf_rr_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20185 {
20186         int rc = 0, error;
20187         LPFC_MBOXQ_t *mboxq;
20188
20189         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20190         if (!mboxq) {
20191                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20192                                 "2763 Failed to allocate mbox for "
20193                                 "READ_FCF cmd\n");
20194                 error = -ENOMEM;
20195                 goto fail_fcf_read;
20196         }
20197         /* Construct the read FCF record mailbox command */
20198         rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20199         if (rc) {
20200                 error = -EINVAL;
20201                 goto fail_fcf_read;
20202         }
20203         /* Issue the mailbox command asynchronously */
20204         mboxq->vport = phba->pport;
20205         mboxq->mbox_cmpl = lpfc_mbx_cmpl_fcf_rr_read_fcf_rec;
20206         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20207         if (rc == MBX_NOT_FINISHED)
20208                 error = -EIO;
20209         else
20210                 error = 0;
20211
20212 fail_fcf_read:
20213         if (error && mboxq)
20214                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
20215         return error;
20216 }
20217
20218 /**
20219  * lpfc_sli4_read_fcf_rec - Read hba fcf record for update eligible fcf bmask.
20220  * @phba: pointer to lpfc hba data structure.
20221  * @fcf_index: FCF table entry offset.
20222  *
20223  * This routine is invoked to read an FCF record indicated by @fcf_index to
20224  * determine whether it's eligible for FLOGI roundrobin failover list.
20225  *
20226  * Return 0 if the mailbox command is submitted successfully, none 0
20227  * otherwise.
20228  **/
20229 int
20230 lpfc_sli4_read_fcf_rec(struct lpfc_hba *phba, uint16_t fcf_index)
20231 {
20232         int rc = 0, error;
20233         LPFC_MBOXQ_t *mboxq;
20234
20235         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20236         if (!mboxq) {
20237                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP | LOG_INIT,
20238                                 "2758 Failed to allocate mbox for "
20239                                 "READ_FCF cmd\n");
20240                                 error = -ENOMEM;
20241                                 goto fail_fcf_read;
20242         }
20243         /* Construct the read FCF record mailbox command */
20244         rc = lpfc_sli4_mbx_read_fcf_rec(phba, mboxq, fcf_index);
20245         if (rc) {
20246                 error = -EINVAL;
20247                 goto fail_fcf_read;
20248         }
20249         /* Issue the mailbox command asynchronously */
20250         mboxq->vport = phba->pport;
20251         mboxq->mbox_cmpl = lpfc_mbx_cmpl_read_fcf_rec;
20252         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_NOWAIT);
20253         if (rc == MBX_NOT_FINISHED)
20254                 error = -EIO;
20255         else
20256                 error = 0;
20257
20258 fail_fcf_read:
20259         if (error && mboxq)
20260                 lpfc_sli4_mbox_cmd_free(phba, mboxq);
20261         return error;
20262 }
20263
20264 /**
20265  * lpfc_check_next_fcf_pri_level
20266  * @phba: pointer to the lpfc_hba struct for this port.
20267  * This routine is called from the lpfc_sli4_fcf_rr_next_index_get
20268  * routine when the rr_bmask is empty. The FCF indecies are put into the
20269  * rr_bmask based on their priority level. Starting from the highest priority
20270  * to the lowest. The most likely FCF candidate will be in the highest
20271  * priority group. When this routine is called it searches the fcf_pri list for
20272  * next lowest priority group and repopulates the rr_bmask with only those
20273  * fcf_indexes.
20274  * returns:
20275  * 1=success 0=failure
20276  **/
20277 static int
20278 lpfc_check_next_fcf_pri_level(struct lpfc_hba *phba)
20279 {
20280         uint16_t next_fcf_pri;
20281         uint16_t last_index;
20282         struct lpfc_fcf_pri *fcf_pri;
20283         int rc;
20284         int ret = 0;
20285
20286         last_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20287                         LPFC_SLI4_FCF_TBL_INDX_MAX);
20288         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20289                         "3060 Last IDX %d\n", last_index);
20290
20291         /* Verify the priority list has 2 or more entries */
20292         spin_lock_irq(&phba->hbalock);
20293         if (list_empty(&phba->fcf.fcf_pri_list) ||
20294             list_is_singular(&phba->fcf.fcf_pri_list)) {
20295                 spin_unlock_irq(&phba->hbalock);
20296                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20297                         "3061 Last IDX %d\n", last_index);
20298                 return 0; /* Empty rr list */
20299         }
20300         spin_unlock_irq(&phba->hbalock);
20301
20302         next_fcf_pri = 0;
20303         /*
20304          * Clear the rr_bmask and set all of the bits that are at this
20305          * priority.
20306          */
20307         memset(phba->fcf.fcf_rr_bmask, 0,
20308                         sizeof(*phba->fcf.fcf_rr_bmask));
20309         spin_lock_irq(&phba->hbalock);
20310         list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20311                 if (fcf_pri->fcf_rec.flag & LPFC_FCF_FLOGI_FAILED)
20312                         continue;
20313                 /*
20314                  * the 1st priority that has not FLOGI failed
20315                  * will be the highest.
20316                  */
20317                 if (!next_fcf_pri)
20318                         next_fcf_pri = fcf_pri->fcf_rec.priority;
20319                 spin_unlock_irq(&phba->hbalock);
20320                 if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20321                         rc = lpfc_sli4_fcf_rr_index_set(phba,
20322                                                 fcf_pri->fcf_rec.fcf_index);
20323                         if (rc)
20324                                 return 0;
20325                 }
20326                 spin_lock_irq(&phba->hbalock);
20327         }
20328         /*
20329          * if next_fcf_pri was not set above and the list is not empty then
20330          * we have failed flogis on all of them. So reset flogi failed
20331          * and start at the beginning.
20332          */
20333         if (!next_fcf_pri && !list_empty(&phba->fcf.fcf_pri_list)) {
20334                 list_for_each_entry(fcf_pri, &phba->fcf.fcf_pri_list, list) {
20335                         fcf_pri->fcf_rec.flag &= ~LPFC_FCF_FLOGI_FAILED;
20336                         /*
20337                          * the 1st priority that has not FLOGI failed
20338                          * will be the highest.
20339                          */
20340                         if (!next_fcf_pri)
20341                                 next_fcf_pri = fcf_pri->fcf_rec.priority;
20342                         spin_unlock_irq(&phba->hbalock);
20343                         if (fcf_pri->fcf_rec.priority == next_fcf_pri) {
20344                                 rc = lpfc_sli4_fcf_rr_index_set(phba,
20345                                                 fcf_pri->fcf_rec.fcf_index);
20346                                 if (rc)
20347                                         return 0;
20348                         }
20349                         spin_lock_irq(&phba->hbalock);
20350                 }
20351         } else
20352                 ret = 1;
20353         spin_unlock_irq(&phba->hbalock);
20354
20355         return ret;
20356 }
20357 /**
20358  * lpfc_sli4_fcf_rr_next_index_get - Get next eligible fcf record index
20359  * @phba: pointer to lpfc hba data structure.
20360  *
20361  * This routine is to get the next eligible FCF record index in a round
20362  * robin fashion. If the next eligible FCF record index equals to the
20363  * initial roundrobin FCF record index, LPFC_FCOE_FCF_NEXT_NONE (0xFFFF)
20364  * shall be returned, otherwise, the next eligible FCF record's index
20365  * shall be returned.
20366  **/
20367 uint16_t
20368 lpfc_sli4_fcf_rr_next_index_get(struct lpfc_hba *phba)
20369 {
20370         uint16_t next_fcf_index;
20371
20372 initial_priority:
20373         /* Search start from next bit of currently registered FCF index */
20374         next_fcf_index = phba->fcf.current_rec.fcf_indx;
20375
20376 next_priority:
20377         /* Determine the next fcf index to check */
20378         next_fcf_index = (next_fcf_index + 1) % LPFC_SLI4_FCF_TBL_INDX_MAX;
20379         next_fcf_index = find_next_bit(phba->fcf.fcf_rr_bmask,
20380                                        LPFC_SLI4_FCF_TBL_INDX_MAX,
20381                                        next_fcf_index);
20382
20383         /* Wrap around condition on phba->fcf.fcf_rr_bmask */
20384         if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20385                 /*
20386                  * If we have wrapped then we need to clear the bits that
20387                  * have been tested so that we can detect when we should
20388                  * change the priority level.
20389                  */
20390                 next_fcf_index = find_first_bit(phba->fcf.fcf_rr_bmask,
20391                                                LPFC_SLI4_FCF_TBL_INDX_MAX);
20392         }
20393
20394
20395         /* Check roundrobin failover list empty condition */
20396         if (next_fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX ||
20397                 next_fcf_index == phba->fcf.current_rec.fcf_indx) {
20398                 /*
20399                  * If next fcf index is not found check if there are lower
20400                  * Priority level fcf's in the fcf_priority list.
20401                  * Set up the rr_bmask with all of the avaiable fcf bits
20402                  * at that level and continue the selection process.
20403                  */
20404                 if (lpfc_check_next_fcf_pri_level(phba))
20405                         goto initial_priority;
20406                 lpfc_printf_log(phba, KERN_WARNING, LOG_FIP,
20407                                 "2844 No roundrobin failover FCF available\n");
20408
20409                 return LPFC_FCOE_FCF_NEXT_NONE;
20410         }
20411
20412         if (next_fcf_index < LPFC_SLI4_FCF_TBL_INDX_MAX &&
20413                 phba->fcf.fcf_pri[next_fcf_index].fcf_rec.flag &
20414                 LPFC_FCF_FLOGI_FAILED) {
20415                 if (list_is_singular(&phba->fcf.fcf_pri_list))
20416                         return LPFC_FCOE_FCF_NEXT_NONE;
20417
20418                 goto next_priority;
20419         }
20420
20421         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20422                         "2845 Get next roundrobin failover FCF (x%x)\n",
20423                         next_fcf_index);
20424
20425         return next_fcf_index;
20426 }
20427
20428 /**
20429  * lpfc_sli4_fcf_rr_index_set - Set bmask with eligible fcf record index
20430  * @phba: pointer to lpfc hba data structure.
20431  * @fcf_index: index into the FCF table to 'set'
20432  *
20433  * This routine sets the FCF record index in to the eligible bmask for
20434  * roundrobin failover search. It checks to make sure that the index
20435  * does not go beyond the range of the driver allocated bmask dimension
20436  * before setting the bit.
20437  *
20438  * Returns 0 if the index bit successfully set, otherwise, it returns
20439  * -EINVAL.
20440  **/
20441 int
20442 lpfc_sli4_fcf_rr_index_set(struct lpfc_hba *phba, uint16_t fcf_index)
20443 {
20444         if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20445                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20446                                 "2610 FCF (x%x) reached driver's book "
20447                                 "keeping dimension:x%x\n",
20448                                 fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20449                 return -EINVAL;
20450         }
20451         /* Set the eligible FCF record index bmask */
20452         set_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20453
20454         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20455                         "2790 Set FCF (x%x) to roundrobin FCF failover "
20456                         "bmask\n", fcf_index);
20457
20458         return 0;
20459 }
20460
20461 /**
20462  * lpfc_sli4_fcf_rr_index_clear - Clear bmask from eligible fcf record index
20463  * @phba: pointer to lpfc hba data structure.
20464  * @fcf_index: index into the FCF table to 'clear'
20465  *
20466  * This routine clears the FCF record index from the eligible bmask for
20467  * roundrobin failover search. It checks to make sure that the index
20468  * does not go beyond the range of the driver allocated bmask dimension
20469  * before clearing the bit.
20470  **/
20471 void
20472 lpfc_sli4_fcf_rr_index_clear(struct lpfc_hba *phba, uint16_t fcf_index)
20473 {
20474         struct lpfc_fcf_pri *fcf_pri, *fcf_pri_next;
20475         if (fcf_index >= LPFC_SLI4_FCF_TBL_INDX_MAX) {
20476                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20477                                 "2762 FCF (x%x) reached driver's book "
20478                                 "keeping dimension:x%x\n",
20479                                 fcf_index, LPFC_SLI4_FCF_TBL_INDX_MAX);
20480                 return;
20481         }
20482         /* Clear the eligible FCF record index bmask */
20483         spin_lock_irq(&phba->hbalock);
20484         list_for_each_entry_safe(fcf_pri, fcf_pri_next, &phba->fcf.fcf_pri_list,
20485                                  list) {
20486                 if (fcf_pri->fcf_rec.fcf_index == fcf_index) {
20487                         list_del_init(&fcf_pri->list);
20488                         break;
20489                 }
20490         }
20491         spin_unlock_irq(&phba->hbalock);
20492         clear_bit(fcf_index, phba->fcf.fcf_rr_bmask);
20493
20494         lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20495                         "2791 Clear FCF (x%x) from roundrobin failover "
20496                         "bmask\n", fcf_index);
20497 }
20498
20499 /**
20500  * lpfc_mbx_cmpl_redisc_fcf_table - completion routine for rediscover FCF table
20501  * @phba: pointer to lpfc hba data structure.
20502  * @mbox: An allocated pointer to type LPFC_MBOXQ_t
20503  *
20504  * This routine is the completion routine for the rediscover FCF table mailbox
20505  * command. If the mailbox command returned failure, it will try to stop the
20506  * FCF rediscover wait timer.
20507  **/
20508 static void
20509 lpfc_mbx_cmpl_redisc_fcf_table(struct lpfc_hba *phba, LPFC_MBOXQ_t *mbox)
20510 {
20511         struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20512         uint32_t shdr_status, shdr_add_status;
20513
20514         redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20515
20516         shdr_status = bf_get(lpfc_mbox_hdr_status,
20517                              &redisc_fcf->header.cfg_shdr.response);
20518         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
20519                              &redisc_fcf->header.cfg_shdr.response);
20520         if (shdr_status || shdr_add_status) {
20521                 lpfc_printf_log(phba, KERN_ERR, LOG_FIP,
20522                                 "2746 Requesting for FCF rediscovery failed "
20523                                 "status x%x add_status x%x\n",
20524                                 shdr_status, shdr_add_status);
20525                 if (phba->fcf.fcf_flag & FCF_ACVL_DISC) {
20526                         spin_lock_irq(&phba->hbalock);
20527                         phba->fcf.fcf_flag &= ~FCF_ACVL_DISC;
20528                         spin_unlock_irq(&phba->hbalock);
20529                         /*
20530                          * CVL event triggered FCF rediscover request failed,
20531                          * last resort to re-try current registered FCF entry.
20532                          */
20533                         lpfc_retry_pport_discovery(phba);
20534                 } else {
20535                         spin_lock_irq(&phba->hbalock);
20536                         phba->fcf.fcf_flag &= ~FCF_DEAD_DISC;
20537                         spin_unlock_irq(&phba->hbalock);
20538                         /*
20539                          * DEAD FCF event triggered FCF rediscover request
20540                          * failed, last resort to fail over as a link down
20541                          * to FCF registration.
20542                          */
20543                         lpfc_sli4_fcf_dead_failthrough(phba);
20544                 }
20545         } else {
20546                 lpfc_printf_log(phba, KERN_INFO, LOG_FIP,
20547                                 "2775 Start FCF rediscover quiescent timer\n");
20548                 /*
20549                  * Start FCF rediscovery wait timer for pending FCF
20550                  * before rescan FCF record table.
20551                  */
20552                 lpfc_fcf_redisc_wait_start_timer(phba);
20553         }
20554
20555         mempool_free(mbox, phba->mbox_mem_pool);
20556 }
20557
20558 /**
20559  * lpfc_sli4_redisc_fcf_table - Request to rediscover entire FCF table by port.
20560  * @phba: pointer to lpfc hba data structure.
20561  *
20562  * This routine is invoked to request for rediscovery of the entire FCF table
20563  * by the port.
20564  **/
20565 int
20566 lpfc_sli4_redisc_fcf_table(struct lpfc_hba *phba)
20567 {
20568         LPFC_MBOXQ_t *mbox;
20569         struct lpfc_mbx_redisc_fcf_tbl *redisc_fcf;
20570         int rc, length;
20571
20572         /* Cancel retry delay timers to all vports before FCF rediscover */
20573         lpfc_cancel_all_vport_retry_delay_timer(phba);
20574
20575         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20576         if (!mbox) {
20577                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20578                                 "2745 Failed to allocate mbox for "
20579                                 "requesting FCF rediscover.\n");
20580                 return -ENOMEM;
20581         }
20582
20583         length = (sizeof(struct lpfc_mbx_redisc_fcf_tbl) -
20584                   sizeof(struct lpfc_sli4_cfg_mhdr));
20585         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_FCOE,
20586                          LPFC_MBOX_OPCODE_FCOE_REDISCOVER_FCF,
20587                          length, LPFC_SLI4_MBX_EMBED);
20588
20589         redisc_fcf = &mbox->u.mqe.un.redisc_fcf_tbl;
20590         /* Set count to 0 for invalidating the entire FCF database */
20591         bf_set(lpfc_mbx_redisc_fcf_count, redisc_fcf, 0);
20592
20593         /* Issue the mailbox command asynchronously */
20594         mbox->vport = phba->pport;
20595         mbox->mbox_cmpl = lpfc_mbx_cmpl_redisc_fcf_table;
20596         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
20597
20598         if (rc == MBX_NOT_FINISHED) {
20599                 mempool_free(mbox, phba->mbox_mem_pool);
20600                 return -EIO;
20601         }
20602         return 0;
20603 }
20604
20605 /**
20606  * lpfc_sli4_fcf_dead_failthrough - Failthrough routine to fcf dead event
20607  * @phba: pointer to lpfc hba data structure.
20608  *
20609  * This function is the failover routine as a last resort to the FCF DEAD
20610  * event when driver failed to perform fast FCF failover.
20611  **/
20612 void
20613 lpfc_sli4_fcf_dead_failthrough(struct lpfc_hba *phba)
20614 {
20615         uint32_t link_state;
20616
20617         /*
20618          * Last resort as FCF DEAD event failover will treat this as
20619          * a link down, but save the link state because we don't want
20620          * it to be changed to Link Down unless it is already down.
20621          */
20622         link_state = phba->link_state;
20623         lpfc_linkdown(phba);
20624         phba->link_state = link_state;
20625
20626         /* Unregister FCF if no devices connected to it */
20627         lpfc_unregister_unused_fcf(phba);
20628 }
20629
20630 /**
20631  * lpfc_sli_get_config_region23 - Get sli3 port region 23 data.
20632  * @phba: pointer to lpfc hba data structure.
20633  * @rgn23_data: pointer to configure region 23 data.
20634  *
20635  * This function gets SLI3 port configure region 23 data through memory dump
20636  * mailbox command. When it successfully retrieves data, the size of the data
20637  * will be returned, otherwise, 0 will be returned.
20638  **/
20639 static uint32_t
20640 lpfc_sli_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20641 {
20642         LPFC_MBOXQ_t *pmb = NULL;
20643         MAILBOX_t *mb;
20644         uint32_t offset = 0;
20645         int rc;
20646
20647         if (!rgn23_data)
20648                 return 0;
20649
20650         pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20651         if (!pmb) {
20652                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20653                                 "2600 failed to allocate mailbox memory\n");
20654                 return 0;
20655         }
20656         mb = &pmb->u.mb;
20657
20658         do {
20659                 lpfc_dump_mem(phba, pmb, offset, DMP_REGION_23);
20660                 rc = lpfc_sli_issue_mbox(phba, pmb, MBX_POLL);
20661
20662                 if (rc != MBX_SUCCESS) {
20663                         lpfc_printf_log(phba, KERN_INFO, LOG_INIT,
20664                                         "2601 failed to read config "
20665                                         "region 23, rc 0x%x Status 0x%x\n",
20666                                         rc, mb->mbxStatus);
20667                         mb->un.varDmp.word_cnt = 0;
20668                 }
20669                 /*
20670                  * dump mem may return a zero when finished or we got a
20671                  * mailbox error, either way we are done.
20672                  */
20673                 if (mb->un.varDmp.word_cnt == 0)
20674                         break;
20675
20676                 if (mb->un.varDmp.word_cnt > DMP_RGN23_SIZE - offset)
20677                         mb->un.varDmp.word_cnt = DMP_RGN23_SIZE - offset;
20678
20679                 lpfc_sli_pcimem_bcopy(((uint8_t *)mb) + DMP_RSP_OFFSET,
20680                                        rgn23_data + offset,
20681                                        mb->un.varDmp.word_cnt);
20682                 offset += mb->un.varDmp.word_cnt;
20683         } while (mb->un.varDmp.word_cnt && offset < DMP_RGN23_SIZE);
20684
20685         mempool_free(pmb, phba->mbox_mem_pool);
20686         return offset;
20687 }
20688
20689 /**
20690  * lpfc_sli4_get_config_region23 - Get sli4 port region 23 data.
20691  * @phba: pointer to lpfc hba data structure.
20692  * @rgn23_data: pointer to configure region 23 data.
20693  *
20694  * This function gets SLI4 port configure region 23 data through memory dump
20695  * mailbox command. When it successfully retrieves data, the size of the data
20696  * will be returned, otherwise, 0 will be returned.
20697  **/
20698 static uint32_t
20699 lpfc_sli4_get_config_region23(struct lpfc_hba *phba, char *rgn23_data)
20700 {
20701         LPFC_MBOXQ_t *mboxq = NULL;
20702         struct lpfc_dmabuf *mp = NULL;
20703         struct lpfc_mqe *mqe;
20704         uint32_t data_length = 0;
20705         int rc;
20706
20707         if (!rgn23_data)
20708                 return 0;
20709
20710         mboxq = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20711         if (!mboxq) {
20712                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20713                                 "3105 failed to allocate mailbox memory\n");
20714                 return 0;
20715         }
20716
20717         if (lpfc_sli4_dump_cfg_rg23(phba, mboxq))
20718                 goto out;
20719         mqe = &mboxq->u.mqe;
20720         mp = mboxq->ctx_buf;
20721         rc = lpfc_sli_issue_mbox(phba, mboxq, MBX_POLL);
20722         if (rc)
20723                 goto out;
20724         data_length = mqe->un.mb_words[5];
20725         if (data_length == 0)
20726                 goto out;
20727         if (data_length > DMP_RGN23_SIZE) {
20728                 data_length = 0;
20729                 goto out;
20730         }
20731         lpfc_sli_pcimem_bcopy((char *)mp->virt, rgn23_data, data_length);
20732 out:
20733         lpfc_mbox_rsrc_cleanup(phba, mboxq, MBOX_THD_UNLOCKED);
20734         return data_length;
20735 }
20736
20737 /**
20738  * lpfc_sli_read_link_ste - Read region 23 to decide if link is disabled.
20739  * @phba: pointer to lpfc hba data structure.
20740  *
20741  * This function read region 23 and parse TLV for port status to
20742  * decide if the user disaled the port. If the TLV indicates the
20743  * port is disabled, the hba_flag is set accordingly.
20744  **/
20745 void
20746 lpfc_sli_read_link_ste(struct lpfc_hba *phba)
20747 {
20748         uint8_t *rgn23_data = NULL;
20749         uint32_t if_type, data_size, sub_tlv_len, tlv_offset;
20750         uint32_t offset = 0;
20751
20752         /* Get adapter Region 23 data */
20753         rgn23_data = kzalloc(DMP_RGN23_SIZE, GFP_KERNEL);
20754         if (!rgn23_data)
20755                 goto out;
20756
20757         if (phba->sli_rev < LPFC_SLI_REV4)
20758                 data_size = lpfc_sli_get_config_region23(phba, rgn23_data);
20759         else {
20760                 if_type = bf_get(lpfc_sli_intf_if_type,
20761                                  &phba->sli4_hba.sli_intf);
20762                 if (if_type == LPFC_SLI_INTF_IF_TYPE_0)
20763                         goto out;
20764                 data_size = lpfc_sli4_get_config_region23(phba, rgn23_data);
20765         }
20766
20767         if (!data_size)
20768                 goto out;
20769
20770         /* Check the region signature first */
20771         if (memcmp(&rgn23_data[offset], LPFC_REGION23_SIGNATURE, 4)) {
20772                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20773                         "2619 Config region 23 has bad signature\n");
20774                         goto out;
20775         }
20776         offset += 4;
20777
20778         /* Check the data structure version */
20779         if (rgn23_data[offset] != LPFC_REGION23_VERSION) {
20780                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
20781                         "2620 Config region 23 has bad version\n");
20782                 goto out;
20783         }
20784         offset += 4;
20785
20786         /* Parse TLV entries in the region */
20787         while (offset < data_size) {
20788                 if (rgn23_data[offset] == LPFC_REGION23_LAST_REC)
20789                         break;
20790                 /*
20791                  * If the TLV is not driver specific TLV or driver id is
20792                  * not linux driver id, skip the record.
20793                  */
20794                 if ((rgn23_data[offset] != DRIVER_SPECIFIC_TYPE) ||
20795                     (rgn23_data[offset + 2] != LINUX_DRIVER_ID) ||
20796                     (rgn23_data[offset + 3] != 0)) {
20797                         offset += rgn23_data[offset + 1] * 4 + 4;
20798                         continue;
20799                 }
20800
20801                 /* Driver found a driver specific TLV in the config region */
20802                 sub_tlv_len = rgn23_data[offset + 1] * 4;
20803                 offset += 4;
20804                 tlv_offset = 0;
20805
20806                 /*
20807                  * Search for configured port state sub-TLV.
20808                  */
20809                 while ((offset < data_size) &&
20810                         (tlv_offset < sub_tlv_len)) {
20811                         if (rgn23_data[offset] == LPFC_REGION23_LAST_REC) {
20812                                 offset += 4;
20813                                 tlv_offset += 4;
20814                                 break;
20815                         }
20816                         if (rgn23_data[offset] != PORT_STE_TYPE) {
20817                                 offset += rgn23_data[offset + 1] * 4 + 4;
20818                                 tlv_offset += rgn23_data[offset + 1] * 4 + 4;
20819                                 continue;
20820                         }
20821
20822                         /* This HBA contains PORT_STE configured */
20823                         if (!rgn23_data[offset + 2])
20824                                 set_bit(LINK_DISABLED, &phba->hba_flag);
20825
20826                         goto out;
20827                 }
20828         }
20829
20830 out:
20831         kfree(rgn23_data);
20832         return;
20833 }
20834
20835 /**
20836  * lpfc_log_fw_write_cmpl - logs firmware write completion status
20837  * @phba: pointer to lpfc hba data structure
20838  * @shdr_status: wr_object rsp's status field
20839  * @shdr_add_status: wr_object rsp's add_status field
20840  * @shdr_add_status_2: wr_object rsp's add_status_2 field
20841  * @shdr_change_status: wr_object rsp's change_status field
20842  * @shdr_csf: wr_object rsp's csf bit
20843  *
20844  * This routine is intended to be called after a firmware write completes.
20845  * It will log next action items to be performed by the user to instantiate
20846  * the newly downloaded firmware or reason for incompatibility.
20847  **/
20848 static void
20849 lpfc_log_fw_write_cmpl(struct lpfc_hba *phba, u32 shdr_status,
20850                        u32 shdr_add_status, u32 shdr_add_status_2,
20851                        u32 shdr_change_status, u32 shdr_csf)
20852 {
20853         lpfc_printf_log(phba, KERN_INFO, LOG_MBOX | LOG_SLI,
20854                         "4198 %s: flash_id x%02x, asic_rev x%02x, "
20855                         "status x%02x, add_status x%02x, add_status_2 x%02x, "
20856                         "change_status x%02x, csf %01x\n", __func__,
20857                         phba->sli4_hba.flash_id, phba->sli4_hba.asic_rev,
20858                         shdr_status, shdr_add_status, shdr_add_status_2,
20859                         shdr_change_status, shdr_csf);
20860
20861         if (shdr_add_status == LPFC_ADD_STATUS_INCOMPAT_OBJ) {
20862                 switch (shdr_add_status_2) {
20863                 case LPFC_ADD_STATUS_2_INCOMPAT_FLASH:
20864                         lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20865                                      "4199 Firmware write failed: "
20866                                      "image incompatible with flash x%02x\n",
20867                                      phba->sli4_hba.flash_id);
20868                         break;
20869                 case LPFC_ADD_STATUS_2_INCORRECT_ASIC:
20870                         lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20871                                      "4200 Firmware write failed: "
20872                                      "image incompatible with ASIC "
20873                                      "architecture x%02x\n",
20874                                      phba->sli4_hba.asic_rev);
20875                         break;
20876                 default:
20877                         lpfc_log_msg(phba, KERN_WARNING, LOG_MBOX | LOG_SLI,
20878                                      "4210 Firmware write failed: "
20879                                      "add_status_2 x%02x\n",
20880                                      shdr_add_status_2);
20881                         break;
20882                 }
20883         } else if (!shdr_status && !shdr_add_status) {
20884                 if (shdr_change_status == LPFC_CHANGE_STATUS_FW_RESET ||
20885                     shdr_change_status == LPFC_CHANGE_STATUS_PORT_MIGRATION) {
20886                         if (shdr_csf)
20887                                 shdr_change_status =
20888                                                    LPFC_CHANGE_STATUS_PCI_RESET;
20889                 }
20890
20891                 switch (shdr_change_status) {
20892                 case (LPFC_CHANGE_STATUS_PHYS_DEV_RESET):
20893                         lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20894                                      "3198 Firmware write complete: System "
20895                                      "reboot required to instantiate\n");
20896                         break;
20897                 case (LPFC_CHANGE_STATUS_FW_RESET):
20898                         lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20899                                      "3199 Firmware write complete: "
20900                                      "Firmware reset required to "
20901                                      "instantiate\n");
20902                         break;
20903                 case (LPFC_CHANGE_STATUS_PORT_MIGRATION):
20904                         lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20905                                      "3200 Firmware write complete: Port "
20906                                      "Migration or PCI Reset required to "
20907                                      "instantiate\n");
20908                         break;
20909                 case (LPFC_CHANGE_STATUS_PCI_RESET):
20910                         lpfc_log_msg(phba, KERN_NOTICE, LOG_MBOX | LOG_SLI,
20911                                      "3201 Firmware write complete: PCI "
20912                                      "Reset required to instantiate\n");
20913                         break;
20914                 default:
20915                         break;
20916                 }
20917         }
20918 }
20919
20920 /**
20921  * lpfc_wr_object - write an object to the firmware
20922  * @phba: HBA structure that indicates port to create a queue on.
20923  * @dmabuf_list: list of dmabufs to write to the port.
20924  * @size: the total byte value of the objects to write to the port.
20925  * @offset: the current offset to be used to start the transfer.
20926  *
20927  * This routine will create a wr_object mailbox command to send to the port.
20928  * the mailbox command will be constructed using the dma buffers described in
20929  * @dmabuf_list to create a list of BDEs. This routine will fill in as many
20930  * BDEs that the imbedded mailbox can support. The @offset variable will be
20931  * used to indicate the starting offset of the transfer and will also return
20932  * the offset after the write object mailbox has completed. @size is used to
20933  * determine the end of the object and whether the eof bit should be set.
20934  *
20935  * Return 0 is successful and offset will contain the new offset to use
20936  * for the next write.
20937  * Return negative value for error cases.
20938  **/
20939 int
20940 lpfc_wr_object(struct lpfc_hba *phba, struct list_head *dmabuf_list,
20941                uint32_t size, uint32_t *offset)
20942 {
20943         struct lpfc_mbx_wr_object *wr_object;
20944         LPFC_MBOXQ_t *mbox;
20945         int rc = 0, i = 0;
20946         int mbox_status = 0;
20947         uint32_t shdr_status, shdr_add_status, shdr_add_status_2;
20948         uint32_t shdr_change_status = 0, shdr_csf = 0;
20949         uint32_t mbox_tmo;
20950         struct lpfc_dmabuf *dmabuf;
20951         uint32_t written = 0;
20952         bool check_change_status = false;
20953
20954         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
20955         if (!mbox)
20956                 return -ENOMEM;
20957
20958         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
20959                         LPFC_MBOX_OPCODE_WRITE_OBJECT,
20960                         sizeof(struct lpfc_mbx_wr_object) -
20961                         sizeof(struct lpfc_sli4_cfg_mhdr), LPFC_SLI4_MBX_EMBED);
20962
20963         wr_object = (struct lpfc_mbx_wr_object *)&mbox->u.mqe.un.wr_object;
20964         wr_object->u.request.write_offset = *offset;
20965         sprintf((uint8_t *)wr_object->u.request.object_name, "/");
20966         wr_object->u.request.object_name[0] =
20967                 cpu_to_le32(wr_object->u.request.object_name[0]);
20968         bf_set(lpfc_wr_object_eof, &wr_object->u.request, 0);
20969         list_for_each_entry(dmabuf, dmabuf_list, list) {
20970                 if (i >= LPFC_MBX_WR_CONFIG_MAX_BDE || written >= size)
20971                         break;
20972                 wr_object->u.request.bde[i].addrLow = putPaddrLow(dmabuf->phys);
20973                 wr_object->u.request.bde[i].addrHigh =
20974                         putPaddrHigh(dmabuf->phys);
20975                 if (written + SLI4_PAGE_SIZE >= size) {
20976                         wr_object->u.request.bde[i].tus.f.bdeSize =
20977                                 (size - written);
20978                         written += (size - written);
20979                         bf_set(lpfc_wr_object_eof, &wr_object->u.request, 1);
20980                         bf_set(lpfc_wr_object_eas, &wr_object->u.request, 1);
20981                         check_change_status = true;
20982                 } else {
20983                         wr_object->u.request.bde[i].tus.f.bdeSize =
20984                                 SLI4_PAGE_SIZE;
20985                         written += SLI4_PAGE_SIZE;
20986                 }
20987                 i++;
20988         }
20989         wr_object->u.request.bde_count = i;
20990         bf_set(lpfc_wr_object_write_length, &wr_object->u.request, written);
20991         if (!phba->sli4_hba.intr_enable)
20992                 mbox_status = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
20993         else {
20994                 mbox_tmo = lpfc_mbox_tmo_val(phba, mbox);
20995                 mbox_status = lpfc_sli_issue_mbox_wait(phba, mbox, mbox_tmo);
20996         }
20997
20998         /* The mbox status needs to be maintained to detect MBOX_TIMEOUT. */
20999         rc = mbox_status;
21000
21001         /* The IOCTL status is embedded in the mailbox subheader. */
21002         shdr_status = bf_get(lpfc_mbox_hdr_status,
21003                              &wr_object->header.cfg_shdr.response);
21004         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status,
21005                                  &wr_object->header.cfg_shdr.response);
21006         shdr_add_status_2 = bf_get(lpfc_mbox_hdr_add_status_2,
21007                                    &wr_object->header.cfg_shdr.response);
21008         if (check_change_status) {
21009                 shdr_change_status = bf_get(lpfc_wr_object_change_status,
21010                                             &wr_object->u.response);
21011                 shdr_csf = bf_get(lpfc_wr_object_csf,
21012                                   &wr_object->u.response);
21013         }
21014
21015         if (shdr_status || shdr_add_status || shdr_add_status_2 || rc) {
21016                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21017                                 "3025 Write Object mailbox failed with "
21018                                 "status x%x add_status x%x, add_status_2 x%x, "
21019                                 "mbx status x%x\n",
21020                                 shdr_status, shdr_add_status, shdr_add_status_2,
21021                                 rc);
21022                 rc = -ENXIO;
21023                 *offset = shdr_add_status;
21024         } else {
21025                 *offset += wr_object->u.response.actual_write_length;
21026         }
21027
21028         if (rc || check_change_status)
21029                 lpfc_log_fw_write_cmpl(phba, shdr_status, shdr_add_status,
21030                                        shdr_add_status_2, shdr_change_status,
21031                                        shdr_csf);
21032
21033         if (!phba->sli4_hba.intr_enable)
21034                 mempool_free(mbox, phba->mbox_mem_pool);
21035         else if (mbox_status != MBX_TIMEOUT)
21036                 mempool_free(mbox, phba->mbox_mem_pool);
21037
21038         return rc;
21039 }
21040
21041 /**
21042  * lpfc_cleanup_pending_mbox - Free up vport discovery mailbox commands.
21043  * @vport: pointer to vport data structure.
21044  *
21045  * This function iterate through the mailboxq and clean up all REG_LOGIN
21046  * and REG_VPI mailbox commands associated with the vport. This function
21047  * is called when driver want to restart discovery of the vport due to
21048  * a Clear Virtual Link event.
21049  **/
21050 void
21051 lpfc_cleanup_pending_mbox(struct lpfc_vport *vport)
21052 {
21053         struct lpfc_hba *phba = vport->phba;
21054         LPFC_MBOXQ_t *mb, *nextmb;
21055         struct lpfc_nodelist *ndlp;
21056         struct lpfc_nodelist *act_mbx_ndlp = NULL;
21057         LIST_HEAD(mbox_cmd_list);
21058         uint8_t restart_loop;
21059
21060         /* Clean up internally queued mailbox commands with the vport */
21061         spin_lock_irq(&phba->hbalock);
21062         list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
21063                 if (mb->vport != vport)
21064                         continue;
21065
21066                 if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21067                         (mb->u.mb.mbxCommand != MBX_REG_VPI))
21068                         continue;
21069
21070                 list_move_tail(&mb->list, &mbox_cmd_list);
21071         }
21072         /* Clean up active mailbox command with the vport */
21073         mb = phba->sli.mbox_active;
21074         if (mb && (mb->vport == vport)) {
21075                 if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) ||
21076                         (mb->u.mb.mbxCommand == MBX_REG_VPI))
21077                         mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21078                 if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21079                         act_mbx_ndlp = mb->ctx_ndlp;
21080
21081                         /* This reference is local to this routine.  The
21082                          * reference is removed at routine exit.
21083                          */
21084                         act_mbx_ndlp = lpfc_nlp_get(act_mbx_ndlp);
21085
21086                         /* Unregister the RPI when mailbox complete */
21087                         mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21088                 }
21089         }
21090         /* Cleanup any mailbox completions which are not yet processed */
21091         do {
21092                 restart_loop = 0;
21093                 list_for_each_entry(mb, &phba->sli.mboxq_cmpl, list) {
21094                         /*
21095                          * If this mailox is already processed or it is
21096                          * for another vport ignore it.
21097                          */
21098                         if ((mb->vport != vport) ||
21099                                 (mb->mbox_flag & LPFC_MBX_IMED_UNREG))
21100                                 continue;
21101
21102                         if ((mb->u.mb.mbxCommand != MBX_REG_LOGIN64) &&
21103                                 (mb->u.mb.mbxCommand != MBX_REG_VPI))
21104                                 continue;
21105
21106                         mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
21107                         if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21108                                 ndlp = mb->ctx_ndlp;
21109                                 /* Unregister the RPI when mailbox complete */
21110                                 mb->mbox_flag |= LPFC_MBX_IMED_UNREG;
21111                                 restart_loop = 1;
21112                                 clear_bit(NLP_IGNR_REG_CMPL, &ndlp->nlp_flag);
21113                                 break;
21114                         }
21115                 }
21116         } while (restart_loop);
21117
21118         spin_unlock_irq(&phba->hbalock);
21119
21120         /* Release the cleaned-up mailbox commands */
21121         while (!list_empty(&mbox_cmd_list)) {
21122                 list_remove_head(&mbox_cmd_list, mb, LPFC_MBOXQ_t, list);
21123                 if (mb->u.mb.mbxCommand == MBX_REG_LOGIN64) {
21124                         ndlp = mb->ctx_ndlp;
21125                         mb->ctx_ndlp = NULL;
21126                         if (ndlp) {
21127                                 clear_bit(NLP_IGNR_REG_CMPL, &ndlp->nlp_flag);
21128                                 lpfc_nlp_put(ndlp);
21129                         }
21130                 }
21131                 lpfc_mbox_rsrc_cleanup(phba, mb, MBOX_THD_UNLOCKED);
21132         }
21133
21134         /* Release the ndlp with the cleaned-up active mailbox command */
21135         if (act_mbx_ndlp) {
21136                 clear_bit(NLP_IGNR_REG_CMPL, &act_mbx_ndlp->nlp_flag);
21137                 lpfc_nlp_put(act_mbx_ndlp);
21138         }
21139 }
21140
21141 /**
21142  * lpfc_drain_txq - Drain the txq
21143  * @phba: Pointer to HBA context object.
21144  *
21145  * This function attempt to submit IOCBs on the txq
21146  * to the adapter.  For SLI4 adapters, the txq contains
21147  * ELS IOCBs that have been deferred because the there
21148  * are no SGLs.  This congestion can occur with large
21149  * vport counts during node discovery.
21150  **/
21151
21152 uint32_t
21153 lpfc_drain_txq(struct lpfc_hba *phba)
21154 {
21155         LIST_HEAD(completions);
21156         struct lpfc_sli_ring *pring;
21157         struct lpfc_iocbq *piocbq = NULL;
21158         unsigned long iflags = 0;
21159         char *fail_msg = NULL;
21160         uint32_t txq_cnt = 0;
21161         struct lpfc_queue *wq;
21162         int ret = 0;
21163
21164         if (phba->link_flag & LS_MDS_LOOPBACK) {
21165                 /* MDS WQE are posted only to first WQ*/
21166                 wq = phba->sli4_hba.hdwq[0].io_wq;
21167                 if (unlikely(!wq))
21168                         return 0;
21169                 pring = wq->pring;
21170         } else {
21171                 wq = phba->sli4_hba.els_wq;
21172                 if (unlikely(!wq))
21173                         return 0;
21174                 pring = lpfc_phba_elsring(phba);
21175         }
21176
21177         if (unlikely(!pring) || list_empty(&pring->txq))
21178                 return 0;
21179
21180         spin_lock_irqsave(&pring->ring_lock, iflags);
21181         list_for_each_entry(piocbq, &pring->txq, list) {
21182                 txq_cnt++;
21183         }
21184
21185         if (txq_cnt > pring->txq_max)
21186                 pring->txq_max = txq_cnt;
21187
21188         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21189
21190         while (!list_empty(&pring->txq)) {
21191                 spin_lock_irqsave(&pring->ring_lock, iflags);
21192
21193                 piocbq = lpfc_sli_ringtx_get(phba, pring);
21194                 if (!piocbq) {
21195                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21196                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21197                                 "2823 txq empty and txq_cnt is %d\n",
21198                                 txq_cnt);
21199                         break;
21200                 }
21201                 txq_cnt--;
21202
21203                 ret = __lpfc_sli_issue_iocb(phba, pring->ringno, piocbq, 0);
21204
21205                 if (ret && ret != IOCB_BUSY) {
21206                         fail_msg = " - Cannot send IO ";
21207                         piocbq->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21208                 }
21209                 if (fail_msg) {
21210                         piocbq->cmd_flag |= LPFC_DRIVER_ABORTED;
21211                         /* Failed means we can't issue and need to cancel */
21212                         lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
21213                                         "2822 IOCB failed %s iotag 0x%x "
21214                                         "xri 0x%x %d flg x%x\n",
21215                                         fail_msg, piocbq->iotag,
21216                                         piocbq->sli4_xritag, ret,
21217                                         piocbq->cmd_flag);
21218                         list_add_tail(&piocbq->list, &completions);
21219                         fail_msg = NULL;
21220                 }
21221                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
21222                 if (txq_cnt == 0 || ret == IOCB_BUSY)
21223                         break;
21224         }
21225         /* Cancel all the IOCBs that cannot be issued */
21226         lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
21227                               IOERR_SLI_ABORTED);
21228
21229         return txq_cnt;
21230 }
21231
21232 /**
21233  * lpfc_wqe_bpl2sgl - Convert the bpl/bde to a sgl.
21234  * @phba: Pointer to HBA context object.
21235  * @pwqeq: Pointer to command WQE.
21236  * @sglq: Pointer to the scatter gather queue object.
21237  *
21238  * This routine converts the bpl or bde that is in the WQE
21239  * to a sgl list for the sli4 hardware. The physical address
21240  * of the bpl/bde is converted back to a virtual address.
21241  * If the WQE contains a BPL then the list of BDE's is
21242  * converted to sli4_sge's. If the WQE contains a single
21243  * BDE then it is converted to a single sli_sge.
21244  * The WQE is still in cpu endianness so the contents of
21245  * the bpl can be used without byte swapping.
21246  *
21247  * Returns valid XRI = Success, NO_XRI = Failure.
21248  */
21249 static uint16_t
21250 lpfc_wqe_bpl2sgl(struct lpfc_hba *phba, struct lpfc_iocbq *pwqeq,
21251                  struct lpfc_sglq *sglq)
21252 {
21253         uint16_t xritag = NO_XRI;
21254         struct ulp_bde64 *bpl = NULL;
21255         struct ulp_bde64 bde;
21256         struct sli4_sge *sgl  = NULL;
21257         struct lpfc_dmabuf *dmabuf;
21258         union lpfc_wqe128 *wqe;
21259         int numBdes = 0;
21260         int i = 0;
21261         uint32_t offset = 0; /* accumulated offset in the sg request list */
21262         int inbound = 0; /* number of sg reply entries inbound from firmware */
21263         uint32_t cmd;
21264
21265         if (!pwqeq || !sglq)
21266                 return xritag;
21267
21268         sgl  = (struct sli4_sge *)sglq->sgl;
21269         wqe = &pwqeq->wqe;
21270         pwqeq->iocb.ulpIoTag = pwqeq->iotag;
21271
21272         cmd = bf_get(wqe_cmnd, &wqe->generic.wqe_com);
21273         if (cmd == CMD_XMIT_BLS_RSP64_WQE)
21274                 return sglq->sli4_xritag;
21275         numBdes = pwqeq->num_bdes;
21276         if (numBdes) {
21277                 /* The addrHigh and addrLow fields within the WQE
21278                  * have not been byteswapped yet so there is no
21279                  * need to swap them back.
21280                  */
21281                 if (pwqeq->bpl_dmabuf)
21282                         dmabuf = pwqeq->bpl_dmabuf;
21283                 else
21284                         return xritag;
21285
21286                 bpl  = (struct ulp_bde64 *)dmabuf->virt;
21287                 if (!bpl)
21288                         return xritag;
21289
21290                 for (i = 0; i < numBdes; i++) {
21291                         /* Should already be byte swapped. */
21292                         sgl->addr_hi = bpl->addrHigh;
21293                         sgl->addr_lo = bpl->addrLow;
21294
21295                         sgl->word2 = le32_to_cpu(sgl->word2);
21296                         if ((i+1) == numBdes)
21297                                 bf_set(lpfc_sli4_sge_last, sgl, 1);
21298                         else
21299                                 bf_set(lpfc_sli4_sge_last, sgl, 0);
21300                         /* swap the size field back to the cpu so we
21301                          * can assign it to the sgl.
21302                          */
21303                         bde.tus.w = le32_to_cpu(bpl->tus.w);
21304                         sgl->sge_len = cpu_to_le32(bde.tus.f.bdeSize);
21305                         /* The offsets in the sgl need to be accumulated
21306                          * separately for the request and reply lists.
21307                          * The request is always first, the reply follows.
21308                          */
21309                         switch (cmd) {
21310                         case CMD_GEN_REQUEST64_WQE:
21311                                 /* add up the reply sg entries */
21312                                 if (bpl->tus.f.bdeFlags == BUFF_TYPE_BDE_64I)
21313                                         inbound++;
21314                                 /* first inbound? reset the offset */
21315                                 if (inbound == 1)
21316                                         offset = 0;
21317                                 bf_set(lpfc_sli4_sge_offset, sgl, offset);
21318                                 bf_set(lpfc_sli4_sge_type, sgl,
21319                                         LPFC_SGE_TYPE_DATA);
21320                                 offset += bde.tus.f.bdeSize;
21321                                 break;
21322                         case CMD_FCP_TRSP64_WQE:
21323                                 bf_set(lpfc_sli4_sge_offset, sgl, 0);
21324                                 bf_set(lpfc_sli4_sge_type, sgl,
21325                                         LPFC_SGE_TYPE_DATA);
21326                                 break;
21327                         case CMD_FCP_TSEND64_WQE:
21328                         case CMD_FCP_TRECEIVE64_WQE:
21329                                 bf_set(lpfc_sli4_sge_type, sgl,
21330                                         bpl->tus.f.bdeFlags);
21331                                 if (i < 3)
21332                                         offset = 0;
21333                                 else
21334                                         offset += bde.tus.f.bdeSize;
21335                                 bf_set(lpfc_sli4_sge_offset, sgl, offset);
21336                                 break;
21337                         }
21338                         sgl->word2 = cpu_to_le32(sgl->word2);
21339                         bpl++;
21340                         sgl++;
21341                 }
21342         } else if (wqe->gen_req.bde.tus.f.bdeFlags == BUFF_TYPE_BDE_64) {
21343                 /* The addrHigh and addrLow fields of the BDE have not
21344                  * been byteswapped yet so they need to be swapped
21345                  * before putting them in the sgl.
21346                  */
21347                 sgl->addr_hi = cpu_to_le32(wqe->gen_req.bde.addrHigh);
21348                 sgl->addr_lo = cpu_to_le32(wqe->gen_req.bde.addrLow);
21349                 sgl->word2 = le32_to_cpu(sgl->word2);
21350                 bf_set(lpfc_sli4_sge_last, sgl, 1);
21351                 sgl->word2 = cpu_to_le32(sgl->word2);
21352                 sgl->sge_len = cpu_to_le32(wqe->gen_req.bde.tus.f.bdeSize);
21353         }
21354         return sglq->sli4_xritag;
21355 }
21356
21357 /**
21358  * lpfc_sli4_issue_wqe - Issue an SLI4 Work Queue Entry (WQE)
21359  * @phba: Pointer to HBA context object.
21360  * @qp: Pointer to HDW queue.
21361  * @pwqe: Pointer to command WQE.
21362  **/
21363 int
21364 lpfc_sli4_issue_wqe(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21365                     struct lpfc_iocbq *pwqe)
21366 {
21367         union lpfc_wqe128 *wqe = &pwqe->wqe;
21368         struct lpfc_async_xchg_ctx *ctxp;
21369         struct lpfc_queue *wq;
21370         struct lpfc_sglq *sglq;
21371         struct lpfc_sli_ring *pring;
21372         unsigned long iflags;
21373         uint32_t ret = 0;
21374
21375         /* NVME_LS and NVME_LS ABTS requests. */
21376         if (pwqe->cmd_flag & LPFC_IO_NVME_LS) {
21377                 pring =  phba->sli4_hba.nvmels_wq->pring;
21378                 lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21379                                           qp, wq_access);
21380                 sglq = __lpfc_sli_get_els_sglq(phba, pwqe);
21381                 if (!sglq) {
21382                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21383                         return WQE_BUSY;
21384                 }
21385                 pwqe->sli4_lxritag = sglq->sli4_lxritag;
21386                 pwqe->sli4_xritag = sglq->sli4_xritag;
21387                 if (lpfc_wqe_bpl2sgl(phba, pwqe, sglq) == NO_XRI) {
21388                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21389                         return WQE_ERROR;
21390                 }
21391                 bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21392                        pwqe->sli4_xritag);
21393                 ret = lpfc_sli4_wq_put(phba->sli4_hba.nvmels_wq, wqe);
21394                 if (ret) {
21395                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21396                         return ret;
21397                 }
21398
21399                 lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21400                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
21401
21402                 lpfc_sli4_poll_eq(qp->hba_eq);
21403                 return 0;
21404         }
21405
21406         /* NVME_FCREQ and NVME_ABTS requests */
21407         if (pwqe->cmd_flag & (LPFC_IO_NVME | LPFC_IO_FCP | LPFC_IO_CMF)) {
21408                 /* Get the IO distribution (hba_wqidx) for WQ assignment. */
21409                 wq = qp->io_wq;
21410                 pring = wq->pring;
21411
21412                 bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21413
21414                 lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21415                                           qp, wq_access);
21416                 ret = lpfc_sli4_wq_put(wq, wqe);
21417                 if (ret) {
21418                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21419                         return ret;
21420                 }
21421                 lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21422                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
21423
21424                 lpfc_sli4_poll_eq(qp->hba_eq);
21425                 return 0;
21426         }
21427
21428         /* NVMET requests */
21429         if (pwqe->cmd_flag & LPFC_IO_NVMET) {
21430                 /* Get the IO distribution (hba_wqidx) for WQ assignment. */
21431                 wq = qp->io_wq;
21432                 pring = wq->pring;
21433
21434                 ctxp = pwqe->context_un.axchg;
21435                 sglq = ctxp->ctxbuf->sglq;
21436                 if (pwqe->sli4_xritag ==  NO_XRI) {
21437                         pwqe->sli4_lxritag = sglq->sli4_lxritag;
21438                         pwqe->sli4_xritag = sglq->sli4_xritag;
21439                 }
21440                 bf_set(wqe_xri_tag, &pwqe->wqe.xmit_bls_rsp.wqe_com,
21441                        pwqe->sli4_xritag);
21442                 bf_set(wqe_cqid, &wqe->generic.wqe_com, qp->io_cq_map);
21443
21444                 lpfc_qp_spin_lock_irqsave(&pring->ring_lock, iflags,
21445                                           qp, wq_access);
21446                 ret = lpfc_sli4_wq_put(wq, wqe);
21447                 if (ret) {
21448                         spin_unlock_irqrestore(&pring->ring_lock, iflags);
21449                         return ret;
21450                 }
21451                 lpfc_sli_ringtxcmpl_put(phba, pring, pwqe);
21452                 spin_unlock_irqrestore(&pring->ring_lock, iflags);
21453
21454                 lpfc_sli4_poll_eq(qp->hba_eq);
21455                 return 0;
21456         }
21457         return WQE_ERROR;
21458 }
21459
21460 /**
21461  * lpfc_sli4_issue_abort_iotag - SLI-4 WQE init & issue for the Abort
21462  * @phba: Pointer to HBA context object.
21463  * @cmdiocb: Pointer to driver command iocb object.
21464  * @cmpl: completion function.
21465  *
21466  * Fill the appropriate fields for the abort WQE and call
21467  * internal routine lpfc_sli4_issue_wqe to send the WQE
21468  * This function is called with hbalock held and no ring_lock held.
21469  *
21470  * RETURNS 0 - SUCCESS
21471  **/
21472
21473 int
21474 lpfc_sli4_issue_abort_iotag(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
21475                             void *cmpl)
21476 {
21477         struct lpfc_vport *vport = cmdiocb->vport;
21478         struct lpfc_iocbq *abtsiocb = NULL;
21479         union lpfc_wqe128 *abtswqe;
21480         struct lpfc_io_buf *lpfc_cmd;
21481         int retval = IOCB_ERROR;
21482         u16 xritag = cmdiocb->sli4_xritag;
21483
21484         /*
21485          * The scsi command can not be in txq and it is in flight because the
21486          * pCmd is still pointing at the SCSI command we have to abort. There
21487          * is no need to search the txcmplq. Just send an abort to the FW.
21488          */
21489
21490         abtsiocb = __lpfc_sli_get_iocbq(phba);
21491         if (!abtsiocb)
21492                 return WQE_NORESOURCE;
21493
21494         /* Indicate the IO is being aborted by the driver. */
21495         cmdiocb->cmd_flag |= LPFC_DRIVER_ABORTED;
21496
21497         abtswqe = &abtsiocb->wqe;
21498         memset(abtswqe, 0, sizeof(*abtswqe));
21499
21500         if (!lpfc_is_link_up(phba) || (phba->link_flag & LS_EXTERNAL_LOOPBACK))
21501                 bf_set(abort_cmd_ia, &abtswqe->abort_cmd, 1);
21502         bf_set(abort_cmd_criteria, &abtswqe->abort_cmd, T_XRI_TAG);
21503         abtswqe->abort_cmd.rsrvd5 = 0;
21504         abtswqe->abort_cmd.wqe_com.abort_tag = xritag;
21505         bf_set(wqe_reqtag, &abtswqe->abort_cmd.wqe_com, abtsiocb->iotag);
21506         bf_set(wqe_cmnd, &abtswqe->abort_cmd.wqe_com, CMD_ABORT_XRI_CX);
21507         bf_set(wqe_xri_tag, &abtswqe->generic.wqe_com, 0);
21508         bf_set(wqe_qosd, &abtswqe->abort_cmd.wqe_com, 1);
21509         bf_set(wqe_lenloc, &abtswqe->abort_cmd.wqe_com, LPFC_WQE_LENLOC_NONE);
21510         bf_set(wqe_cmd_type, &abtswqe->abort_cmd.wqe_com, OTHER_COMMAND);
21511
21512         /* ABTS WQE must go to the same WQ as the WQE to be aborted */
21513         abtsiocb->hba_wqidx = cmdiocb->hba_wqidx;
21514         abtsiocb->cmd_flag |= LPFC_USE_FCPWQIDX;
21515         if (cmdiocb->cmd_flag & LPFC_IO_FCP)
21516                 abtsiocb->cmd_flag |= LPFC_IO_FCP;
21517         if (cmdiocb->cmd_flag & LPFC_IO_NVME)
21518                 abtsiocb->cmd_flag |= LPFC_IO_NVME;
21519         if (cmdiocb->cmd_flag & LPFC_IO_FOF)
21520                 abtsiocb->cmd_flag |= LPFC_IO_FOF;
21521         abtsiocb->vport = vport;
21522         abtsiocb->cmd_cmpl = cmpl;
21523
21524         lpfc_cmd = container_of(cmdiocb, struct lpfc_io_buf, cur_iocbq);
21525         retval = lpfc_sli4_issue_wqe(phba, lpfc_cmd->hdwq, abtsiocb);
21526
21527         lpfc_printf_vlog(vport, KERN_INFO, LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
21528                          "0359 Abort xri x%x, original iotag x%x, "
21529                          "abort cmd iotag x%x retval x%x\n",
21530                          xritag, cmdiocb->iotag, abtsiocb->iotag, retval);
21531
21532         if (retval) {
21533                 cmdiocb->cmd_flag &= ~LPFC_DRIVER_ABORTED;
21534                 __lpfc_sli_release_iocbq(phba, abtsiocb);
21535         }
21536
21537         return retval;
21538 }
21539
21540 #ifdef LPFC_MXP_STAT
21541 /**
21542  * lpfc_snapshot_mxp - Snapshot pbl, pvt and busy count
21543  * @phba: pointer to lpfc hba data structure.
21544  * @hwqid: belong to which HWQ.
21545  *
21546  * The purpose of this routine is to take a snapshot of pbl, pvt and busy count
21547  * 15 seconds after a test case is running.
21548  *
21549  * The user should call lpfc_debugfs_multixripools_write before running a test
21550  * case to clear stat_snapshot_taken. Then the user starts a test case. During
21551  * test case is running, stat_snapshot_taken is incremented by 1 every time when
21552  * this routine is called from heartbeat timer. When stat_snapshot_taken is
21553  * equal to LPFC_MXP_SNAPSHOT_TAKEN, a snapshot is taken.
21554  **/
21555 void lpfc_snapshot_mxp(struct lpfc_hba *phba, u32 hwqid)
21556 {
21557         struct lpfc_sli4_hdw_queue *qp;
21558         struct lpfc_multixri_pool *multixri_pool;
21559         struct lpfc_pvt_pool *pvt_pool;
21560         struct lpfc_pbl_pool *pbl_pool;
21561         u32 txcmplq_cnt;
21562
21563         qp = &phba->sli4_hba.hdwq[hwqid];
21564         multixri_pool = qp->p_multixri_pool;
21565         if (!multixri_pool)
21566                 return;
21567
21568         if (multixri_pool->stat_snapshot_taken == LPFC_MXP_SNAPSHOT_TAKEN) {
21569                 pvt_pool = &qp->p_multixri_pool->pvt_pool;
21570                 pbl_pool = &qp->p_multixri_pool->pbl_pool;
21571                 txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21572
21573                 multixri_pool->stat_pbl_count = pbl_pool->count;
21574                 multixri_pool->stat_pvt_count = pvt_pool->count;
21575                 multixri_pool->stat_busy_count = txcmplq_cnt;
21576         }
21577
21578         multixri_pool->stat_snapshot_taken++;
21579 }
21580 #endif
21581
21582 /**
21583  * lpfc_adjust_pvt_pool_count - Adjust private pool count
21584  * @phba: pointer to lpfc hba data structure.
21585  * @hwqid: belong to which HWQ.
21586  *
21587  * This routine moves some XRIs from private to public pool when private pool
21588  * is not busy.
21589  **/
21590 void lpfc_adjust_pvt_pool_count(struct lpfc_hba *phba, u32 hwqid)
21591 {
21592         struct lpfc_multixri_pool *multixri_pool;
21593         u32 io_req_count;
21594         u32 prev_io_req_count;
21595
21596         multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21597         if (!multixri_pool)
21598                 return;
21599         io_req_count = multixri_pool->io_req_count;
21600         prev_io_req_count = multixri_pool->prev_io_req_count;
21601
21602         if (prev_io_req_count != io_req_count) {
21603                 /* Private pool is busy */
21604                 multixri_pool->prev_io_req_count = io_req_count;
21605         } else {
21606                 /* Private pool is not busy.
21607                  * Move XRIs from private to public pool.
21608                  */
21609                 lpfc_move_xri_pvt_to_pbl(phba, hwqid);
21610         }
21611 }
21612
21613 /**
21614  * lpfc_adjust_high_watermark - Adjust high watermark
21615  * @phba: pointer to lpfc hba data structure.
21616  * @hwqid: belong to which HWQ.
21617  *
21618  * This routine sets high watermark as number of outstanding XRIs,
21619  * but make sure the new value is between xri_limit/2 and xri_limit.
21620  **/
21621 void lpfc_adjust_high_watermark(struct lpfc_hba *phba, u32 hwqid)
21622 {
21623         u32 new_watermark;
21624         u32 watermark_max;
21625         u32 watermark_min;
21626         u32 xri_limit;
21627         u32 txcmplq_cnt;
21628         u32 abts_io_bufs;
21629         struct lpfc_multixri_pool *multixri_pool;
21630         struct lpfc_sli4_hdw_queue *qp;
21631
21632         qp = &phba->sli4_hba.hdwq[hwqid];
21633         multixri_pool = qp->p_multixri_pool;
21634         if (!multixri_pool)
21635                 return;
21636         xri_limit = multixri_pool->xri_limit;
21637
21638         watermark_max = xri_limit;
21639         watermark_min = xri_limit / 2;
21640
21641         txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21642         abts_io_bufs = qp->abts_scsi_io_bufs;
21643         abts_io_bufs += qp->abts_nvme_io_bufs;
21644
21645         new_watermark = txcmplq_cnt + abts_io_bufs;
21646         new_watermark = min(watermark_max, new_watermark);
21647         new_watermark = max(watermark_min, new_watermark);
21648         multixri_pool->pvt_pool.high_watermark = new_watermark;
21649
21650 #ifdef LPFC_MXP_STAT
21651         multixri_pool->stat_max_hwm = max(multixri_pool->stat_max_hwm,
21652                                           new_watermark);
21653 #endif
21654 }
21655
21656 /**
21657  * lpfc_move_xri_pvt_to_pbl - Move some XRIs from private to public pool
21658  * @phba: pointer to lpfc hba data structure.
21659  * @hwqid: belong to which HWQ.
21660  *
21661  * This routine is called from hearbeat timer when pvt_pool is idle.
21662  * All free XRIs are moved from private to public pool on hwqid with 2 steps.
21663  * The first step moves (all - low_watermark) amount of XRIs.
21664  * The second step moves the rest of XRIs.
21665  **/
21666 void lpfc_move_xri_pvt_to_pbl(struct lpfc_hba *phba, u32 hwqid)
21667 {
21668         struct lpfc_pbl_pool *pbl_pool;
21669         struct lpfc_pvt_pool *pvt_pool;
21670         struct lpfc_sli4_hdw_queue *qp;
21671         struct lpfc_io_buf *lpfc_ncmd;
21672         struct lpfc_io_buf *lpfc_ncmd_next;
21673         unsigned long iflag;
21674         struct list_head tmp_list;
21675         u32 tmp_count;
21676
21677         qp = &phba->sli4_hba.hdwq[hwqid];
21678         pbl_pool = &qp->p_multixri_pool->pbl_pool;
21679         pvt_pool = &qp->p_multixri_pool->pvt_pool;
21680         tmp_count = 0;
21681
21682         lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag, qp, mv_to_pub_pool);
21683         lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_from_pvt_pool);
21684
21685         if (pvt_pool->count > pvt_pool->low_watermark) {
21686                 /* Step 1: move (all - low_watermark) from pvt_pool
21687                  * to pbl_pool
21688                  */
21689
21690                 /* Move low watermark of bufs from pvt_pool to tmp_list */
21691                 INIT_LIST_HEAD(&tmp_list);
21692                 list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21693                                          &pvt_pool->list, list) {
21694                         list_move_tail(&lpfc_ncmd->list, &tmp_list);
21695                         tmp_count++;
21696                         if (tmp_count >= pvt_pool->low_watermark)
21697                                 break;
21698                 }
21699
21700                 /* Move all bufs from pvt_pool to pbl_pool */
21701                 list_splice_init(&pvt_pool->list, &pbl_pool->list);
21702
21703                 /* Move all bufs from tmp_list to pvt_pool */
21704                 list_splice(&tmp_list, &pvt_pool->list);
21705
21706                 pbl_pool->count += (pvt_pool->count - tmp_count);
21707                 pvt_pool->count = tmp_count;
21708         } else {
21709                 /* Step 2: move the rest from pvt_pool to pbl_pool */
21710                 list_splice_init(&pvt_pool->list, &pbl_pool->list);
21711                 pbl_pool->count += pvt_pool->count;
21712                 pvt_pool->count = 0;
21713         }
21714
21715         spin_unlock(&pvt_pool->lock);
21716         spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21717 }
21718
21719 /**
21720  * _lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21721  * @phba: pointer to lpfc hba data structure
21722  * @qp: pointer to HDW queue
21723  * @pbl_pool: specified public free XRI pool
21724  * @pvt_pool: specified private free XRI pool
21725  * @count: number of XRIs to move
21726  *
21727  * This routine tries to move some free common bufs from the specified pbl_pool
21728  * to the specified pvt_pool. It might move less than count XRIs if there's not
21729  * enough in public pool.
21730  *
21731  * Return:
21732  *   true - if XRIs are successfully moved from the specified pbl_pool to the
21733  *          specified pvt_pool
21734  *   false - if the specified pbl_pool is empty or locked by someone else
21735  **/
21736 static bool
21737 _lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, struct lpfc_sli4_hdw_queue *qp,
21738                           struct lpfc_pbl_pool *pbl_pool,
21739                           struct lpfc_pvt_pool *pvt_pool, u32 count)
21740 {
21741         struct lpfc_io_buf *lpfc_ncmd;
21742         struct lpfc_io_buf *lpfc_ncmd_next;
21743         unsigned long iflag;
21744         int ret;
21745
21746         ret = spin_trylock_irqsave(&pbl_pool->lock, iflag);
21747         if (ret) {
21748                 if (pbl_pool->count) {
21749                         /* Move a batch of XRIs from public to private pool */
21750                         lpfc_qp_spin_lock(&pvt_pool->lock, qp, mv_to_pvt_pool);
21751                         list_for_each_entry_safe(lpfc_ncmd,
21752                                                  lpfc_ncmd_next,
21753                                                  &pbl_pool->list,
21754                                                  list) {
21755                                 list_move_tail(&lpfc_ncmd->list,
21756                                                &pvt_pool->list);
21757                                 pvt_pool->count++;
21758                                 pbl_pool->count--;
21759                                 count--;
21760                                 if (count == 0)
21761                                         break;
21762                         }
21763
21764                         spin_unlock(&pvt_pool->lock);
21765                         spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21766                         return true;
21767                 }
21768                 spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21769         }
21770
21771         return false;
21772 }
21773
21774 /**
21775  * lpfc_move_xri_pbl_to_pvt - Move some XRIs from public to private pool
21776  * @phba: pointer to lpfc hba data structure.
21777  * @hwqid: belong to which HWQ.
21778  * @count: number of XRIs to move
21779  *
21780  * This routine tries to find some free common bufs in one of public pools with
21781  * Round Robin method. The search always starts from local hwqid, then the next
21782  * HWQ which was found last time (rrb_next_hwqid). Once a public pool is found,
21783  * a batch of free common bufs are moved to private pool on hwqid.
21784  * It might move less than count XRIs if there's not enough in public pool.
21785  **/
21786 void lpfc_move_xri_pbl_to_pvt(struct lpfc_hba *phba, u32 hwqid, u32 count)
21787 {
21788         struct lpfc_multixri_pool *multixri_pool;
21789         struct lpfc_multixri_pool *next_multixri_pool;
21790         struct lpfc_pvt_pool *pvt_pool;
21791         struct lpfc_pbl_pool *pbl_pool;
21792         struct lpfc_sli4_hdw_queue *qp;
21793         u32 next_hwqid;
21794         u32 hwq_count;
21795         int ret;
21796
21797         qp = &phba->sli4_hba.hdwq[hwqid];
21798         multixri_pool = qp->p_multixri_pool;
21799         pvt_pool = &multixri_pool->pvt_pool;
21800         pbl_pool = &multixri_pool->pbl_pool;
21801
21802         /* Check if local pbl_pool is available */
21803         ret = _lpfc_move_xri_pbl_to_pvt(phba, qp, pbl_pool, pvt_pool, count);
21804         if (ret) {
21805 #ifdef LPFC_MXP_STAT
21806                 multixri_pool->local_pbl_hit_count++;
21807 #endif
21808                 return;
21809         }
21810
21811         hwq_count = phba->cfg_hdw_queue;
21812
21813         /* Get the next hwqid which was found last time */
21814         next_hwqid = multixri_pool->rrb_next_hwqid;
21815
21816         do {
21817                 /* Go to next hwq */
21818                 next_hwqid = (next_hwqid + 1) % hwq_count;
21819
21820                 next_multixri_pool =
21821                         phba->sli4_hba.hdwq[next_hwqid].p_multixri_pool;
21822                 pbl_pool = &next_multixri_pool->pbl_pool;
21823
21824                 /* Check if the public free xri pool is available */
21825                 ret = _lpfc_move_xri_pbl_to_pvt(
21826                         phba, qp, pbl_pool, pvt_pool, count);
21827
21828                 /* Exit while-loop if success or all hwqid are checked */
21829         } while (!ret && next_hwqid != multixri_pool->rrb_next_hwqid);
21830
21831         /* Starting point for the next time */
21832         multixri_pool->rrb_next_hwqid = next_hwqid;
21833
21834         if (!ret) {
21835                 /* stats: all public pools are empty*/
21836                 multixri_pool->pbl_empty_count++;
21837         }
21838
21839 #ifdef LPFC_MXP_STAT
21840         if (ret) {
21841                 if (next_hwqid == hwqid)
21842                         multixri_pool->local_pbl_hit_count++;
21843                 else
21844                         multixri_pool->other_pbl_hit_count++;
21845         }
21846 #endif
21847 }
21848
21849 /**
21850  * lpfc_keep_pvt_pool_above_lowwm - Keep pvt_pool above low watermark
21851  * @phba: pointer to lpfc hba data structure.
21852  * @hwqid: belong to which HWQ.
21853  *
21854  * This routine get a batch of XRIs from pbl_pool if pvt_pool is less than
21855  * low watermark.
21856  **/
21857 void lpfc_keep_pvt_pool_above_lowwm(struct lpfc_hba *phba, u32 hwqid)
21858 {
21859         struct lpfc_multixri_pool *multixri_pool;
21860         struct lpfc_pvt_pool *pvt_pool;
21861
21862         multixri_pool = phba->sli4_hba.hdwq[hwqid].p_multixri_pool;
21863         pvt_pool = &multixri_pool->pvt_pool;
21864
21865         if (pvt_pool->count < pvt_pool->low_watermark)
21866                 lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
21867 }
21868
21869 /**
21870  * lpfc_release_io_buf - Return one IO buf back to free pool
21871  * @phba: pointer to lpfc hba data structure.
21872  * @lpfc_ncmd: IO buf to be returned.
21873  * @qp: belong to which HWQ.
21874  *
21875  * This routine returns one IO buf back to free pool. If this is an urgent IO,
21876  * the IO buf is returned to expedite pool. If cfg_xri_rebalancing==1,
21877  * the IO buf is returned to pbl_pool or pvt_pool based on watermark and
21878  * xri_limit.  If cfg_xri_rebalancing==0, the IO buf is returned to
21879  * lpfc_io_buf_list_put.
21880  **/
21881 void lpfc_release_io_buf(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_ncmd,
21882                          struct lpfc_sli4_hdw_queue *qp)
21883 {
21884         unsigned long iflag;
21885         struct lpfc_pbl_pool *pbl_pool;
21886         struct lpfc_pvt_pool *pvt_pool;
21887         struct lpfc_epd_pool *epd_pool;
21888         u32 txcmplq_cnt;
21889         u32 xri_owned;
21890         u32 xri_limit;
21891         u32 abts_io_bufs;
21892
21893         /* MUST zero fields if buffer is reused by another protocol */
21894         lpfc_ncmd->nvmeCmd = NULL;
21895         lpfc_ncmd->cur_iocbq.cmd_cmpl = NULL;
21896
21897         if (phba->cfg_xpsgl && !phba->nvmet_support &&
21898             !list_empty(&lpfc_ncmd->dma_sgl_xtra_list))
21899                 lpfc_put_sgl_per_hdwq(phba, lpfc_ncmd);
21900
21901         if (!list_empty(&lpfc_ncmd->dma_cmd_rsp_list))
21902                 lpfc_put_cmd_rsp_buf_per_hdwq(phba, lpfc_ncmd);
21903
21904         if (phba->cfg_xri_rebalancing) {
21905                 if (lpfc_ncmd->expedite) {
21906                         /* Return to expedite pool */
21907                         epd_pool = &phba->epd_pool;
21908                         spin_lock_irqsave(&epd_pool->lock, iflag);
21909                         list_add_tail(&lpfc_ncmd->list, &epd_pool->list);
21910                         epd_pool->count++;
21911                         spin_unlock_irqrestore(&epd_pool->lock, iflag);
21912                         return;
21913                 }
21914
21915                 /* Avoid invalid access if an IO sneaks in and is being rejected
21916                  * just _after_ xri pools are destroyed in lpfc_offline.
21917                  * Nothing much can be done at this point.
21918                  */
21919                 if (!qp->p_multixri_pool)
21920                         return;
21921
21922                 pbl_pool = &qp->p_multixri_pool->pbl_pool;
21923                 pvt_pool = &qp->p_multixri_pool->pvt_pool;
21924
21925                 txcmplq_cnt = qp->io_wq->pring->txcmplq_cnt;
21926                 abts_io_bufs = qp->abts_scsi_io_bufs;
21927                 abts_io_bufs += qp->abts_nvme_io_bufs;
21928
21929                 xri_owned = pvt_pool->count + txcmplq_cnt + abts_io_bufs;
21930                 xri_limit = qp->p_multixri_pool->xri_limit;
21931
21932 #ifdef LPFC_MXP_STAT
21933                 if (xri_owned <= xri_limit)
21934                         qp->p_multixri_pool->below_limit_count++;
21935                 else
21936                         qp->p_multixri_pool->above_limit_count++;
21937 #endif
21938
21939                 /* XRI goes to either public or private free xri pool
21940                  *     based on watermark and xri_limit
21941                  */
21942                 if ((pvt_pool->count < pvt_pool->low_watermark) ||
21943                     (xri_owned < xri_limit &&
21944                      pvt_pool->count < pvt_pool->high_watermark)) {
21945                         lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag,
21946                                                   qp, free_pvt_pool);
21947                         list_add_tail(&lpfc_ncmd->list,
21948                                       &pvt_pool->list);
21949                         pvt_pool->count++;
21950                         spin_unlock_irqrestore(&pvt_pool->lock, iflag);
21951                 } else {
21952                         lpfc_qp_spin_lock_irqsave(&pbl_pool->lock, iflag,
21953                                                   qp, free_pub_pool);
21954                         list_add_tail(&lpfc_ncmd->list,
21955                                       &pbl_pool->list);
21956                         pbl_pool->count++;
21957                         spin_unlock_irqrestore(&pbl_pool->lock, iflag);
21958                 }
21959         } else {
21960                 lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_put_lock, iflag,
21961                                           qp, free_xri);
21962                 list_add_tail(&lpfc_ncmd->list,
21963                               &qp->lpfc_io_buf_list_put);
21964                 qp->put_io_bufs++;
21965                 spin_unlock_irqrestore(&qp->io_buf_list_put_lock,
21966                                        iflag);
21967         }
21968 }
21969
21970 /**
21971  * lpfc_get_io_buf_from_private_pool - Get one free IO buf from private pool
21972  * @phba: pointer to lpfc hba data structure.
21973  * @qp: pointer to HDW queue
21974  * @pvt_pool: pointer to private pool data structure.
21975  * @ndlp: pointer to lpfc nodelist data structure.
21976  *
21977  * This routine tries to get one free IO buf from private pool.
21978  *
21979  * Return:
21980  *   pointer to one free IO buf - if private pool is not empty
21981  *   NULL - if private pool is empty
21982  **/
21983 static struct lpfc_io_buf *
21984 lpfc_get_io_buf_from_private_pool(struct lpfc_hba *phba,
21985                                   struct lpfc_sli4_hdw_queue *qp,
21986                                   struct lpfc_pvt_pool *pvt_pool,
21987                                   struct lpfc_nodelist *ndlp)
21988 {
21989         struct lpfc_io_buf *lpfc_ncmd;
21990         struct lpfc_io_buf *lpfc_ncmd_next;
21991         unsigned long iflag;
21992
21993         lpfc_qp_spin_lock_irqsave(&pvt_pool->lock, iflag, qp, alloc_pvt_pool);
21994         list_for_each_entry_safe(lpfc_ncmd, lpfc_ncmd_next,
21995                                  &pvt_pool->list, list) {
21996                 if (lpfc_test_rrq_active(
21997                         phba, ndlp, lpfc_ncmd->cur_iocbq.sli4_lxritag))
21998                         continue;
21999                 list_del(&lpfc_ncmd->list);
22000                 pvt_pool->count--;
22001                 spin_unlock_irqrestore(&pvt_pool->lock, iflag);
22002                 return lpfc_ncmd;
22003         }
22004         spin_unlock_irqrestore(&pvt_pool->lock, iflag);
22005
22006         return NULL;
22007 }
22008
22009 /**
22010  * lpfc_get_io_buf_from_expedite_pool - Get one free IO buf from expedite pool
22011  * @phba: pointer to lpfc hba data structure.
22012  *
22013  * This routine tries to get one free IO buf from expedite pool.
22014  *
22015  * Return:
22016  *   pointer to one free IO buf - if expedite pool is not empty
22017  *   NULL - if expedite pool is empty
22018  **/
22019 static struct lpfc_io_buf *
22020 lpfc_get_io_buf_from_expedite_pool(struct lpfc_hba *phba)
22021 {
22022         struct lpfc_io_buf *lpfc_ncmd = NULL, *iter;
22023         struct lpfc_io_buf *lpfc_ncmd_next;
22024         unsigned long iflag;
22025         struct lpfc_epd_pool *epd_pool;
22026
22027         epd_pool = &phba->epd_pool;
22028
22029         spin_lock_irqsave(&epd_pool->lock, iflag);
22030         if (epd_pool->count > 0) {
22031                 list_for_each_entry_safe(iter, lpfc_ncmd_next,
22032                                          &epd_pool->list, list) {
22033                         list_del(&iter->list);
22034                         epd_pool->count--;
22035                         lpfc_ncmd = iter;
22036                         break;
22037                 }
22038         }
22039         spin_unlock_irqrestore(&epd_pool->lock, iflag);
22040
22041         return lpfc_ncmd;
22042 }
22043
22044 /**
22045  * lpfc_get_io_buf_from_multixri_pools - Get one free IO bufs
22046  * @phba: pointer to lpfc hba data structure.
22047  * @ndlp: pointer to lpfc nodelist data structure.
22048  * @hwqid: belong to which HWQ
22049  * @expedite: 1 means this request is urgent.
22050  *
22051  * This routine will do the following actions and then return a pointer to
22052  * one free IO buf.
22053  *
22054  * 1. If private free xri count is empty, move some XRIs from public to
22055  *    private pool.
22056  * 2. Get one XRI from private free xri pool.
22057  * 3. If we fail to get one from pvt_pool and this is an expedite request,
22058  *    get one free xri from expedite pool.
22059  *
22060  * Note: ndlp is only used on SCSI side for RRQ testing.
22061  *       The caller should pass NULL for ndlp on NVME side.
22062  *
22063  * Return:
22064  *   pointer to one free IO buf - if private pool is not empty
22065  *   NULL - if private pool is empty
22066  **/
22067 static struct lpfc_io_buf *
22068 lpfc_get_io_buf_from_multixri_pools(struct lpfc_hba *phba,
22069                                     struct lpfc_nodelist *ndlp,
22070                                     int hwqid, int expedite)
22071 {
22072         struct lpfc_sli4_hdw_queue *qp;
22073         struct lpfc_multixri_pool *multixri_pool;
22074         struct lpfc_pvt_pool *pvt_pool;
22075         struct lpfc_io_buf *lpfc_ncmd;
22076
22077         qp = &phba->sli4_hba.hdwq[hwqid];
22078         lpfc_ncmd = NULL;
22079         if (!qp) {
22080                 lpfc_printf_log(phba, KERN_INFO,
22081                                 LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22082                                 "5556 NULL qp for hwqid  x%x\n", hwqid);
22083                 return lpfc_ncmd;
22084         }
22085         multixri_pool = qp->p_multixri_pool;
22086         if (!multixri_pool) {
22087                 lpfc_printf_log(phba, KERN_INFO,
22088                                 LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22089                                 "5557 NULL multixri for hwqid  x%x\n", hwqid);
22090                 return lpfc_ncmd;
22091         }
22092         pvt_pool = &multixri_pool->pvt_pool;
22093         if (!pvt_pool) {
22094                 lpfc_printf_log(phba, KERN_INFO,
22095                                 LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22096                                 "5558 NULL pvt_pool for hwqid  x%x\n", hwqid);
22097                 return lpfc_ncmd;
22098         }
22099         multixri_pool->io_req_count++;
22100
22101         /* If pvt_pool is empty, move some XRIs from public to private pool */
22102         if (pvt_pool->count == 0)
22103                 lpfc_move_xri_pbl_to_pvt(phba, hwqid, XRI_BATCH);
22104
22105         /* Get one XRI from private free xri pool */
22106         lpfc_ncmd = lpfc_get_io_buf_from_private_pool(phba, qp, pvt_pool, ndlp);
22107
22108         if (lpfc_ncmd) {
22109                 lpfc_ncmd->hdwq = qp;
22110                 lpfc_ncmd->hdwq_no = hwqid;
22111         } else if (expedite) {
22112                 /* If we fail to get one from pvt_pool and this is an expedite
22113                  * request, get one free xri from expedite pool.
22114                  */
22115                 lpfc_ncmd = lpfc_get_io_buf_from_expedite_pool(phba);
22116         }
22117
22118         return lpfc_ncmd;
22119 }
22120
22121 static inline struct lpfc_io_buf *
22122 lpfc_io_buf(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp, int idx)
22123 {
22124         struct lpfc_sli4_hdw_queue *qp;
22125         struct lpfc_io_buf *lpfc_cmd, *lpfc_cmd_next;
22126
22127         qp = &phba->sli4_hba.hdwq[idx];
22128         list_for_each_entry_safe(lpfc_cmd, lpfc_cmd_next,
22129                                  &qp->lpfc_io_buf_list_get, list) {
22130                 if (lpfc_test_rrq_active(phba, ndlp,
22131                                          lpfc_cmd->cur_iocbq.sli4_lxritag))
22132                         continue;
22133
22134                 if (lpfc_cmd->flags & LPFC_SBUF_NOT_POSTED)
22135                         continue;
22136
22137                 list_del_init(&lpfc_cmd->list);
22138                 qp->get_io_bufs--;
22139                 lpfc_cmd->hdwq = qp;
22140                 lpfc_cmd->hdwq_no = idx;
22141                 return lpfc_cmd;
22142         }
22143         return NULL;
22144 }
22145
22146 /**
22147  * lpfc_get_io_buf - Get one IO buffer from free pool
22148  * @phba: The HBA for which this call is being executed.
22149  * @ndlp: pointer to lpfc nodelist data structure.
22150  * @hwqid: belong to which HWQ
22151  * @expedite: 1 means this request is urgent.
22152  *
22153  * This routine gets one IO buffer from free pool. If cfg_xri_rebalancing==1,
22154  * removes a IO buffer from multiXRI pools. If cfg_xri_rebalancing==0, removes
22155  * a IO buffer from head of @hdwq io_buf_list and returns to caller.
22156  *
22157  * Note: ndlp is only used on SCSI side for RRQ testing.
22158  *       The caller should pass NULL for ndlp on NVME side.
22159  *
22160  * Return codes:
22161  *   NULL - Error
22162  *   Pointer to lpfc_io_buf - Success
22163  **/
22164 struct lpfc_io_buf *lpfc_get_io_buf(struct lpfc_hba *phba,
22165                                     struct lpfc_nodelist *ndlp,
22166                                     u32 hwqid, int expedite)
22167 {
22168         struct lpfc_sli4_hdw_queue *qp;
22169         unsigned long iflag;
22170         struct lpfc_io_buf *lpfc_cmd;
22171
22172         qp = &phba->sli4_hba.hdwq[hwqid];
22173         lpfc_cmd = NULL;
22174         if (!qp) {
22175                 lpfc_printf_log(phba, KERN_WARNING,
22176                                 LOG_SLI | LOG_NVME_ABTS | LOG_FCP,
22177                                 "5555 NULL qp for hwqid  x%x\n", hwqid);
22178                 return lpfc_cmd;
22179         }
22180
22181         if (phba->cfg_xri_rebalancing)
22182                 lpfc_cmd = lpfc_get_io_buf_from_multixri_pools(
22183                         phba, ndlp, hwqid, expedite);
22184         else {
22185                 lpfc_qp_spin_lock_irqsave(&qp->io_buf_list_get_lock, iflag,
22186                                           qp, alloc_xri_get);
22187                 if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT || expedite)
22188                         lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22189                 if (!lpfc_cmd) {
22190                         lpfc_qp_spin_lock(&qp->io_buf_list_put_lock,
22191                                           qp, alloc_xri_put);
22192                         list_splice(&qp->lpfc_io_buf_list_put,
22193                                     &qp->lpfc_io_buf_list_get);
22194                         qp->get_io_bufs += qp->put_io_bufs;
22195                         INIT_LIST_HEAD(&qp->lpfc_io_buf_list_put);
22196                         qp->put_io_bufs = 0;
22197                         spin_unlock(&qp->io_buf_list_put_lock);
22198                         if (qp->get_io_bufs > LPFC_NVME_EXPEDITE_XRICNT ||
22199                             expedite)
22200                                 lpfc_cmd = lpfc_io_buf(phba, ndlp, hwqid);
22201                 }
22202                 spin_unlock_irqrestore(&qp->io_buf_list_get_lock, iflag);
22203         }
22204
22205         return lpfc_cmd;
22206 }
22207
22208 /**
22209  * lpfc_read_object - Retrieve object data from HBA
22210  * @phba: The HBA for which this call is being executed.
22211  * @rdobject: Pathname of object data we want to read.
22212  * @datap: Pointer to where data will be copied to.
22213  * @datasz: size of data area
22214  *
22215  * This routine is limited to object sizes of LPFC_BPL_SIZE (1024) or less.
22216  * The data will be truncated if datasz is not large enough.
22217  * Version 1 is not supported with Embedded mbox cmd, so we must use version 0.
22218  * Returns the actual bytes read from the object.
22219  *
22220  * This routine is hard coded to use a poll completion.  Unlike other
22221  * sli4_config mailboxes, it uses lpfc_mbuf memory which is not
22222  * cleaned up in lpfc_sli4_cmd_mbox_free.  If this routine is modified
22223  * to use interrupt-based completions, code is needed to fully cleanup
22224  * the memory.
22225  */
22226 int
22227 lpfc_read_object(struct lpfc_hba *phba, char *rdobject, uint32_t *datap,
22228                  uint32_t datasz)
22229 {
22230         struct lpfc_mbx_read_object *read_object;
22231         LPFC_MBOXQ_t *mbox;
22232         int rc, length, eof, j, byte_cnt = 0;
22233         uint32_t shdr_status, shdr_add_status;
22234         union lpfc_sli4_cfg_shdr *shdr;
22235         struct lpfc_dmabuf *pcmd;
22236         u32 rd_object_name[LPFC_MBX_OBJECT_NAME_LEN_DW] = {0};
22237
22238         mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
22239         if (!mbox)
22240                 return -ENOMEM;
22241         length = (sizeof(struct lpfc_mbx_read_object) -
22242                   sizeof(struct lpfc_sli4_cfg_mhdr));
22243         lpfc_sli4_config(phba, mbox, LPFC_MBOX_SUBSYSTEM_COMMON,
22244                          LPFC_MBOX_OPCODE_READ_OBJECT,
22245                          length, LPFC_SLI4_MBX_EMBED);
22246         read_object = &mbox->u.mqe.un.read_object;
22247         shdr = (union lpfc_sli4_cfg_shdr *)&read_object->header.cfg_shdr;
22248
22249         bf_set(lpfc_mbox_hdr_version, &shdr->request, LPFC_Q_CREATE_VERSION_0);
22250         bf_set(lpfc_mbx_rd_object_rlen, &read_object->u.request, datasz);
22251         read_object->u.request.rd_object_offset = 0;
22252         read_object->u.request.rd_object_cnt = 1;
22253
22254         memset((void *)read_object->u.request.rd_object_name, 0,
22255                LPFC_OBJ_NAME_SZ);
22256         scnprintf((char *)rd_object_name, sizeof(rd_object_name), rdobject);
22257         for (j = 0; j < strlen(rdobject); j++)
22258                 read_object->u.request.rd_object_name[j] =
22259                         cpu_to_le32(rd_object_name[j]);
22260
22261         pcmd = kmalloc(sizeof(*pcmd), GFP_KERNEL);
22262         if (pcmd)
22263                 pcmd->virt = lpfc_mbuf_alloc(phba, MEM_PRI, &pcmd->phys);
22264         if (!pcmd || !pcmd->virt) {
22265                 kfree(pcmd);
22266                 mempool_free(mbox, phba->mbox_mem_pool);
22267                 return -ENOMEM;
22268         }
22269         memset((void *)pcmd->virt, 0, LPFC_BPL_SIZE);
22270         read_object->u.request.rd_object_hbuf[0].pa_lo =
22271                 putPaddrLow(pcmd->phys);
22272         read_object->u.request.rd_object_hbuf[0].pa_hi =
22273                 putPaddrHigh(pcmd->phys);
22274         read_object->u.request.rd_object_hbuf[0].length = LPFC_BPL_SIZE;
22275
22276         mbox->vport = phba->pport;
22277         mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
22278         mbox->ctx_ndlp = NULL;
22279
22280         rc = lpfc_sli_issue_mbox(phba, mbox, MBX_POLL);
22281         shdr_status = bf_get(lpfc_mbox_hdr_status, &shdr->response);
22282         shdr_add_status = bf_get(lpfc_mbox_hdr_add_status, &shdr->response);
22283
22284         if (shdr_status == STATUS_FAILED &&
22285             shdr_add_status == ADD_STATUS_INVALID_OBJECT_NAME) {
22286                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22287                                 "4674 No port cfg file in FW.\n");
22288                 byte_cnt = -ENOENT;
22289         } else if (shdr_status || shdr_add_status || rc) {
22290                 lpfc_printf_log(phba, KERN_ERR, LOG_INIT | LOG_CGN_MGMT,
22291                                 "2625 READ_OBJECT mailbox failed with "
22292                                 "status x%x add_status x%x, mbx status x%x\n",
22293                                 shdr_status, shdr_add_status, rc);
22294                 byte_cnt = -ENXIO;
22295         } else {
22296                 /* Success */
22297                 length = read_object->u.response.rd_object_actual_rlen;
22298                 eof = bf_get(lpfc_mbx_rd_object_eof, &read_object->u.response);
22299                 lpfc_printf_log(phba, KERN_INFO, LOG_INIT | LOG_CGN_MGMT,
22300                                 "2626 READ_OBJECT Success len %d:%d, EOF %d\n",
22301                                 length, datasz, eof);
22302
22303                 /* Detect the port config file exists but is empty */
22304                 if (!length && eof) {
22305                         byte_cnt = 0;
22306                         goto exit;
22307                 }
22308
22309                 byte_cnt = length;
22310                 lpfc_sli_pcimem_bcopy(pcmd->virt, datap, byte_cnt);
22311         }
22312
22313  exit:
22314         /* This is an embedded SLI4 mailbox with an external buffer allocated.
22315          * Free the pcmd and then cleanup with the correct routine.
22316          */
22317         lpfc_mbuf_free(phba, pcmd->virt, pcmd->phys);
22318         kfree(pcmd);
22319         lpfc_sli4_mbox_cmd_free(phba, mbox);
22320         return byte_cnt;
22321 }
22322
22323 /**
22324  * lpfc_get_sgl_per_hdwq - Get one SGL chunk from hdwq's pool
22325  * @phba: The HBA for which this call is being executed.
22326  * @lpfc_buf: IO buf structure to append the SGL chunk
22327  *
22328  * This routine gets one SGL chunk buffer from hdwq's SGL chunk pool,
22329  * and will allocate an SGL chunk if the pool is empty.
22330  *
22331  * Return codes:
22332  *   NULL - Error
22333  *   Pointer to sli4_hybrid_sgl - Success
22334  **/
22335 struct sli4_hybrid_sgl *
22336 lpfc_get_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22337 {
22338         struct sli4_hybrid_sgl *list_entry = NULL;
22339         struct sli4_hybrid_sgl *tmp = NULL;
22340         struct sli4_hybrid_sgl *allocated_sgl = NULL;
22341         struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22342         struct list_head *buf_list = &hdwq->sgl_list;
22343         unsigned long iflags;
22344
22345         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22346
22347         if (likely(!list_empty(buf_list))) {
22348                 /* break off 1 chunk from the sgl_list */
22349                 list_for_each_entry_safe(list_entry, tmp,
22350                                          buf_list, list_node) {
22351                         list_move_tail(&list_entry->list_node,
22352                                        &lpfc_buf->dma_sgl_xtra_list);
22353                         break;
22354                 }
22355         } else {
22356                 /* allocate more */
22357                 spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22358                 tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22359                                    cpu_to_node(hdwq->io_wq->chann));
22360                 if (!tmp) {
22361                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22362                                         "8353 error kmalloc memory for HDWQ "
22363                                         "%d %s\n",
22364                                         lpfc_buf->hdwq_no, __func__);
22365                         return NULL;
22366                 }
22367
22368                 tmp->dma_sgl = dma_pool_alloc(phba->lpfc_sg_dma_buf_pool,
22369                                               GFP_ATOMIC, &tmp->dma_phys_sgl);
22370                 if (!tmp->dma_sgl) {
22371                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22372                                         "8354 error pool_alloc memory for HDWQ "
22373                                         "%d %s\n",
22374                                         lpfc_buf->hdwq_no, __func__);
22375                         kfree(tmp);
22376                         return NULL;
22377                 }
22378
22379                 spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22380                 list_add_tail(&tmp->list_node, &lpfc_buf->dma_sgl_xtra_list);
22381         }
22382
22383         allocated_sgl = list_last_entry(&lpfc_buf->dma_sgl_xtra_list,
22384                                         struct sli4_hybrid_sgl,
22385                                         list_node);
22386
22387         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22388
22389         return allocated_sgl;
22390 }
22391
22392 /**
22393  * lpfc_put_sgl_per_hdwq - Put one SGL chunk into hdwq pool
22394  * @phba: The HBA for which this call is being executed.
22395  * @lpfc_buf: IO buf structure with the SGL chunk
22396  *
22397  * This routine puts one SGL chunk buffer into hdwq's SGL chunk pool.
22398  *
22399  * Return codes:
22400  *   0 - Success
22401  *   -EINVAL - Error
22402  **/
22403 int
22404 lpfc_put_sgl_per_hdwq(struct lpfc_hba *phba, struct lpfc_io_buf *lpfc_buf)
22405 {
22406         int rc = 0;
22407         struct sli4_hybrid_sgl *list_entry = NULL;
22408         struct sli4_hybrid_sgl *tmp = NULL;
22409         struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22410         struct list_head *buf_list = &hdwq->sgl_list;
22411         unsigned long iflags;
22412
22413         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22414
22415         if (likely(!list_empty(&lpfc_buf->dma_sgl_xtra_list))) {
22416                 list_for_each_entry_safe(list_entry, tmp,
22417                                          &lpfc_buf->dma_sgl_xtra_list,
22418                                          list_node) {
22419                         list_move_tail(&list_entry->list_node,
22420                                        buf_list);
22421                 }
22422         } else {
22423                 rc = -EINVAL;
22424         }
22425
22426         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22427         return rc;
22428 }
22429
22430 /**
22431  * lpfc_free_sgl_per_hdwq - Free all SGL chunks of hdwq pool
22432  * @phba: phba object
22433  * @hdwq: hdwq to cleanup sgl buff resources on
22434  *
22435  * This routine frees all SGL chunks of hdwq SGL chunk pool.
22436  *
22437  * Return codes:
22438  *   None
22439  **/
22440 void
22441 lpfc_free_sgl_per_hdwq(struct lpfc_hba *phba,
22442                        struct lpfc_sli4_hdw_queue *hdwq)
22443 {
22444         struct list_head *buf_list = &hdwq->sgl_list;
22445         struct sli4_hybrid_sgl *list_entry = NULL;
22446         struct sli4_hybrid_sgl *tmp = NULL;
22447         unsigned long iflags;
22448
22449         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22450
22451         /* Free sgl pool */
22452         list_for_each_entry_safe(list_entry, tmp,
22453                                  buf_list, list_node) {
22454                 list_del(&list_entry->list_node);
22455                 dma_pool_free(phba->lpfc_sg_dma_buf_pool,
22456                               list_entry->dma_sgl,
22457                               list_entry->dma_phys_sgl);
22458                 kfree(list_entry);
22459         }
22460
22461         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22462 }
22463
22464 /**
22465  * lpfc_get_cmd_rsp_buf_per_hdwq - Get one CMD/RSP buffer from hdwq
22466  * @phba: The HBA for which this call is being executed.
22467  * @lpfc_buf: IO buf structure to attach the CMD/RSP buffer
22468  *
22469  * This routine gets one CMD/RSP buffer from hdwq's CMD/RSP pool,
22470  * and will allocate an CMD/RSP buffer if the pool is empty.
22471  *
22472  * Return codes:
22473  *   NULL - Error
22474  *   Pointer to fcp_cmd_rsp_buf - Success
22475  **/
22476 struct fcp_cmd_rsp_buf *
22477 lpfc_get_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22478                               struct lpfc_io_buf *lpfc_buf)
22479 {
22480         struct fcp_cmd_rsp_buf *list_entry = NULL;
22481         struct fcp_cmd_rsp_buf *tmp = NULL;
22482         struct fcp_cmd_rsp_buf *allocated_buf = NULL;
22483         struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22484         struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22485         unsigned long iflags;
22486
22487         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22488
22489         if (likely(!list_empty(buf_list))) {
22490                 /* break off 1 chunk from the list */
22491                 list_for_each_entry_safe(list_entry, tmp,
22492                                          buf_list,
22493                                          list_node) {
22494                         list_move_tail(&list_entry->list_node,
22495                                        &lpfc_buf->dma_cmd_rsp_list);
22496                         break;
22497                 }
22498         } else {
22499                 /* allocate more */
22500                 spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22501                 tmp = kmalloc_node(sizeof(*tmp), GFP_ATOMIC,
22502                                    cpu_to_node(hdwq->io_wq->chann));
22503                 if (!tmp) {
22504                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22505                                         "8355 error kmalloc memory for HDWQ "
22506                                         "%d %s\n",
22507                                         lpfc_buf->hdwq_no, __func__);
22508                         return NULL;
22509                 }
22510
22511                 tmp->fcp_cmnd = dma_pool_zalloc(phba->lpfc_cmd_rsp_buf_pool,
22512                                                 GFP_ATOMIC,
22513                                                 &tmp->fcp_cmd_rsp_dma_handle);
22514
22515                 if (!tmp->fcp_cmnd) {
22516                         lpfc_printf_log(phba, KERN_INFO, LOG_SLI,
22517                                         "8356 error pool_alloc memory for HDWQ "
22518                                         "%d %s\n",
22519                                         lpfc_buf->hdwq_no, __func__);
22520                         kfree(tmp);
22521                         return NULL;
22522                 }
22523
22524                 tmp->fcp_rsp = (struct fcp_rsp *)((uint8_t *)tmp->fcp_cmnd +
22525                                 sizeof(struct fcp_cmnd32));
22526
22527                 spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22528                 list_add_tail(&tmp->list_node, &lpfc_buf->dma_cmd_rsp_list);
22529         }
22530
22531         allocated_buf = list_last_entry(&lpfc_buf->dma_cmd_rsp_list,
22532                                         struct fcp_cmd_rsp_buf,
22533                                         list_node);
22534
22535         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22536
22537         return allocated_buf;
22538 }
22539
22540 /**
22541  * lpfc_put_cmd_rsp_buf_per_hdwq - Put one CMD/RSP buffer into hdwq pool
22542  * @phba: The HBA for which this call is being executed.
22543  * @lpfc_buf: IO buf structure with the CMD/RSP buf
22544  *
22545  * This routine puts one CMD/RSP buffer into executing CPU's CMD/RSP pool.
22546  *
22547  * Return codes:
22548  *   0 - Success
22549  *   -EINVAL - Error
22550  **/
22551 int
22552 lpfc_put_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22553                               struct lpfc_io_buf *lpfc_buf)
22554 {
22555         int rc = 0;
22556         struct fcp_cmd_rsp_buf *list_entry = NULL;
22557         struct fcp_cmd_rsp_buf *tmp = NULL;
22558         struct lpfc_sli4_hdw_queue *hdwq = lpfc_buf->hdwq;
22559         struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22560         unsigned long iflags;
22561
22562         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22563
22564         if (likely(!list_empty(&lpfc_buf->dma_cmd_rsp_list))) {
22565                 list_for_each_entry_safe(list_entry, tmp,
22566                                          &lpfc_buf->dma_cmd_rsp_list,
22567                                          list_node) {
22568                         list_move_tail(&list_entry->list_node,
22569                                        buf_list);
22570                 }
22571         } else {
22572                 rc = -EINVAL;
22573         }
22574
22575         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22576         return rc;
22577 }
22578
22579 /**
22580  * lpfc_free_cmd_rsp_buf_per_hdwq - Free all CMD/RSP chunks of hdwq pool
22581  * @phba: phba object
22582  * @hdwq: hdwq to cleanup cmd rsp buff resources on
22583  *
22584  * This routine frees all CMD/RSP buffers of hdwq's CMD/RSP buf pool.
22585  *
22586  * Return codes:
22587  *   None
22588  **/
22589 void
22590 lpfc_free_cmd_rsp_buf_per_hdwq(struct lpfc_hba *phba,
22591                                struct lpfc_sli4_hdw_queue *hdwq)
22592 {
22593         struct list_head *buf_list = &hdwq->cmd_rsp_buf_list;
22594         struct fcp_cmd_rsp_buf *list_entry = NULL;
22595         struct fcp_cmd_rsp_buf *tmp = NULL;
22596         unsigned long iflags;
22597
22598         spin_lock_irqsave(&hdwq->hdwq_lock, iflags);
22599
22600         /* Free cmd_rsp buf pool */
22601         list_for_each_entry_safe(list_entry, tmp,
22602                                  buf_list,
22603                                  list_node) {
22604                 list_del(&list_entry->list_node);
22605                 dma_pool_free(phba->lpfc_cmd_rsp_buf_pool,
22606                               list_entry->fcp_cmnd,
22607                               list_entry->fcp_cmd_rsp_dma_handle);
22608                 kfree(list_entry);
22609         }
22610
22611         spin_unlock_irqrestore(&hdwq->hdwq_lock, iflags);
22612 }
22613
22614 /**
22615  * lpfc_sli_prep_wqe - Prepare WQE for the command to be posted
22616  * @phba: phba object
22617  * @job: job entry of the command to be posted.
22618  *
22619  * Fill the common fields of the wqe for each of the command.
22620  *
22621  * Return codes:
22622  *      None
22623  **/
22624 void
22625 lpfc_sli_prep_wqe(struct lpfc_hba *phba, struct lpfc_iocbq *job)
22626 {
22627         u8 cmnd;
22628         u32 *pcmd;
22629         u32 if_type = 0;
22630         u32 abort_tag;
22631         bool fip;
22632         struct lpfc_nodelist *ndlp = NULL;
22633         union lpfc_wqe128 *wqe = &job->wqe;
22634         u8 command_type = ELS_COMMAND_NON_FIP;
22635
22636         fip = test_bit(HBA_FIP_SUPPORT, &phba->hba_flag);
22637         /* The fcp commands will set command type */
22638         if (job->cmd_flag &  LPFC_IO_FCP)
22639                 command_type = FCP_COMMAND;
22640         else if (fip && (job->cmd_flag & LPFC_FIP_ELS_ID_MASK))
22641                 command_type = ELS_COMMAND_FIP;
22642         else
22643                 command_type = ELS_COMMAND_NON_FIP;
22644
22645         abort_tag = job->iotag;
22646         cmnd = bf_get(wqe_cmnd, &wqe->els_req.wqe_com);
22647
22648         switch (cmnd) {
22649         case CMD_ELS_REQUEST64_WQE:
22650                 ndlp = job->ndlp;
22651
22652                 if_type = bf_get(lpfc_sli_intf_if_type,
22653                                  &phba->sli4_hba.sli_intf);
22654                 if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22655                         pcmd = (u32 *)job->cmd_dmabuf->virt;
22656                         if (pcmd && (*pcmd == ELS_CMD_FLOGI ||
22657                                      *pcmd == ELS_CMD_SCR ||
22658                                      *pcmd == ELS_CMD_RDF ||
22659                                      *pcmd == ELS_CMD_EDC ||
22660                                      *pcmd == ELS_CMD_RSCN_XMT ||
22661                                      *pcmd == ELS_CMD_FDISC ||
22662                                      *pcmd == ELS_CMD_LOGO ||
22663                                      *pcmd == ELS_CMD_QFPA ||
22664                                      *pcmd == ELS_CMD_UVEM ||
22665                                      *pcmd == ELS_CMD_PLOGI)) {
22666                                 bf_set(els_req64_sp, &wqe->els_req, 1);
22667                                 bf_set(els_req64_sid, &wqe->els_req,
22668                                        job->vport->fc_myDID);
22669
22670                                 if ((*pcmd == ELS_CMD_FLOGI) &&
22671                                     !(phba->fc_topology ==
22672                                       LPFC_TOPOLOGY_LOOP))
22673                                         bf_set(els_req64_sid, &wqe->els_req, 0);
22674
22675                                 bf_set(wqe_ct, &wqe->els_req.wqe_com, 1);
22676                                 bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22677                                        phba->vpi_ids[job->vport->vpi]);
22678                         } else if (pcmd) {
22679                                 bf_set(wqe_ct, &wqe->els_req.wqe_com, 0);
22680                                 bf_set(wqe_ctxt_tag, &wqe->els_req.wqe_com,
22681                                        phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22682                         }
22683                 }
22684
22685                 bf_set(wqe_temp_rpi, &wqe->els_req.wqe_com,
22686                        phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22687
22688                 bf_set(wqe_dbde, &wqe->els_req.wqe_com, 1);
22689                 bf_set(wqe_iod, &wqe->els_req.wqe_com, LPFC_WQE_IOD_READ);
22690                 bf_set(wqe_qosd, &wqe->els_req.wqe_com, 1);
22691                 bf_set(wqe_lenloc, &wqe->els_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22692                 bf_set(wqe_ebde_cnt, &wqe->els_req.wqe_com, 0);
22693                 break;
22694         case CMD_XMIT_ELS_RSP64_WQE:
22695                 ndlp = job->ndlp;
22696
22697                 /* word4 */
22698                 wqe->xmit_els_rsp.word4 = 0;
22699
22700                 if_type = bf_get(lpfc_sli_intf_if_type,
22701                                  &phba->sli4_hba.sli_intf);
22702                 if (if_type >= LPFC_SLI_INTF_IF_TYPE_2) {
22703                         if (test_bit(FC_PT2PT, &job->vport->fc_flag)) {
22704                                 bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22705                                 bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22706                                        job->vport->fc_myDID);
22707                                 if (job->vport->fc_myDID == Fabric_DID) {
22708                                         bf_set(wqe_els_did,
22709                                                &wqe->xmit_els_rsp.wqe_dest, 0);
22710                                 }
22711                         }
22712                 }
22713
22714                 bf_set(wqe_dbde, &wqe->xmit_els_rsp.wqe_com, 1);
22715                 bf_set(wqe_iod, &wqe->xmit_els_rsp.wqe_com, LPFC_WQE_IOD_WRITE);
22716                 bf_set(wqe_qosd, &wqe->xmit_els_rsp.wqe_com, 1);
22717                 bf_set(wqe_lenloc, &wqe->xmit_els_rsp.wqe_com,
22718                        LPFC_WQE_LENLOC_WORD3);
22719                 bf_set(wqe_ebde_cnt, &wqe->xmit_els_rsp.wqe_com, 0);
22720
22721                 if (phba->fc_topology == LPFC_TOPOLOGY_LOOP) {
22722                         bf_set(els_rsp64_sp, &wqe->xmit_els_rsp, 1);
22723                         bf_set(els_rsp64_sid, &wqe->xmit_els_rsp,
22724                                job->vport->fc_myDID);
22725                         bf_set(wqe_ct, &wqe->xmit_els_rsp.wqe_com, 1);
22726                 }
22727
22728                 if (phba->sli_rev == LPFC_SLI_REV4) {
22729                         bf_set(wqe_rsp_temp_rpi, &wqe->xmit_els_rsp,
22730                                phba->sli4_hba.rpi_ids[ndlp->nlp_rpi]);
22731
22732                         if (bf_get(wqe_ct, &wqe->xmit_els_rsp.wqe_com))
22733                                 bf_set(wqe_ctxt_tag, &wqe->xmit_els_rsp.wqe_com,
22734                                        phba->vpi_ids[job->vport->vpi]);
22735                 }
22736                 command_type = OTHER_COMMAND;
22737                 break;
22738         case CMD_GEN_REQUEST64_WQE:
22739                 /* Word 10 */
22740                 bf_set(wqe_dbde, &wqe->gen_req.wqe_com, 1);
22741                 bf_set(wqe_iod, &wqe->gen_req.wqe_com, LPFC_WQE_IOD_READ);
22742                 bf_set(wqe_qosd, &wqe->gen_req.wqe_com, 1);
22743                 bf_set(wqe_lenloc, &wqe->gen_req.wqe_com, LPFC_WQE_LENLOC_NONE);
22744                 bf_set(wqe_ebde_cnt, &wqe->gen_req.wqe_com, 0);
22745                 command_type = OTHER_COMMAND;
22746                 break;
22747         case CMD_XMIT_SEQUENCE64_WQE:
22748                 if (phba->link_flag & LS_LOOPBACK_MODE)
22749                         bf_set(wqe_xo, &wqe->xmit_sequence.wge_ctl, 1);
22750
22751                 wqe->xmit_sequence.rsvd3 = 0;
22752                 bf_set(wqe_pu, &wqe->xmit_sequence.wqe_com, 0);
22753                 bf_set(wqe_dbde, &wqe->xmit_sequence.wqe_com, 1);
22754                 bf_set(wqe_iod, &wqe->xmit_sequence.wqe_com,
22755                        LPFC_WQE_IOD_WRITE);
22756                 bf_set(wqe_lenloc, &wqe->xmit_sequence.wqe_com,
22757                        LPFC_WQE_LENLOC_WORD12);
22758                 bf_set(wqe_ebde_cnt, &wqe->xmit_sequence.wqe_com, 0);
22759                 command_type = OTHER_COMMAND;
22760                 break;
22761         case CMD_XMIT_BLS_RSP64_WQE:
22762                 bf_set(xmit_bls_rsp64_seqcnthi, &wqe->xmit_bls_rsp, 0xffff);
22763                 bf_set(wqe_xmit_bls_pt, &wqe->xmit_bls_rsp.wqe_dest, 0x1);
22764                 bf_set(wqe_ct, &wqe->xmit_bls_rsp.wqe_com, 1);
22765                 bf_set(wqe_ctxt_tag, &wqe->xmit_bls_rsp.wqe_com,
22766                        phba->vpi_ids[phba->pport->vpi]);
22767                 bf_set(wqe_qosd, &wqe->xmit_bls_rsp.wqe_com, 1);
22768                 bf_set(wqe_lenloc, &wqe->xmit_bls_rsp.wqe_com,
22769                        LPFC_WQE_LENLOC_NONE);
22770                 /* Overwrite the pre-set comnd type with OTHER_COMMAND */
22771                 command_type = OTHER_COMMAND;
22772                 break;
22773         case CMD_FCP_ICMND64_WQE:       /* task mgmt commands */
22774         case CMD_ABORT_XRI_WQE:         /* abort iotag */
22775         case CMD_SEND_FRAME:            /* mds loopback */
22776                 /* cases already formatted for sli4 wqe - no chgs necessary */
22777                 return;
22778         default:
22779                 dump_stack();
22780                 lpfc_printf_log(phba, KERN_ERR, LOG_TRACE_EVENT,
22781                                 "6207 Invalid command 0x%x\n",
22782                                 cmnd);
22783                 break;
22784         }
22785
22786         wqe->generic.wqe_com.abort_tag = abort_tag;
22787         bf_set(wqe_reqtag, &wqe->generic.wqe_com, job->iotag);
22788         bf_set(wqe_cmd_type, &wqe->generic.wqe_com, command_type);
22789         bf_set(wqe_cqid, &wqe->generic.wqe_com, LPFC_WQE_CQ_ID_DEFAULT);
22790 }
This page took 1.364352 seconds and 4 git commands to generate.